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/exe/logsafe ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "logsafe"
5
+ require "tempfile"
6
+ require "tmpdir"
7
+
8
+ USAGE = <<~TEXT
9
+ logsafe key prints a new key
10
+ logsafe decrypt FILE | gzip -dc prints a day's file
11
+ logsafe decrypt STREAM YYYY-MM-DD PART… prints the lines of these parts of that stream and day
12
+ The key to decrypt with comes from LOGSAFE_KEY, and keys that were in use before from LOGSAFE_OLD_KEYS.
13
+ TEXT
14
+
15
+ begin
16
+ use_keys = lambda do
17
+ Logsafe.key = ENV.fetch("LOGSAFE_KEY") { abort "Set LOGSAFE_KEY to the key the logs were encrypted with." }
18
+ Logsafe.old_keys = ENV.fetch("LOGSAFE_OLD_KEYS", nil)
19
+ end
20
+ case ARGV
21
+ in ["key"]
22
+ puts Logsafe.generate_key
23
+ in ["decrypt", file]
24
+ use_keys.call
25
+ # Into a file first: nothing is printed before the whole file has been checked.
26
+ Tempfile.create("logsafe") do |gzip|
27
+ Logsafe.decrypt(file, gzip.path)
28
+ IO.copy_stream(gzip.path, $stdout)
29
+ end
30
+ in ["decrypt", stream, day, *parts] if parts.any? && day.match?(Logsafe::DATE)
31
+ use_keys.call
32
+ source = Logsafe::Source.new(stream, day, Logsafe.keys)
33
+ # Each part by itself, so that one that cannot be read, or that ends in the middle of a line, takes
34
+ # nothing from the others.
35
+ read = parts.map do |part|
36
+ Dir.mktmpdir("logsafe") do |dir|
37
+ FileUtils.cp(part, copy = File.join(dir, "part"))
38
+ source.part(copy)
39
+ IO.copy_stream(copy, $stdout)
40
+ end
41
+ rescue Logsafe::Error => e
42
+ warn "#{part}: #{e.message}"
43
+ end
44
+ exit 1 unless read.all?
45
+ else
46
+ abort USAGE
47
+ end
48
+ rescue Logsafe::Error, SystemCallError => e
49
+ abort e.message
50
+ end
@@ -0,0 +1,170 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "securerandom"
5
+
6
+ module Logsafe
7
+ # What the key seals, and how.
8
+ # A day's file is its gzip under AES-256-GCM: "logsafe1", the length (2 bytes) and text of
9
+ # "<stream>/<day>", a 12-byte nonce, what is sealed, a 16-byte tag. The name is sealed along with it,
10
+ # so that one day's file cannot pass for another's. What is sealed is the gzip, zeros up to a multiple
11
+ # of PAD, and the gzip's length in the last 8 bytes: the size of the file then says little about what
12
+ # is in it. Someone who can add lines of their own could otherwise tell from how well they compress
13
+ # whether they are like the others.
14
+ # A line the shipper sealed (shipper/vector.yaml) is "enc:" and then, in Base64, a 12-byte nonce, the
15
+ # line under ChaCha20-Poly1305 and a 16-byte tag. A line's key is not the key itself but
16
+ # HMAC-SHA256(key, "<stream>/<day>"): so few lines share a key that the shipper's random nonces are
17
+ # not expected to repeat under it.
18
+ # To open something, each key is tried in turn: the one in use first, then the old ones.
19
+ # ponytail: an old key costs one failed try per line or file it did not seal; write which key
20
+ # sealed it in front if that ever shows. GCM seals at most 64 GB per file.
21
+ module Cipher
22
+ MAGIC = "logsafe1".b
23
+ LINE = "enc:"
24
+ NONCE = 12
25
+ TAG = 16
26
+ PAD = 64 << 10
27
+ NO_KEY = "this is encrypted and Logsafe.key is not set"
28
+ NOT_OURS = "was not encrypted with this key or an old one, or has been changed"
29
+
30
+ class << self
31
+ def generate_key
32
+ SecureRandom.base64(32)
33
+ end
34
+
35
+ # The 32 bytes of a key as generate_key made it.
36
+ def key(text)
37
+ key = text.to_s.strip.unpack1("m0")
38
+ key.bytesize == 32 ? key : raise(ArgumentError)
39
+ rescue ArgumentError
40
+ raise Error, "a Logsafe key must be 32 bytes in Base64; `logsafe key` prints a new one"
41
+ end
42
+
43
+ def day_keys(keys, stream, day)
44
+ keys.map { |key| OpenSSL::HMAC.digest("SHA256", key, "#{stream}/#{day}") }
45
+ end
46
+
47
+ # Returns the path of the sealed file. name is "<stream>/<day>".
48
+ def seal(from, into, key, name)
49
+ cipher = cipher("aes-256-gcm", :encrypt, key)
50
+ File.open(into, "wb") do |out|
51
+ out << (head = head_of(name)) << cipher.random_iv
52
+ cipher.auth_data = head
53
+ File.open(from, "rb") { |file| pump(cipher, file, out, file.size) << cipher.update(padding(file.size)) }
54
+ out << cipher.final << cipher.auth_tag
55
+ end
56
+ into
57
+ end
58
+
59
+ # Returns the path of the opened file. Fails, and leaves nothing behind, unless the whole file is
60
+ # what one of the keys sealed, and under this name if one is given.
61
+ def unseal(from, into, keys, name = nil)
62
+ fit(keys, "the file #{NOT_OURS}") { |key| open_file(from, into, key, name) }
63
+ rescue Error
64
+ FileUtils.rm_f(into)
65
+ raise
66
+ end
67
+
68
+ # The text of one sealed line, given what follows LINE. Strict about the Base64: what follows its
69
+ # end would otherwise be dropped unseen.
70
+ def line(payload, keys)
71
+ fit(keys, "a line #{NOT_OURS}") do |key|
72
+ data = payload.unpack1("m0")
73
+ cipher = cipher("chacha20-poly1305", :decrypt, key, data[0, NONCE], data[-TAG..])
74
+ cipher.update(data[NONCE...-TAG]) + cipher.final
75
+ end
76
+ end
77
+
78
+ # A line sealed the way the shipper does it, without its line break.
79
+ def seal_line(text, key)
80
+ cipher = cipher("chacha20-poly1305", :encrypt, key)
81
+ nonce = cipher.random_iv
82
+ LINE + [nonce + cipher.update(text) + cipher.final + cipher.auth_tag].pack("m0")
83
+ end
84
+
85
+ # A line as it was before the shipper sealed it; a line that was never sealed, as it is.
86
+ def plain(line, keys)
87
+ line.start_with?(LINE) ? "#{line(line.delete_prefix(LINE).delete_suffix("\n"), keys)}\n" : line
88
+ end
89
+
90
+ private
91
+
92
+ # What the block gives with the first key that fits.
93
+ def fit(keys, failure)
94
+ raise Error, NO_KEY if keys.empty?
95
+
96
+ keys.each do |key|
97
+ return yield(key)
98
+ rescue OpenSSL::Cipher::CipherError, ArgumentError, TypeError
99
+ next
100
+ end
101
+ raise Error, failure
102
+ end
103
+
104
+ def open_file(from, into, key, name)
105
+ File.open(from, "rb") do |file|
106
+ head = head(file, name)
107
+ nonce = file.read(NONCE)
108
+ body = file.size - file.pos - TAG
109
+ raise ArgumentError if body < 8
110
+
111
+ cipher = cipher("aes-256-gcm", :decrypt, key, nonce, file.pread(TAG, file.size - TAG))
112
+ cipher.auth_data = head
113
+ File.open(into, "wb") { |out| pump(cipher, file, out, body) << cipher.final }
114
+ end
115
+ trim(into)
116
+ end
117
+
118
+ # What comes before the nonce.
119
+ def head_of(name)
120
+ MAGIC + [name.bytesize].pack("n") + name.b
121
+ end
122
+
123
+ def head(file, name)
124
+ magic = file.read(MAGIC.bytesize)
125
+ length = file.read(2).to_s.unpack1("n")
126
+ raise ArgumentError unless magic == MAGIC && length
127
+
128
+ found = file.read(length).to_s
129
+ raise ArgumentError unless found.bytesize == length
130
+ raise Error, "this is the file of #{found.inspect}, not of #{name}" if name && found != name.b
131
+
132
+ head_of(found)
133
+ end
134
+
135
+ def padding(size)
136
+ ("\0" * (-(size + 8) % PAD)) + [size].pack("Q>")
137
+ end
138
+
139
+ # Back to what was sealed, without its padding.
140
+ def trim(path)
141
+ File.open(path, "r+b") do |file|
142
+ size = file.pread(8, file.size - 8).unpack1("Q>")
143
+ size <= file.size - 8 ? file.truncate(size) : raise(ArgumentError)
144
+ end
145
+ path
146
+ end
147
+
148
+ # To open something, with its nonce and tag. A tag that is missing fails like one that is wrong.
149
+ def cipher(name, mode, key, nonce = nil, tag = nil)
150
+ cipher = OpenSSL::Cipher.new(name).public_send(mode)
151
+ cipher.key = key
152
+ return cipher if mode == :encrypt
153
+
154
+ cipher.iv = nonce
155
+ cipher.auth_tag = tag
156
+ cipher
157
+ end
158
+
159
+ # A megabyte at a time, so the size of the file does not matter. Returns into.
160
+ def pump(cipher, from, into, bytes)
161
+ while bytes.positive?
162
+ chunk = from.read([bytes, 1 << 20].min)
163
+ into << cipher.update(chunk)
164
+ bytes -= chunk.bytesize
165
+ end
166
+ into
167
+ end
168
+ end
169
+ end
170
+ end
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module Logsafe
6
+ # To search a day this machine needs its lines in plain text. So the day's file and its parts are
7
+ # fetched and decrypted once, into a folder only this user can read, and the copy is kept while it
8
+ # is in use: a later search fetches only what the storage has and the copy does not. A copy nobody
9
+ # used for KEEP seconds is deleted, by the next search and by a thread of this process, and every
10
+ # copy when this process ends.
11
+ # A copy knows what it holds by the names of the keys. So KEEP is shorter than the hour between two
12
+ # merges: a part that arrives late is listed for at least that hour, and a copy either sees it or
13
+ # is gone before the part is. Merges less than KEEP apart can make a copy miss such a part.
14
+ # A part that cannot be read is left out, and remembered, so that it is not fetched for every search.
15
+ # The copies take no more of the disk than they leave free: the ones not used for longest go first.
16
+ # ponytail: a new part means writing the day's copy again, about once a minute for today; and the
17
+ # lock files stay, empty, one per day searched. Parts of an hour each, if that is ever felt.
18
+ module Copies
19
+ KEEP = 30 * 60
20
+ SLICE = 1000 # keys fetched before what there is, is kept: a fetch that is cut off goes on from there
21
+ WAIT = 5 # seconds for another search that is fetching the same day
22
+ WIDTH = 16 << 10 # bytes of a line that are kept, as many as Docker has in one
23
+ BUSY = "another search is fetching these logs right now. Load the page again in a moment."
24
+ GONE = "the storage changed while it was read. Load the page again."
25
+ C = { "LC_ALL" => "C" }.freeze # bytes, not letters: the order the merge's sort gave the lines
26
+
27
+ class << self
28
+ # The path of the day's lines, sorted, after adding what the storage has and the copy does not.
29
+ # And what is not in it because it could not be read, as a text for each part.
30
+ def path(stream, day, keys)
31
+ name = Digest::SHA256.hexdigest("#{Logsafe.storage}/#{stream}/#{day}")
32
+ log = File.join(dir, "#{name}.log")
33
+ left_out = locked(name, WAIT) { refresh(Day.new(stream, day), keys, log) } || raise(Error, BUSY)
34
+ [log, left_out]
35
+ end
36
+
37
+ # Deletes what was not used for this many seconds, and what a search that was cut off left behind.
38
+ # What a search is working on is left alone.
39
+ def sweep(unused_for = KEEP)
40
+ Dir.children(dir).grep_v(/\.lock\z/).each do |name|
41
+ path = File.join(dir, name)
42
+ locked(name[/\A\h+/], 0) { FileUtils.rm_rf(path) if File.mtime(path) <= Time.now - unused_for }
43
+ rescue Errno::ENOENT
44
+ next # another process was first
45
+ end
46
+ end
47
+
48
+ # Sweeps now, and from then on without a search having to come: the last copies must not stay.
49
+ # Nor may they outlive the process: when it ends, every copy goes, and another process that
50
+ # shares the folder fetches again. A fork has no thread, but it has its parent's at_exit.
51
+ def tidy
52
+ sweep
53
+ return if @sweeper&.alive?
54
+
55
+ at_exit { sweep(0) } unless @sweeper
56
+ @sweeper = Thread.new { loop { sleep(KEEP / 6) && sweep } }
57
+ end
58
+
59
+ def dir
60
+ PrivateFolder.path("logsafe-web")
61
+ end
62
+
63
+ private
64
+
65
+ # Runs the block when nobody else is at this copy, waiting up to wait seconds for that.
66
+ # Returns what the block gave, or nothing when the copy stayed taken.
67
+ def locked(name, wait)
68
+ File.open(File.join(dir, "#{name}.lock"), File::CREAT | File::RDWR) do |lock|
69
+ give_up = Time.now + wait
70
+ until (mine = lock.flock(File::LOCK_EX | File::LOCK_NB))
71
+ break if Time.now >= give_up
72
+
73
+ sleep(0.1)
74
+ end
75
+ yield if mine
76
+ end
77
+ end
78
+
79
+ def refresh(day, keys, log)
80
+ _, list, unread = beside(log)
81
+ FileUtils.rm_f([list, unread]) unless File.exist?(log)
82
+ FileUtils.touch([list, unread])
83
+ had = File.readlines(list, chomp: true)
84
+ passing = (keys - had).each_slice(SLICE).flat_map do |slice|
85
+ again = take(day, slice, log, unread)
86
+ File.write(list, (had |= slice - again.map(&:first)).join("\n"))
87
+ again
88
+ end
89
+ FileUtils.touch([log, list, unread]) # in use
90
+ File.readlines(unread) + texts(passing)
91
+ end
92
+
93
+ # The copy, the keys that are in it, and what of them could not be read.
94
+ def beside(log)
95
+ %w[log keys unread].map { |ending| log.sub(/log\z/, ending) }
96
+ end
97
+
98
+ # Adds these keys, and writes down the ones that cannot be read. Returns the ones to try again: what
99
+ # the storage would not give now.
100
+ def take(day, keys, log, unread)
101
+ make_room
102
+ lasting, passing = add(day, keys, log).partition { |_, error| error.is_a?(Error) }
103
+ File.write(unread, texts(lasting).join, mode: "a")
104
+ passing
105
+ end
106
+
107
+ def texts(bad)
108
+ bad.map { |key, error| "#{key}: #{Day.reason(error)}\n" }
109
+ end
110
+
111
+ # A day's file is sorted as it is, and the parts are sorted here: what is left is to merge them.
112
+ # In a folder beside the copy, so that a new copy is moved into place and not written twice.
113
+ # Returns the parts that could not be read. One that the storage would not give may be gone.
114
+ def add(day, keys, log)
115
+ Dir.mktmpdir("#{File.basename(log, ".log")}.", dir) do |work|
116
+ runs, bad = runs(day, keys, work)
117
+ refused = bad.reject { |_, error| error.is_a?(Error) }
118
+ raise Error, GONE if refused.any? && gone?(refused.keys)
119
+
120
+ merge(runs + [log].select { |path| File.exist?(path) }, log)
121
+ bad
122
+ end
123
+ rescue Error
124
+ raise
125
+ rescue StandardError
126
+ raise unless gone?(keys)
127
+
128
+ raise Error, GONE
129
+ end
130
+
131
+ def runs(day, keys, work)
132
+ files, parts = keys.partition { |key| key.match?(Search::DAY_FILE) }
133
+ runs = files.map { |file| day.lines([file], Dir.mktmpdir("file", work), sorted: true).first }
134
+ sorted, bad = day.lines(parts, work) if parts.any?
135
+ [[*runs, *sorted].map { |run| narrow(run) }, bad || {}]
136
+ end
137
+
138
+ # The page shows no more of a line than this, and need not hold more of it either.
139
+ def narrow(run)
140
+ system(C, "cut", "-b", "1-#{WIDTH}", in: run, out: "#{run}.cut") || raise(Error, "cut failed")
141
+ File.delete(run)
142
+ "#{run}.cut"
143
+ end
144
+
145
+ # Moved into place at once, for a search that is reading the copy.
146
+ def merge(runs, log)
147
+ return File.rename(runs.first, log) if runs.size == 1
148
+
149
+ system(C, "sort", "-m", "-u", "-o", "#{log}.new", *runs) || raise(Error, "sort failed")
150
+ File.rename("#{log}.new", log)
151
+ end
152
+
153
+ # Deletes the copies not used for longest, until they take no more than they leave free. A copy
154
+ # that a search is adding to is left alone.
155
+ def make_room
156
+ logs = Dir.glob(File.join(dir, "*.log")).sort_by { |log| File.mtime(log) }
157
+ over = logs.sum { |log| File.size(log) } - Room.free(dir)
158
+ logs.each { |log| over -= 2 * evict(log) if over.positive? } # as much less taken, and as much more free
159
+ rescue Errno::ENOENT
160
+ nil # another process was first
161
+ end
162
+
163
+ # Returns the bytes it made free.
164
+ def evict(log)
165
+ size = File.size(log)
166
+ locked(File.basename(log, ".log"), 0) { FileUtils.rm_f(beside(log)) } ? size : 0
167
+ end
168
+
169
+ # Whether the storage no longer has one of these keys: the merge job removes the parts it has merged.
170
+ def gone?(keys)
171
+ folders = keys.map { |key| "#{File.dirname(key)}/" }.uniq
172
+ (keys - folders.flat_map { |folder| Logsafe.storage.keys(folder) }).any?
173
+ end
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module Logsafe
6
+ # The logs of one stream of one day.
7
+ class Day
8
+ class << self
9
+ # What could not be read, { part => error }, in a sentence.
10
+ def left_out(bad)
11
+ key, error = bad.first
12
+ count = bad.size == 1 ? "1 part" : "#{bad.size} parts"
13
+ "#{count} could not be read and stay where they are. The first: #{key}: #{reason(error)}"
14
+ end
15
+
16
+ def reason(error)
17
+ text = error.message.lines.first.to_s.chomp
18
+ error.is_a?(Error) ? text : "#{error.class}: #{text}"
19
+ end
20
+ end
21
+
22
+ def initialize(stream, day)
23
+ @stream = stream
24
+ @day = day
25
+ @key = Logsafe.keys.first
26
+ @source = Source.new(stream, day, Logsafe.keys)
27
+ end
28
+
29
+ # The first run writes the day's file and leaves the parts. A later run finds that the parts add
30
+ # nothing to the file, and only then removes them. So a part is never deleted on the word of the
31
+ # run that uploaded it, and two runs at the same time cannot lose a line between them.
32
+ # The day's file under its other name, from before the key was set, counts as a part:
33
+ # so a day never ends up as two files, one of them in plain text.
34
+ # A part that cannot be read stays where it is and does not hold up the others, but fails the run.
35
+ # What version the file has is asked before it is read: a run that took long, or that began with
36
+ # an older file, then cannot put it in place of one that another run has written meanwhile, whose
37
+ # parts may be gone.
38
+ def merge(parts)
39
+ file, other = names
40
+ version = Logsafe.storage.version(file)
41
+ parts += [other] if Logsafe.storage.version(other)
42
+ bad = Dir.mktmpdir("logsafe") { |dir| step(file, version, parts, dir) }
43
+ raise Error, Day.left_out(bad) if bad.any?
44
+ end
45
+
46
+ # The lines of these keys, decrypted and sorted, in a file in dir. Returns its path, and what could
47
+ # not be read as { part => error }. A day's file is in order as it is: say so, and it is not sorted again.
48
+ def lines(keys, dir, sorted: false)
49
+ bad = gather(keys, dir)
50
+ [sorted ? File.join(dir, "all") : sort(dir), bad]
51
+ end
52
+
53
+ private
54
+
55
+ # The name of the day's file, and the name it has with the key set the other way.
56
+ def names
57
+ plain = "#{@day[0, 4]}/#{@day[5, 2]}/#{@stream}.#{@day}.log.gz"
58
+ @key ? ["#{plain}.enc", plain] : [plain, "#{plain}.enc"]
59
+ end
60
+
61
+ def step(file, version, parts, dir)
62
+ bad = gather([*(file if version), *parts], dir, watch: file)
63
+ good = parts - bad.keys
64
+ return bad if good.empty?
65
+
66
+ merged = sort(dir)
67
+ if version && @text == digest(merged)
68
+ Logsafe.storage.delete(good)
69
+ else
70
+ Logsafe.storage.store(pack(merged), file, version)
71
+ end
72
+ bad
73
+ rescue Storage::Changed
74
+ bad # another run was first, and the next one goes on from what it wrote
75
+ end
76
+
77
+ # All the lines of these keys as plain text in one file. Returns the parts that could not be read.
78
+ # A day's file is not left out: the day would be written without it. Remembers what the text of the
79
+ # day's file to watch was.
80
+ # ponytail: with sort's own files this needs disk for three times a day's logs; feed sort
81
+ # through a pipe if that is ever too much.
82
+ def gather(keys, dir, watch: nil)
83
+ room = Room.new(dir)
84
+ bad = {}
85
+ failed = ->(key, error) { set_aside(key, error, bad) }
86
+ paths = Storage.fetch(Logsafe.storage, keys, dir, failed:) do |key, path|
87
+ @source.plain(key, path, room.left)
88
+ @text = digest(path) if key == watch
89
+ room.take(File.size(path))
90
+ end
91
+ join(paths, File.join(dir, "all"))
92
+ bad
93
+ end
94
+
95
+ def set_aside(key, error, bad)
96
+ raise error if !key.start_with?(PARTS) || error.is_a?(Full) || error.is_a?(Errno::ENOSPC)
97
+
98
+ bad[key] = error
99
+ end
100
+
101
+ def join(paths, into)
102
+ File.open(into, "wb") do |all|
103
+ paths.each do |path|
104
+ IO.copy_stream(path, all)
105
+ all << "\n" unless ends_with_line_break?(path) # or two lines would become one
106
+ File.delete(path) # so the sources and their lines are not both on disk
107
+ end
108
+ end
109
+ end
110
+
111
+ def ends_with_line_break?(path)
112
+ File.zero?(path) || File.open(path, "rb") { |file| file.seek(-1, IO::SEEK_END) && file.read(1) == "\n" }
113
+ end
114
+
115
+ # Every line starts with its time at a fixed width, so sorting the text sorts by time, and the
116
+ # system's sort does it on disk however large the day is. -u keeps a line that is there twice
117
+ # only once, which is what makes running again harmless.
118
+ # ponytail: two identical lines in the same nanosecond become one; number the lines in
119
+ # vector.yaml if that ever matters.
120
+ def sort(dir)
121
+ all = File.join(dir, "all")
122
+ sorted = File.join(dir, "sorted")
123
+ system({ "LC_ALL" => "C", "TMPDIR" => dir }, "sort", "-u", "-o", sorted, all) || raise(Error, "sort failed")
124
+ File.delete(all)
125
+ sorted
126
+ end
127
+
128
+ # The system's gzip and not Ruby's Zlib, here and in Source: Zlib fails with BufError when any
129
+ # child process exits while it works (seen on Ruby 4.0), and a job worker starts processes often.
130
+ def pack(path)
131
+ system("gzip", "-n", path) || raise(Error, "gzip failed")
132
+ @key ? Cipher.seal("#{path}.gz", "#{path}.gz.enc", @key, "#{@stream}/#{@day}") : "#{path}.gz"
133
+ end
134
+
135
+ def digest(path)
136
+ Digest::SHA256.file(path).hexdigest
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_job"
4
+
5
+ module Logsafe
6
+ # A plain Active Job, so whatever runs your jobs can run it: Solid Queue, Sidekiq, GoodJob, Resque, ...
7
+ # Without arguments it merges every stream; with stream names, only those.
8
+ class MergeJob < ActiveJob::Base
9
+ def perform(*streams)
10
+ Logsafe.merge(*streams)
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Logsafe
4
+ # A folder for this user alone, and not taken over from anyone else. The same one for every process
5
+ # of this user, or, when someone else was first to take that name, one for this process.
6
+ module PrivateFolder
7
+ class << self
8
+ def path(name)
9
+ usual = File.join(Dir.tmpdir, "#{name}-#{Process.uid}")
10
+ Dir.mkdir(usual, 0o700)
11
+ usual
12
+ rescue Errno::EEXIST
13
+ private?(usual) ? usual : own(name)
14
+ end
15
+
16
+ private
17
+
18
+ def private?(dir)
19
+ found = File.lstat(dir)
20
+ found.directory? && found.owned? && (found.mode & 0o077).zero?
21
+ end
22
+
23
+ def own(name)
24
+ @own = nil unless @own && File.directory?(@own)
25
+ @own ||= Dir.mktmpdir("#{name}-")
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Logsafe
4
+ # Encrypts with the key in use everything in the storage that it does not open: what an old key
5
+ # encrypted, and what was never encrypted. That is every day's file, and every line in the parts.
6
+ # What the key in use already opens is left as it is, so it can be run again. When it has run
7
+ # without failing, nothing that was in the storage is plain, or needs an old key.
8
+ # ponytail: it reads every day's file and every part each time it runs; write which key sealed a
9
+ # file in front of it if that ever takes too long.
10
+ module Reencrypt
11
+ DAY = %r{\A\d{4}/\d{2}/(#{STREAM})\.(\d{4}-\d{2}-\d{2})\.log\.gz\.enc\z}
12
+ PLAIN_DAY = %r{\A\d{4}/\d{2}/(#{STREAM})\.(\d{4}-\d{2}-\d{2})\.log\.gz\z}
13
+ ALL = Regexp.union(DAY, PLAIN_DAY, PART) # what the merge takes for a part, and nothing else under parts/
14
+
15
+ class << self
16
+ # One file that fails does not hold up the others. The block encrypts a day's plain file, given
17
+ # its stream and day.
18
+ def call(storage, key, old_keys, &encrypt_day)
19
+ failures = storage.keys("").grep(ALL).select { |name| Logsafe.stream?(stream(name)) }.filter_map do |name|
20
+ one(storage, name, [key, *old_keys], &encrypt_day)
21
+ nil
22
+ rescue StandardError => e
23
+ warn "Logsafe could not encrypt #{name}: #{e.class}: #{e.message.lines.first}"
24
+ e
25
+ end
26
+ raise failures.first if failures.any?
27
+ end
28
+
29
+ private
30
+
31
+ def stream(name)
32
+ name[PART, 1] || name[DAY, 1] || name[PLAIN_DAY, 1]
33
+ end
34
+
35
+ def one(storage, name, keys)
36
+ return plain_day(storage, name) { yield(*PLAIN_DAY.match(name).captures) } if PLAIN_DAY.match?(name)
37
+
38
+ Dir.mktmpdir("logsafe") do |dir|
39
+ version = storage.version(name) # before it is read: a merge can write the file meanwhile
40
+ storage.fetch(name, file = File.join(dir, "file"))
41
+ again = name.start_with?(PARTS) ? part(name, file, keys) : day(name, file, *keys)
42
+ storage.store(again, name, version) if again
43
+ end
44
+ end
45
+
46
+ def plain_day(storage, name)
47
+ yield
48
+ left = storage.keys("#{File.dirname(name)}/").include?(name)
49
+ raise Error, "#{name} is still there in plain text; is it in the folder of its own year and month?" if left
50
+ end
51
+
52
+ # The path of the file encrypted again, or nothing when the key in use opens it.
53
+ def day(name, file, key, *old_keys)
54
+ of = name.match(DAY).captures.join("/")
55
+ Cipher.unseal(file, "#{file}.gz", [key], of)
56
+ nil
57
+ rescue Error
58
+ raise if old_keys.empty?
59
+
60
+ Cipher.seal(Cipher.unseal(file, "#{file}.gz", old_keys, of), "#{file}.enc", key, of)
61
+ end
62
+
63
+ # The same for a part, where each line is encrypted with the key of its stream and day.
64
+ def part(name, file, keys)
65
+ key, *old_keys = Cipher.day_keys(keys, *name.match(PART).captures)
66
+ gzip = Source.gzip?(file)
67
+ Source.gunzip(file, Source::PART_LIMIT) if gzip
68
+ return unless rewrite(file, "#{file}.new") { |line| line(line, key, old_keys) }
69
+
70
+ gzip ? pack("#{file}.new") : "#{file}.new"
71
+ end
72
+
73
+ # Whether any line became another.
74
+ def rewrite(from, into)
75
+ changed = false
76
+ File.open(into, "wb") do |out|
77
+ Source.each_line(from) do |line|
78
+ again = yield(line)
79
+ changed ||= again != line
80
+ out << again
81
+ end
82
+ end
83
+ changed
84
+ end
85
+
86
+ def line(line, key, old_keys)
87
+ return seal(line.delete_suffix("\n"), key) unless line.start_with?(Cipher::LINE) # not chomp: a \r stays
88
+
89
+ Cipher.plain(line, [key])
90
+ line
91
+ rescue Error
92
+ raise if old_keys.empty?
93
+
94
+ seal(Cipher.plain(line, old_keys).delete_suffix("\n"), key)
95
+ end
96
+
97
+ def seal(text, key)
98
+ text.empty? ? "\n" : "#{Cipher.seal_line(text, key)}\n"
99
+ end
100
+
101
+ def pack(file)
102
+ system("gzip", "-n", file) || raise(Error, "gzip failed")
103
+ "#{file}.gz"
104
+ end
105
+ end
106
+ end
107
+ end