logsafe 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md ADDED
@@ -0,0 +1,654 @@
1
+ # Logsafe
2
+
3
+ Keep your logs without paying a logging service: one sorted, compressed file per day, in storage you own.
4
+
5
+ For apps that run in Docker on servers you control. The app logs to STDOUT as usual, and three pieces
6
+ do the rest:
7
+
8
+ 1. Docker writes each container's output to its normal log file on the server.
9
+ 2. [Vector](https://vector.dev), a log shipper, runs on every app server. It follows those files and
10
+ sends what is new to your storage about once a minute, as small parts.
11
+ 3. `Logsafe::MergeJob`, a background job in your Rails app, turns each finished day into a single file.
12
+
13
+ ```
14
+ my-logs/
15
+ 2026/11/shop-prod.2026-11-23.log.gz one file per stream per day
16
+ 2026/11/shop-prod.2026-11-24.log.gz
17
+ parts/shop-prod/2026-11-25/… today, not merged yet
18
+ ```
19
+
20
+ A *stream* is a name you choose, such as `shop-prod` or `shop-prod-worker`. Containers with the same
21
+ name share a file, on however many servers they run, and whatever language they are written in. Days
22
+ are UTC.
23
+
24
+ Every line gets the time Docker received it in front:
25
+
26
+ ```
27
+ 2026-11-24T10:15:02.123456789Z Started GET "/orders" for 203.0.113.7
28
+ ```
29
+
30
+ Storage can be Amazon S3 or anything that speaks its protocol (DigitalOcean Spaces, MinIO or Garage on
31
+ your own server), Google Cloud Storage, or a plain folder. The job runs on whatever runs your jobs:
32
+ Solid Queue, Sidekiq, GoodJob, Resque, or cron.
33
+
34
+ You can also [search the logs in the browser](#in-the-browser), on a page you mount in your app, and
35
+ [encrypt them](#encryption) before they leave your servers.
36
+
37
+ **Contents:** [Requirements](#requirements) · [Try it](#try-it) · [Setup](#setup) ·
38
+ [Reading the logs](#reading-the-logs) · [Lograge and other loggers](#lograge-and-other-loggers) ·
39
+ [Encryption](#encryption) · [Reference](#reference) · [What can still be lost](#what-can-still-be-lost) ·
40
+ [Good to know](#good-to-know) · [What has been run](#what-has-been-run) · [Development](#development)
41
+
42
+ ## Requirements
43
+
44
+ - Ruby 3.3 or newer, and Active Job 7.1 or newer. The page needs no Rails: any Rack app can mount it.
45
+ - Docker on the app servers, with its default `json-file` log driver.
46
+ - For storage in a bucket, the gem of that storage: `aws-sdk-s3` 1.197 or newer, or
47
+ `google-cloud-storage`. Logsafe does not install them for you.
48
+ - Where the merge job and the page run: the `sort`, `gzip`, `df`, `grep`, `awk`, `cut` and `tail`
49
+ commands, which every common Linux image has. On Alpine, add `coreutils`.
50
+
51
+ ## Try it
52
+
53
+ A look at the page on your own machine, with a folder for storage and no Vector:
54
+
55
+ ```sh
56
+ bundle add logsafe
57
+
58
+ day=$(date -u +%F)
59
+ mkdir -p tmp/logs/parts/demo/$day
60
+ echo "${day}T08:00:00.000000001Z ERROR hello" > tmp/logs/parts/demo/$day/a.log
61
+ touch -t 202601010000 tmp/logs/parts/demo/$day/a.log # a part that was just written is left alone
62
+ ```
63
+
64
+ ```ruby
65
+ # config/initializers/logsafe.rb
66
+ Logsafe.storage = Rails.root.join("tmp/logs")
67
+
68
+ # config/routes.rb
69
+ mount Logsafe::Web, at: "logsafe" if Rails.env.development?
70
+ ```
71
+
72
+ Start the app and open `/logsafe`. For your own logs, go on with Setup.
73
+
74
+ ## Setup
75
+
76
+ ### 1. Storage
77
+
78
+ **A bucket (S3-compatible or Google Cloud Storage)**
79
+
80
+ - Keep it private and turn **versioning** on, so a deleted or overwritten file can be brought back. Add
81
+ a lifecycle rule that removes old versions after a week or two.
82
+ - Use one bucket for production and another for staging. Let staging expire after a few weeks.
83
+ - Make one access key per environment for the app servers, allowed only to write under `parts/`. On
84
+ AWS:
85
+
86
+ ```json
87
+ {
88
+ "Version": "2012-10-17",
89
+ "Statement": [
90
+ { "Effect": "Allow", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::my-logs/parts/shop-prod*" }
91
+ ]
92
+ }
93
+ ```
94
+
95
+ A server that is broken into can then neither read nor delete logs. It can still add lines of its
96
+ own, under any stream the key covers.
97
+ - Make one more key for the merge job, allowed to list, read, write and delete in the bucket.
98
+
99
+ **A folder (a disk on your own server, a network share, or your own machine in development)**
100
+
101
+ - Every app server and the machine that runs the merge job must see the same folder.
102
+ - Make it so that other users of the machine cannot enter it, and give the job's user (1000 here)
103
+ rights on everything that is created in it later. Vector writes as root, and the job must be allowed
104
+ to delete what Vector wrote:
105
+
106
+ ```sh
107
+ install -d -m 750 /mnt/logs /mnt/logs/parts
108
+ setfacl -R -m u:1000:rwX -m d:u:1000:rwX -m d:o::--- /mnt/logs
109
+ ```
110
+
111
+ Run the job as that user and not as root. A server that is broken into can write to the folder, so
112
+ the job does not follow links in it; on Linux it opens each folder in a way that cannot be swapped
113
+ in between.
114
+ - Where you can, let the app servers write to `parts/` only, and not to the year folders.
115
+
116
+ ### 2. Your app's containers
117
+
118
+ Give each container a `logs` label with its stream name, tell Docker to write that label into the log
119
+ file, and limit the size of the log files. Containers without the label are not shipped.
120
+ A stream name is made of letters, digits, `.`, `_` and `-`, and starts with a letter or a digit.
121
+ Lines with any other name end up in the stream `unparsed`.
122
+
123
+ ```sh
124
+ docker run --label logs=shop-prod \
125
+ --log-opt labels=logs --log-opt max-size=50m --log-opt max-file=5 …
126
+ ```
127
+
128
+ Docker Compose:
129
+
130
+ ```yaml
131
+ services:
132
+ web:
133
+ labels: { logs: shop-prod }
134
+ logging:
135
+ options: { labels: logs, max-size: 50m, max-file: "5" }
136
+ ```
137
+
138
+ Kamal (`config/deploy.yml`):
139
+
140
+ ```yaml
141
+ logging:
142
+ options: { labels: logs, max-size: 50m, max-file: "5" }
143
+ servers:
144
+ web:
145
+ hosts: [203.0.113.10]
146
+ labels: { logs: shop-prod-web }
147
+ job:
148
+ hosts: [203.0.113.10]
149
+ cmd: bin/jobs
150
+ labels: { logs: shop-prod-worker }
151
+ ```
152
+
153
+ The app must log to STDOUT, which is what a new Rails app does in production by default.
154
+
155
+ `max-size` times `max-file` is how much each container keeps on the server. It is also how far behind
156
+ Vector can fall before lines are lost, so don't set it small.
157
+
158
+ ### 3. Vector, on every app server
159
+
160
+ The files for Vector come with the gem. `bundle info logsafe --path` prints where it is, and they are
161
+ in its `shipper/` folder. Take them from the version of the gem your app uses, and look at them again
162
+ when you update it: how Vector writes a line has to fit how the gem reads it.
163
+
164
+ Copy [shipper/vector.yaml](shipper/vector.yaml) to `/etc/vector/`, together with **one** of these, and
165
+ fill in the name of your bucket:
166
+
167
+ | Storage | File | The key |
168
+ | --- | --- | --- |
169
+ | S3-compatible | [shipper/to-s3.yaml](shipper/to-s3.yaml) | `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` in `/etc/vector/keys` |
170
+ | Google Cloud Storage | [shipper/to-gcs.yaml](shipper/to-gcs.yaml) | the service account's key file |
171
+ | Folder | [shipper/to-folder.yaml](shipper/to-folder.yaml) | none |
172
+
173
+ Copy [shipper/start](shipper/start) there too, and make the file for the keys so that only root can
174
+ read it. Keys belong in that file and not on a command line, where other users can see them:
175
+
176
+ ```sh
177
+ install -m 600 /dev/null /etc/vector/keys # then write the keys into it, one NAME=value per line
178
+ ```
179
+
180
+ Then start it. For S3-compatible storage:
181
+
182
+ ```sh
183
+ docker run -d --name vector --restart unless-stopped \
184
+ --env-file /etc/vector/keys \
185
+ -v /etc/vector:/etc/vector:ro \
186
+ -v /var/lib/docker/containers:/var/lib/docker/containers:ro \
187
+ -v vector-data:/var/lib/vector \
188
+ --entrypoint sh timberio/vector:0.62.0-alpine /etc/vector/start \
189
+ --config /etc/vector/vector.yaml --config /etc/vector/to-s3.yaml
190
+ ```
191
+
192
+ For Google Cloud Storage, name `to-gcs.yaml` and put
193
+ `GOOGLE_APPLICATION_CREDENTIALS=/etc/vector/key.json` in `/etc/vector/keys`. For a folder, name
194
+ `to-folder.yaml` and add `-v /mnt/logs/parts:/logs/parts`. `start` sees to it that other users of the
195
+ machine cannot read what Vector writes there.
196
+
197
+ Keep the `vector-data` volume: it holds Vector's position in each log file and the lines waiting to be
198
+ sent. The first time it starts, Vector also ships what is already in the log files.
199
+
200
+ **Check `docker logs vector` after the first minute.** If the bucket's name or the key is wrong, Vector
201
+ does not wait: it drops what the storage refuses. Vector's start-up health check also lists the bucket,
202
+ which a write-only key may not do; if that is the only error, set `healthcheck: { enabled: false }`
203
+ under the sink.
204
+
205
+ ### 4. The merge job, in one Rails app
206
+
207
+ ```ruby
208
+ # Gemfile
209
+ gem "logsafe"
210
+ gem "aws-sdk-s3", ">= 1.197" # for S3-compatible storage
211
+ gem "google-cloud-storage" # for Google Cloud Storage
212
+ ```
213
+
214
+ ```ruby
215
+ # config/initializers/logsafe.rb, one of:
216
+ Logsafe.storage = { s3: "my-logs", region: "eu-west-1" }
217
+ Logsafe.storage = { s3: "my-logs", region: "ams3", endpoint: "https://ams3.digitaloceanspaces.com",
218
+ access_key_id: "…", secret_access_key: "…" }
219
+ Logsafe.storage = { gcs: "my-logs", project_id: "my-project", credentials: "/path/to/key.json" }
220
+ Logsafe.storage = "/mnt/logs"
221
+ ```
222
+
223
+ What follows the bucket's name goes to `Aws::S3::Resource.new` or `Google::Cloud::Storage.new` as it
224
+ is. Without keys, each library looks where it usually does, such as `AWS_ACCESS_KEY_ID`. For storage
225
+ of another kind, give `Logsafe.storage` an object of your own; the five methods it needs are listed in
226
+ [lib/logsafe/storage.rb](lib/logsafe/storage.rb).
227
+
228
+ Then have `Logsafe::MergeJob` run **every hour**. It is a plain Active Job, so it runs on the backend
229
+ your app already uses:
230
+
231
+ ```yaml
232
+ # Solid Queue, config/recurring.yml
233
+ production:
234
+ merge_logs:
235
+ class: Logsafe::MergeJob
236
+ schedule: "30 * * * *"
237
+ ```
238
+
239
+ ```yaml
240
+ # Sidekiq with sidekiq-cron, config/schedule.yml
241
+ merge_logs:
242
+ cron: "30 * * * *"
243
+ class: Logsafe::MergeJob
244
+ ```
245
+
246
+ ```ruby
247
+ # GoodJob, config/application.rb
248
+ config.good_job.enable_cron = true
249
+ config.good_job.cron = { merge_logs: { cron: "30 * * * *", class: "Logsafe::MergeJob" } }
250
+ ```
251
+
252
+ ```
253
+ # Anything else, or no job backend at all: cron
254
+ 30 * * * * cd /app && bin/rails runner "Logsafe.merge"
255
+ ```
256
+
257
+ Why every hour: the first run after midnight UTC writes the day's file, and the run after it removes
258
+ the parts, once it has found every one of their lines in that file. A run with nothing to do only
259
+ lists the bucket.
260
+
261
+ - **Name your streams** in `config/initializers/logsafe.rb`, as they are in your containers' labels:
262
+
263
+ ```ruby
264
+ Logsafe.streams = %w[shop-prod-web shop-prod-worker]
265
+ ```
266
+
267
+ Then nothing else is merged, shown on the page or encrypted again, however many other names a server
268
+ that was broken into makes up. A stream you forget to name is not lost: its parts stay, and every
269
+ run says in the worker's log which names it left alone. Without the list, every stream is taken.
270
+ - **One app is enough.** Without arguments the job merges every stream in the storage, so one Rails app
271
+ can do it for all your apps. If several apps run the job on the same storage, give each its own
272
+ streams: `Logsafe::MergeJob.perform_later("shop-prod-web", "shop-prod-worker")`.
273
+ - **It can be run again at any time.** A run that fails deletes nothing, one day that fails does not
274
+ hold up the others, and parts that arrive late are added to their day's file. Several runs at the
275
+ same time do not lose each other's lines: a day's file is only replaced by a run that has read the
276
+ latest one. Amazon S3 and Google Cloud Storage see to that themselves, and a folder does it with a
277
+ lock. With an S3-compatible storage that does not know conditional writes, or a network share without
278
+ locks, a moment between the look and the write is left.
279
+ - **A run ends after 50 minutes** and leaves the rest to the next one. Parts of a date more than a year
280
+ ago are left alone.
281
+ - **A part that cannot be read** stays where it is. The others are merged without it, and the run
282
+ fails with its name, every hour until you have looked at it and removed it. That is a part that is
283
+ damaged, unpacks to more than 256 MB, has a line of more than 2 MB, or was encrypted with another key.
284
+ - **A line that does not start with a time of its day** gets the start of that day in front. Vector
285
+ sends no such lines. What is not under `parts/<stream>/<date>/` is left alone, and counted in the
286
+ worker's log.
287
+ - **Where it runs** it needs the `sort`, `gzip` and `df` commands, which every common Linux image has,
288
+ and free disk in the temporary folder for about four times a day's logs, uncompressed. With less
289
+ than that the day fails and nothing is changed, so that the disk is not filled.
290
+ On Alpine, add `apk add coreutils` to the image: the `sort` Alpine comes with keeps the whole day
291
+ in memory.
292
+ - **Watch that it succeeds**, the way you watch your other jobs. A merge that fails silently leaves you
293
+ with parts, not with nothing, but the parts keep piling up.
294
+
295
+ ## Reading the logs
296
+
297
+ ```sh
298
+ aws s3 cp s3://my-logs/2026/11/shop-prod.2026-11-24.log.gz - | gzip -dc | grep "OrdersController"
299
+ ```
300
+
301
+ Today's lines are still in parts:
302
+
303
+ ```sh
304
+ aws s3 cp s3://my-logs/parts/shop-prod/$(date -u +%F)/ today --recursive
305
+ gzip -dc today/* | LC_ALL=C sort | less
306
+ ```
307
+
308
+ ### In the browser
309
+
310
+ `Logsafe::Web` is a page to read and search the logs on: pick the days (today unless you say
311
+ otherwise), a stream and a level, type words, and read the lines that match, the newest at the bottom.
312
+ It reads the day's files and the parts together, so today's lines are there too, and it decrypts with
313
+ `Logsafe.key`.
314
+
315
+ It is a Rack app, so you mount it where you want it, in the app that has `Logsafe.storage` set:
316
+
317
+ ```ruby
318
+ # config/routes.rb
319
+ authenticate :user, ->(user) { user.admin? } do # Devise
320
+ namespace :admin do
321
+ mount Logsafe::Web, at: "logsafe", as: :logsafe # /admin/logsafe, admin_logsafe_path
322
+ end
323
+ end
324
+ ```
325
+
326
+ **The page does not ask who is looking, and whoever reaches it reads every log.** A `namespace :admin`
327
+ block is not enough: a mounted app does not go through your controllers, so their `before_action` does
328
+ not guard it. Without Devise, use a constraint that reads your session:
329
+
330
+ ```ruby
331
+ mount Logsafe::Web, at: "admin/logsafe",
332
+ constraints: ->(request) { User.find_by(id: request.session[:user_id])&.admin? }
333
+ ```
334
+
335
+ - **Words:** a line must hold every word you type, in any case (for the letters a to z). The first
336
+ eight words count, and the first 16 KB of a line, which is as much as Docker puts in one.
337
+ - **Level:** Docker does not know a line's level, so the page looks for the word in the line: `ERROR`,
338
+ `level=error` and `"level":"error"` are all found by "error". Lines without the word, such as the
339
+ lines of a stack trace, are not. Rails' production logger does not print the level; give it a
340
+ formatter that does, in `config/environments/production.rb`:
341
+
342
+ ```ruby
343
+ config.logger = ActiveSupport::TaggedLogging.new(Logger.new($stdout, formatter: Logger::Formatter.new))
344
+ ```
345
+ - **It shows 500 lines** at a time, with a link to the ones before. Times and days are UTC. A search
346
+ spans seven days at most, and 50 streams: with more, choose one.
347
+ - **A search from another website** is not run. Its words and days are filled in, and you press Search.
348
+ So a link to a search in a chat or a mail takes one click more. Browsers that do not say where a
349
+ request comes from (`Sec-Fetch-Site`) are not asked.
350
+ - **The first search of a day waits** while the server fetches that day: its file, or for today every
351
+ part so far. After that only new parts are fetched, and the storage is listed once a minute at
352
+ most. A very large day can take longer than a proxy in front of your app allows. What was fetched
353
+ is kept, a thousand parts at a time, so load the page again and it goes on from there. While one
354
+ search fetches a day, another search for the same day is told so and does not wait.
355
+ - **The server keeps a copy** of each day you search, in plain text, in a folder of its own in the
356
+ temporary folder, until nobody has searched that day for 30 minutes or the app stops. An app that
357
+ is killed leaves its copies there until the next search on that server. It needs the disk for those
358
+ days, uncompressed, and about four times a day's size more while it fetches one; and the `sort`,
359
+ `gzip`, `grep`, `awk`, `cut`, `tail` and `df` commands. The copies never take more than they leave
360
+ free: the ones not used for longest go first. Each server keeps its own copies: with several servers
361
+ behind a load balancer, each fetches a day the first time a search for it lands there.
362
+ - **What cannot be read is named on the page**, and the rest is shown: a part that is damaged or was
363
+ encrypted with another key, or a stream whose day's file was.
364
+ - **New lines** appear once Vector has shipped them and the storage is listed again: one to two
365
+ minutes, or up to four with a folder.
366
+ - **Run the merge job no more often than every half hour** if you use the page. A copy knows what it
367
+ holds by the names of the files. A part that arrives late for a finished day is listed for as long
368
+ as two merges are apart, and a copy that is in use all that time sees it only if that is longer
369
+ than the 30 minutes a copy can go unused.
370
+
371
+ ## Lograge and other loggers
372
+
373
+ Logsafe does not touch your app's logger. It ships what the container writes to STDOUT, so lograge,
374
+ semantic_logger, tagged logging and JSON formatters work as they are. The one thing to check is that
375
+ they write to STDOUT and not to a file.
376
+
377
+ [Lograge](https://github.com/roidrage/lograge) goes well with the page. A request is one line, so a
378
+ search shows all of it, and its fields are words you can search for:
379
+
380
+ | Lograge writes | Search for | The level "error" finds |
381
+ | --- | --- | --- |
382
+ | key=value, its default | `status=500` | nothing: the line has no level |
383
+ | key=value, with the formatter from [Level](#in-the-browser) above | `status=500` | what is logged as an error; a failed request is logged as info |
384
+ | JSON, with a `level` of its own | `"status":500` | requests that raised an error |
385
+
386
+ For the last one:
387
+
388
+ ```ruby
389
+ # config/environments/production.rb
390
+ config.lograge.enabled = true
391
+ config.lograge.formatter = Lograge::Formatters::Json.new
392
+ config.lograge.custom_options = ->(event) { { level: event.payload[:exception] ? "error" : "info" } }
393
+ ```
394
+
395
+ Words are found in the text of a line and nothing else: `status=500` also finds `status=5001`, and
396
+ there is no search by field.
397
+
398
+ ## Encryption
399
+
400
+ Without a key, whoever can read the storage can read the logs. With one, they cannot read what the
401
+ lines say: Vector encrypts every line before it leaves the server, and the merge job writes each
402
+ day's file encrypted, as `shop-prod.2026-11-24.log.gz.enc`. The names of the files, the length of each
403
+ line in a part and, to the nearest 64 KB, the size of a day's file stay visible.
404
+
405
+ Make a key once:
406
+
407
+ ```sh
408
+ bundle exec logsafe key
409
+ ```
410
+
411
+ **Keep a copy somewhere safe. Without the key nobody can read the logs, you included.**
412
+
413
+ Give the same key to both sides, the app first: an app with the key reads plain parts too, but an app
414
+ without it cannot merge what Vector has encrypted.
415
+
416
+ - **The merge job:** `Logsafe.key = ENV.fetch("LOGSAFE_KEY")` in `config/initializers/logsafe.rb`, or
417
+ take it from your Rails credentials.
418
+ - **Vector, on every app server:** add a line `LOGSAFE_KEY=…` to `/etc/vector/keys`. Copy
419
+ [shipper/start](shipper/start) and [shipper/vector.yaml](shipper/vector.yaml) again if yours are from
420
+ before there was encryption: an older `vector.yaml` ignores the key. Then remove the running
421
+ container with `docker rm -f vector` and start it again with the same `docker run` as in Setup.
422
+ Removing it loses nothing, the `vector-data` volume stays; `docker restart` is not enough, because
423
+ it does not read the key again.
424
+
425
+ **Check each server:** a minute or two later, every line in its newest parts starts with `enc:`. A
426
+ server you missed keeps sending plain text, and nothing else will tell you.
427
+
428
+ To read a day, with the key in `LOGSAFE_KEY`. `logsafe` is the gem's command: `bundle exec logsafe`
429
+ in the app, or plain `logsafe` after `gem install logsafe` on your own machine.
430
+
431
+ ```sh
432
+ aws s3 cp s3://my-logs/2026/11/shop-prod.2026-11-24.log.gz.enc day.enc
433
+ logsafe decrypt day.enc | gzip -dc | grep "OrdersController"
434
+ ```
435
+
436
+ Today's lines, from the parts, need the stream and the day as well. A part that cannot be read is
437
+ named, and the others are printed.
438
+
439
+ ```sh
440
+ aws s3 cp s3://my-logs/parts/shop-prod/$(date -u +%F)/ today --recursive
441
+ logsafe decrypt shop-prod $(date -u +%F) today/* | LC_ALL=C sort | less
442
+ ```
443
+
444
+ - **A key that is not one stops Vector from starting.** `start` checks that `LOGSAFE_KEY` is 32 bytes
445
+ in Base64 with nothing around it, such as quotes. If it is not, it says so in `docker logs vector`
446
+ and the container keeps restarting. Nothing is lost meanwhile: the lines wait in Docker's log
447
+ files. Vector itself cannot refuse a key, so started without `start` it drops every line it cannot
448
+ encrypt. With no key at all it ships plain text, and the merge accepts that.
449
+ - **You can turn it on later.** Parts from before are merged as they are, into encrypted files. A
450
+ day's file from before stays plain until you run `Logsafe::ReencryptJob.perform_later`, or
451
+ `bin/rails runner "Logsafe.reencrypt"`: that encrypts every plain day's file, and every plain line
452
+ still in the parts. Run it a few minutes after Vector has the key on every server. More about the
453
+ job under [Changing the key](#changing-the-key).
454
+ - **Parts take more room.** An encrypted line hardly compresses, so a day's parts are about as large
455
+ as its logs, uncompressed, until the day is merged. A day's file is compressed before it is
456
+ encrypted and stays small.
457
+ - **What is encrypted cannot be changed unnoticed.** `logsafe decrypt`, the page and the merge job
458
+ refuse an encrypted file or line that was changed, that another key encrypted, or that belongs to
459
+ another stream or day, and a file that is named as encrypted and is not. It promises no more than
460
+ that: someone who can write to the storage can still add plain lines of their own, remove files, or
461
+ put back an earlier version of the same day's file.
462
+ - **How well lines compress can say something about them.** Someone who can add lines and see the sizes
463
+ of the files could guess at what other lines of that day say, one merge at a time, because similar
464
+ lines compress together. Sizes are rounded to 64 KB, which makes that slow and not impossible. Keep
465
+ secrets out of the logs, encrypted or not.
466
+ - **The key is on every app server.** A server that is broken into has it, and with it can read
467
+ whatever of the storage it can reach. Keep the server's storage key write-only, as in Setup.
468
+ - **One storage, one key.** Every app that merges in this storage needs the same key, and the job
469
+ that encrypts what is already there takes everything in it, whichever app's streams they are, unless
470
+ `Logsafe.streams` names the ones that are yours.
471
+ - **Earlier versions stay as they were.** If the bucket keeps versions, as Setup recommends, then
472
+ whatever was replaced or removed is still there as an earlier version, in plain text or under an
473
+ old key, until your lifecycle rule removes it. Remove those versions yourself if the plain text
474
+ must go, or if an old key has leaked.
475
+ - **Where the logs are still readable:** on the app servers, in Docker's log files, in the merge
476
+ job's temporary folder while it works, and, if you use the page in the browser, in its copies of
477
+ the days that were searched in the last 30 minutes.
478
+
479
+ The formats are described in [lib/logsafe/cipher.rb](lib/logsafe/cipher.rb): AES-256-GCM for a day's
480
+ file, ChaCha20-Poly1305 for a line.
481
+
482
+ ### Changing the key
483
+
484
+ 1. Make a new key with `logsafe key`.
485
+ 2. In the app, make it the key and keep the old one beside it:
486
+
487
+ ```ruby
488
+ Logsafe.key = ENV.fetch("LOGSAFE_KEY")
489
+ Logsafe.old_keys = ENV["LOGSAFE_OLD_KEYS"] # one key, or several with commas between them
490
+ ```
491
+
492
+ From now on everything is read with either key and written with the new one.
493
+ 3. Give Vector the new key on every app server: change `LOGSAFE_KEY`, then remove the container and
494
+ run it again, as when you turned encryption on. `docker restart` would keep the old key.
495
+ 4. Five minutes later, run `Logsafe::ReencryptJob.perform_later`, or
496
+ `bin/rails runner "Logsafe.reencrypt"`. It encrypts with the new key every day's file and every
497
+ line in the parts that the new key does not open: what the old key encrypted, and what was never
498
+ encrypted. The wait is for what Vector had already encrypted with the old key, which it sends
499
+ within a minute, and for a folder, where a part is left alone for two minutes.
500
+ 5. When it has succeeded, take the old key out of `Logsafe.old_keys`. The runner has succeeded when
501
+ it ends without an error; the job, when your job backend shows it finished and not failed. The
502
+ current files in the storage need the old key no more. Keep your own copy of it until a few days
503
+ of merges have succeeded, and until the earlier versions in the bucket are gone.
504
+
505
+ - **The job reads everything in the storage**, so it takes a while on a large archive. It can be run
506
+ again at any time: what the new key already opens is left as it is. A file that fails does not
507
+ hold up the others; the job names it on STDERR, in the worker's log, and fails at the end.
508
+ - **A day's plain file is removed only after a check.** The job writes the encrypted file, reads it
509
+ back from the storage, and removes the plain one once every line of it is found there.
510
+ - **A line can still arrive under the old key** after the job has run: from a server you had not
511
+ given the new key yet, or from lines Vector was holding while the storage was down. Nothing is
512
+ lost. The merge of that day says so and fails, and those parts stay until the old key is back in
513
+ `Logsafe.old_keys` and the merge has run again.
514
+ - **`logsafe decrypt`** takes old keys from `LOGSAFE_OLD_KEYS`.
515
+
516
+ ## Reference
517
+
518
+ What is listed here is what you can count on from one patch version to the next. Until 1.0 a minor
519
+ version can change it, and [CHANGELOG.md](CHANGELOG.md) says so. Everything else in the gem is for its
520
+ own use.
521
+
522
+ ### Settings
523
+
524
+ Set them in `config/initializers/logsafe.rb`. None is read from the environment by itself.
525
+
526
+ | Setting | What it takes | Without it |
527
+ | --- | --- | --- |
528
+ | `Logsafe.storage` | a path, `{ folder: path }`, `{ s3: bucket, … }`, `{ gcs: bucket, … }` or [an object of your own](#storage-of-your-own) | nothing works |
529
+ | `Logsafe.streams` | the names of the streams that are merged, shown and encrypted again | every stream |
530
+ | `Logsafe.key` | a key from `logsafe key` | nothing is encrypted, and what is cannot be read |
531
+ | `Logsafe.old_keys` | keys that were in use before: a list, or one text with commas between them | only `Logsafe.key` reads |
532
+
533
+ ### Jobs and methods
534
+
535
+ | Job | The same, without a job | What it does |
536
+ | --- | --- | --- |
537
+ | `Logsafe::MergeJob.perform_later(*streams)` | `Logsafe.merge(*streams)` | Merges the finished days of these streams, or of all. Run it every hour. |
538
+ | `Logsafe::ReencryptJob.perform_later` | `Logsafe.reencrypt` | Encrypts with the key in use what is plain or under an old key. Run it after the key was set or changed. |
539
+ | | `Logsafe.generate_key` | A new key, as `logsafe key` prints it. |
540
+ | | `Logsafe.decrypt(from, into)` | Writes the gzip of a day's encrypted file to a path. |
541
+
542
+ `Logsafe::Web` is a Rack app and takes no settings. What Logsafe itself refuses is a `Logsafe::Error`;
543
+ what a storage raises, such as a network error, is passed on as it is.
544
+
545
+ ### The command line
546
+
547
+ | Command | What it does |
548
+ | --- | --- |
549
+ | `logsafe key` | Prints a new key. |
550
+ | `logsafe decrypt FILE` | Prints a day's file as gzip. |
551
+ | `logsafe decrypt STREAM YYYY-MM-DD PART…` | Prints the lines of these parts, of that stream and day. |
552
+
553
+ The keys come from `LOGSAFE_KEY` and `LOGSAFE_OLD_KEYS`. It needs neither Rails nor a storage.
554
+
555
+ ### Storage of your own
556
+
557
+ Any object with these five methods can be `Logsafe.storage`. What each has to promise is written in
558
+ [lib/logsafe/storage.rb](lib/logsafe/storage.rb), and `Logsafe::Storage::GCS` there is a short example.
559
+
560
+ | Method | What it does |
561
+ | --- | --- |
562
+ | `keys(prefix)` | The keys that start with the prefix. |
563
+ | `fetch(key, path)` | Copies a key's content to a local file. Several threads call it at once. |
564
+ | `version(key)` | What tells the content the key has now from any other, or nil when there is none. |
565
+ | `store(path, key, was)` | Copies a local file to the key if it still has the version `was`, and otherwise raises `Logsafe::Storage::Changed.new(key)`. |
566
+ | `delete(keys)` | Removes them. One that is gone already is no failure. |
567
+
568
+ Give it a `to_s` that says which storage it is, so that the page keeps two of them apart.
569
+
570
+ ## What can still be lost
571
+
572
+ | What happens | What is lost |
573
+ | --- | --- |
574
+ | The app crashes or is killed | Nothing. A line written to STDOUT has already left the process. |
575
+ | The network or the storage is down | Nothing, for as long as it fits on the server: 1 GB in Vector's buffer, then Docker's own log files up to their limit. |
576
+ | The merge job or the job backend is down | Nothing. The parts wait. |
577
+ | The server loses power | The last few seconds, which the system had not yet written to disk. |
578
+ | The server's disk is destroyed | What was not sent yet: up to a minute. |
579
+ | A container is removed (`docker rm`, `--rm`, a deploy tidying up) | Its log file goes with it. Normally Vector has read all but the last second or less. If Vector was down, everything it had not read from that container. |
580
+ | Vector is down for a long time | Lines that Docker's rotation (`max-size` × `max-file`) removed meanwhile. |
581
+ | The bucket's name or the key is wrong | What Vector tried to send meanwhile. While the lines are still in Docker's log files you can get them back: correct the setting, remove the `vector-data` volume and start Vector again. It ships everything again, and the merge drops what it already has. |
582
+ | A file in the bucket is deleted or overwritten | Nothing, with versioning on. |
583
+
584
+ So watch that Vector is running and not logging errors, not only that the merge succeeds.
585
+
586
+ Nothing can promise that no line is ever lost without making the app wait for each line to be stored.
587
+ What must never be lost, such as an audit trail, belongs in your database, saved together with the
588
+ change it describes.
589
+
590
+ ## Good to know
591
+
592
+ - **One file per day** holds once the day is over and two merges have run. During the day there are
593
+ parts.
594
+ - **Order** is the time Docker received each line, to the nanosecond, across containers and servers.
595
+ It is as good as the servers' clocks; keep them synchronised (NTP).
596
+ - **A line sent twice is kept once.** Vector can send a batch twice after a failure; the merge drops
597
+ the copy. The cost: two identical lines with the same nanosecond time become one.
598
+ - **Lines over 16 KB** are cut into pieces by Docker, and stay in pieces.
599
+ - **A line Vector can't read** as Docker's format is kept under the stream `unparsed`.
600
+ - **In a folder** the parts are plain text, a new file per server every minute, and the job leaves a
601
+ part alone until it has not changed for two minutes.
602
+ - **A copy on a local disk:** point `aws s3 sync` or `rclone` at the year folders from the machine that
603
+ has the disk.
604
+ - **Personal data:** keep passwords, tokens and personal data out of logs (`filter_parameters` in
605
+ Rails), and decide how long production logs are kept.
606
+
607
+ ## What has been run
608
+
609
+ `shipper/test` runs every check on one machine with Docker:
610
+
611
+ - The whole path, for an S3 stand-in and for a folder: labelled containers write, Docker rotates a log
612
+ file, Vector is restarted on the way, and the merge must end with one complete, sorted file.
613
+ - The S3 and Google Cloud Storage code against local stand-ins.
614
+ - Vector's own tests of how lines are rewritten, and the validity of all three storage files.
615
+ - The whole path once more with a key, for the S3 stand-in: the parts hold only encrypted lines, and
616
+ the merge job opens what Vector encrypted.
617
+ - `shipper/start` with keys that are not keys, with a key and with none.
618
+
619
+ `bundle exec rake` runs the part that needs no Docker: order, duplicates, late parts, a run that
620
+ fails, today left alone, encryption with a right, a wrong and a missing key, a change of key with
621
+ everything encrypted again, plain files and lines encrypted afterwards, the jobs through Active
622
+ Job, and the page in the browser as a Rack app: its searches, an address that was made up, a fetch
623
+ that is cut off, a part that is removed meanwhile, two searches for one day, and the removal of its
624
+ copies. And what someone could do who may write parts, or to the storage: parts that unpack to very
625
+ much or cannot be read, lines of another day, streams and dates that were made up, links in a folder,
626
+ encrypted files that were swapped, and searches that another website starts. Several runs at the same
627
+ time, with each kind of storage.
628
+
629
+ By hand, with the built gem installed: the page mounted in a Rails app, in a namespace and behind the
630
+ session constraint above, and the merge through Active Job, on Rails 7.1 with Ruby 3.3 and on Rails 8.1
631
+ with Ruby 4.0. What the page finds of lograge's lines, on Rails 8.1.
632
+
633
+ Not run: the Devise example; real AWS, Google or DigitalOcean storage; Vector sending to Google Cloud Storage (the stand-in
634
+ refuses the kind of upload Vector makes); Kamal; the scheduling examples above, which follow each
635
+ tool's documentation; more than one server; long outages; folder permissions on Linux.
636
+
637
+ ## Development
638
+
639
+ ```sh
640
+ bin/setup # installs what is needed
641
+ bundle exec rake # specs and RuboCop
642
+ shipper/test # the same specs and the ones that need Docker: run this after a change to shipper/ or storage
643
+ ```
644
+
645
+ Bug reports and pull requests are welcome on [GitHub](https://github.com/TTD93/LogSafe). Please don't
646
+ paste real log lines or keys into an issue.
647
+
648
+ To publish a version: set it in `lib/logsafe/version.rb`, run `bundle install`, name it with its date in
649
+ [CHANGELOG.md](CHANGELOG.md), merge to `master`, wait for CI, and run `bundle exec rake release` there.
650
+ That builds the gem, pushes the tag, and pushes the gem to RubyGems, which asks for a second factor.
651
+
652
+ ## License
653
+
654
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).