redu-sandbox-sdk 0.1.1
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.
- checksums.yaml +7 -0
- data/LICENSE +202 -0
- data/README.md +82 -0
- data/docs/reference.md +865 -0
- data/lib/redu_sandbox/audit.rb +525 -0
- data/lib/redu_sandbox/client.rb +59 -0
- data/lib/redu_sandbox/errors.rb +230 -0
- data/lib/redu_sandbox/http.rb +326 -0
- data/lib/redu_sandbox/sandboxes.rb +1947 -0
- data/lib/redu_sandbox/types.rb +1154 -0
- data/lib/redu_sandbox/version.rb +5 -0
- data/lib/redu_sandbox.rb +23 -0
- data/redu-sandbox-sdk.gemspec +27 -0
- metadata +63 -0
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
|
|
5
|
+
module ReduSandbox
|
|
6
|
+
# The JSON of an audit log's answer (GET /v1/sandboxes/:id/audit), read here rather than by JSON.parse because each
|
|
7
|
+
# record is hashed as the sandbox service wrote it: every value keeps the text it spans, a whole number of any size
|
|
8
|
+
# stays exact, 12.0 stays a float, and a string holding a lone surrogate (which a program in the sandbox can put in a
|
|
9
|
+
# record it reports) is read rather than refused. Strict JSON otherwise: no NaN, no trailing comma, no comment.
|
|
10
|
+
module AuditJson
|
|
11
|
+
# One value of a JSON text: +type+ (:object, :array, :string, :number, :true, :false or :null), the bytes it
|
|
12
|
+
# spans (+from+ up to +to+), and +value+: an object's [key, Node] pairs in their order, an array's Nodes, a string's
|
|
13
|
+
# characters as UTF-8 (a lone surrogate as its own three bytes), a number's text.
|
|
14
|
+
Node = Struct.new(:type, :from, :to, :value)
|
|
15
|
+
|
|
16
|
+
# A text that is not JSON this reader takes.
|
|
17
|
+
class Invalid < StandardError; end
|
|
18
|
+
|
|
19
|
+
# The deepest nesting read: the sandbox service's own JSON (Python's) cannot write a record nested near this deep.
|
|
20
|
+
MAX_DEPTH = 1000
|
|
21
|
+
NUMBER = /\G-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?/n
|
|
22
|
+
HEX4 = /\G[0-9a-fA-F]{4}/n
|
|
23
|
+
ESCAPES = { 0x22 => 0x22, 0x5C => 0x5C, 0x2F => 0x2F, 0x62 => 0x08, 0x66 => 0x0C, 0x6E => 0x0A, 0x72 => 0x0D,
|
|
24
|
+
0x74 => 0x09 }.freeze
|
|
25
|
+
# How Python's json.dumps (ensure_ascii) writes the characters it does not write as they are.
|
|
26
|
+
SHORT = { 0x22 => '\\"', 0x5C => "\\\\", 0x08 => "\\b", 0x0C => "\\f", 0x0A => "\\n", 0x0D => "\\r",
|
|
27
|
+
0x09 => "\\t" }.freeze
|
|
28
|
+
|
|
29
|
+
module_function
|
|
30
|
+
|
|
31
|
+
# The Node of a whole JSON text (one value, with white space around it), or Invalid.
|
|
32
|
+
def parse(text)
|
|
33
|
+
r = Reader.new(text.b)
|
|
34
|
+
node = r.value(0)
|
|
35
|
+
r.space
|
|
36
|
+
raise Invalid, "text after the JSON value, at byte #{r.pos}" unless r.done?
|
|
37
|
+
|
|
38
|
+
node
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# A Node as Ruby values: a Hash with String keys (a key given twice keeps its last value, as Python's json does),
|
|
42
|
+
# an Array, a String, an Integer of any size, a Float, true, false or nil.
|
|
43
|
+
def native(node)
|
|
44
|
+
case node.type
|
|
45
|
+
when :object then node.value.to_h { |k, v| [k, native(v)] }
|
|
46
|
+
when :array then node.value.map { |v| native(v) }
|
|
47
|
+
when :string then node.value
|
|
48
|
+
when :number then float?(node.value) ? to_float(node.value) : Integer(node.value, 10)
|
|
49
|
+
when :true then true
|
|
50
|
+
when :false then false
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# The text the chain hashes: the value as Python's json.dumps(value, sort_keys=True, separators=(",", ":")) writes
|
|
55
|
+
# it, leaving out the object's own key +without+ (keys sorted by code point at every level, no white space, ASCII
|
|
56
|
+
# only, floats as Python writes them).
|
|
57
|
+
def canonical(node, without: nil, out: +"")
|
|
58
|
+
case node.type
|
|
59
|
+
when :object
|
|
60
|
+
fields = {}
|
|
61
|
+
node.value.each { |k, v| fields[k] = v unless k == without }
|
|
62
|
+
out << "{"
|
|
63
|
+
fields.keys.sort.each_with_index do |k, i|
|
|
64
|
+
out << "," if i.positive?
|
|
65
|
+
string(k, out) << ":"
|
|
66
|
+
canonical(fields[k], out: out)
|
|
67
|
+
end
|
|
68
|
+
out << "}"
|
|
69
|
+
when :array
|
|
70
|
+
out << "["
|
|
71
|
+
node.value.each_with_index do |v, i|
|
|
72
|
+
out << "," if i.positive?
|
|
73
|
+
canonical(v, out: out)
|
|
74
|
+
end
|
|
75
|
+
out << "]"
|
|
76
|
+
when :string then string(node.value, out)
|
|
77
|
+
when :number then out << number(node.value)
|
|
78
|
+
else out << node.type.to_s
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def float?(text)
|
|
83
|
+
text.match?(/[.eE]/)
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# A JSON number as Python writes the value json.loads reads from it: a whole number's digits (0 for -0), or the
|
|
87
|
+
# float's repr (Infinity past the largest float).
|
|
88
|
+
def number(text)
|
|
89
|
+
return text == "-0" ? "0" : text unless float?(text)
|
|
90
|
+
|
|
91
|
+
python_float(to_float(text))
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# The float a JSON number reads as (as Python's float() reads it: the nearest, infinite past the largest float, 0
|
|
95
|
+
# below the smallest), without Ruby's warning for a number far out of range.
|
|
96
|
+
def to_float(text)
|
|
97
|
+
m = /\A(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([-+]?[0-9]+))?\z/.match(text)
|
|
98
|
+
digits = m[2] + m[3].to_s
|
|
99
|
+
first = digits.index(/[1-9]/)
|
|
100
|
+
return m[1] == "-" ? -0.0 : 0.0 if first.nil?
|
|
101
|
+
|
|
102
|
+
power = m[2].length - 1 - first + m[4].to_i
|
|
103
|
+
return m[1] == "-" ? -Float::INFINITY : Float::INFINITY if power > 309
|
|
104
|
+
return m[1] == "-" ? -0.0 : 0.0 if power < -325
|
|
105
|
+
|
|
106
|
+
Float(text)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# Python's repr of a float: its shortest digits that read back as the same float, in fixed notation from 1e-4 up
|
|
110
|
+
# to below 1e16 (with ".0" for a whole number), in exponent notation (1e+16, 2.5e-07) outside.
|
|
111
|
+
def python_float(f)
|
|
112
|
+
return "NaN" if f.nan?
|
|
113
|
+
return f.positive? ? "Infinity" : "-Infinity" if f.infinite?
|
|
114
|
+
return (1.0 / f).negative? ? "-0.0" : "0.0" if f.zero?
|
|
115
|
+
|
|
116
|
+
digits, point = shortest(f.abs)
|
|
117
|
+
n = digits.length
|
|
118
|
+
text =
|
|
119
|
+
if point <= -4 || point > 16
|
|
120
|
+
exp = point - 1
|
|
121
|
+
"#{n == 1 ? digits : "#{digits[0]}.#{digits[1..]}"}e#{exp.negative? ? "-" : "+"}#{format("%02d", exp.abs)}"
|
|
122
|
+
elsif point <= 0
|
|
123
|
+
"0.#{"0" * -point}#{digits}"
|
|
124
|
+
elsif point >= n
|
|
125
|
+
"#{digits}#{"0" * (point - n)}.0"
|
|
126
|
+
else
|
|
127
|
+
"#{digits[0, point]}.#{digits[point..]}"
|
|
128
|
+
end
|
|
129
|
+
f.negative? ? "-#{text}" : text
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
# The shortest digits of a positive float and where its point goes (the value is 0.DIGITS times 10**point), from
|
|
133
|
+
# Float#to_s, which writes them with the same algorithm as Python's repr (David Gay's, shortest mode).
|
|
134
|
+
def shortest(f)
|
|
135
|
+
mantissa, exp = f.to_s.split("e")
|
|
136
|
+
int, frac = mantissa.split(".")
|
|
137
|
+
digits = int + frac.to_s
|
|
138
|
+
point = int.length + exp.to_i
|
|
139
|
+
lead = digits[/\A0*/].length
|
|
140
|
+
[digits[lead..].sub(/0+\z/, ""), point - lead]
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# A string as Python's json.dumps writes it with ensure_ascii: \" \\ \b \f \n \r \t, space to ~ as they are, every
|
|
144
|
+
# other character as \uXXXX in lowercase hex (two of them, a surrogate pair, past U+FFFF).
|
|
145
|
+
def string(s, out)
|
|
146
|
+
out << '"'
|
|
147
|
+
i = 0
|
|
148
|
+
n = s.bytesize
|
|
149
|
+
while i < n
|
|
150
|
+
c = s.getbyte(i)
|
|
151
|
+
if c < 0x80
|
|
152
|
+
cp = c
|
|
153
|
+
i += 1
|
|
154
|
+
elsif c >= 0xF0
|
|
155
|
+
cp = ((c & 0x07) << 18) | ((s.getbyte(i + 1) & 0x3F) << 12) | ((s.getbyte(i + 2) & 0x3F) << 6) |
|
|
156
|
+
(s.getbyte(i + 3) & 0x3F)
|
|
157
|
+
i += 4
|
|
158
|
+
elsif c >= 0xE0
|
|
159
|
+
cp = ((c & 0x0F) << 12) | ((s.getbyte(i + 1) & 0x3F) << 6) | (s.getbyte(i + 2) & 0x3F)
|
|
160
|
+
i += 3
|
|
161
|
+
else
|
|
162
|
+
cp = ((c & 0x1F) << 6) | (s.getbyte(i + 1) & 0x3F)
|
|
163
|
+
i += 2
|
|
164
|
+
end
|
|
165
|
+
if SHORT.key?(cp)
|
|
166
|
+
out << SHORT[cp]
|
|
167
|
+
elsif cp >= 0x20 && cp <= 0x7E
|
|
168
|
+
out << cp
|
|
169
|
+
elsif cp > 0xFFFF
|
|
170
|
+
v = cp - 0x10000
|
|
171
|
+
out << format("\\u%04x\\u%04x", 0xD800 + (v >> 10), 0xDC00 + (v & 0x3FF))
|
|
172
|
+
else
|
|
173
|
+
out << format("\\u%04x", cp)
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
out << '"'
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# A reader of one JSON text, byte by byte.
|
|
180
|
+
class Reader
|
|
181
|
+
attr_reader :pos
|
|
182
|
+
|
|
183
|
+
def initialize(bytes)
|
|
184
|
+
@s = bytes
|
|
185
|
+
@pos = 0
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def done?
|
|
189
|
+
@pos == @s.bytesize
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
def space
|
|
193
|
+
@pos += 1 while [0x20, 0x09, 0x0A, 0x0D].include?(@s.getbyte(@pos))
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
def value(depth)
|
|
197
|
+
raise Invalid, "nested deeper than #{MAX_DEPTH}" if depth > MAX_DEPTH
|
|
198
|
+
|
|
199
|
+
space
|
|
200
|
+
from = @pos
|
|
201
|
+
case @s.getbyte(@pos)
|
|
202
|
+
when 0x7B then object(from, depth)
|
|
203
|
+
when 0x5B then array(from, depth)
|
|
204
|
+
when 0x22 then Node.new(:string, from, nil, string).tap { |n| n.to = @pos }
|
|
205
|
+
when 0x74 then word("true", :true, from)
|
|
206
|
+
when 0x66 then word("false", :false, from)
|
|
207
|
+
when 0x6E then word("null", :null, from)
|
|
208
|
+
else
|
|
209
|
+
m = NUMBER.match(@s, @pos)
|
|
210
|
+
raise Invalid, "no JSON value at byte #{@pos}" if m.nil? || m[0].empty?
|
|
211
|
+
|
|
212
|
+
@pos += m[0].bytesize
|
|
213
|
+
Node.new(:number, from, @pos, m[0].dup.force_encoding(Encoding::UTF_8))
|
|
214
|
+
end
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
private
|
|
218
|
+
|
|
219
|
+
def object(from, depth)
|
|
220
|
+
@pos += 1
|
|
221
|
+
pairs = []
|
|
222
|
+
space
|
|
223
|
+
if @s.getbyte(@pos) == 0x7D
|
|
224
|
+
@pos += 1
|
|
225
|
+
return Node.new(:object, from, @pos, pairs)
|
|
226
|
+
end
|
|
227
|
+
loop do
|
|
228
|
+
space
|
|
229
|
+
raise Invalid, "an object key must be a string, at byte #{@pos}" unless @s.getbyte(@pos) == 0x22
|
|
230
|
+
|
|
231
|
+
key = string
|
|
232
|
+
space
|
|
233
|
+
expect(0x3A, ":")
|
|
234
|
+
pairs << [key, value(depth + 1)]
|
|
235
|
+
space
|
|
236
|
+
c = @s.getbyte(@pos)
|
|
237
|
+
@pos += 1
|
|
238
|
+
return Node.new(:object, from, @pos, pairs) if c == 0x7D
|
|
239
|
+
raise Invalid, "expected , or } at byte #{@pos - 1}" unless c == 0x2C
|
|
240
|
+
end
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
def array(from, depth)
|
|
244
|
+
@pos += 1
|
|
245
|
+
items = []
|
|
246
|
+
space
|
|
247
|
+
if @s.getbyte(@pos) == 0x5D
|
|
248
|
+
@pos += 1
|
|
249
|
+
return Node.new(:array, from, @pos, items)
|
|
250
|
+
end
|
|
251
|
+
loop do
|
|
252
|
+
items << value(depth + 1)
|
|
253
|
+
space
|
|
254
|
+
c = @s.getbyte(@pos)
|
|
255
|
+
@pos += 1
|
|
256
|
+
return Node.new(:array, from, @pos, items) if c == 0x5D
|
|
257
|
+
raise Invalid, "expected , or ] at byte #{@pos - 1}" unless c == 0x2C
|
|
258
|
+
end
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
def word(text, type, from)
|
|
262
|
+
raise Invalid, "no JSON value at byte #{@pos}" unless @s.byteslice(@pos, text.length) == text
|
|
263
|
+
|
|
264
|
+
@pos += text.length
|
|
265
|
+
Node.new(type, from, @pos, nil)
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
def expect(byte, what)
|
|
269
|
+
raise Invalid, "expected #{what} at byte #{@pos}" unless @s.getbyte(@pos) == byte
|
|
270
|
+
|
|
271
|
+
@pos += 1
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
# A string's characters as UTF-8, its escapes read as Python's json reads them: a \u escape of a high surrogate
|
|
275
|
+
# followed by one of a low surrogate is one character; any other surrogate stays a character of its own.
|
|
276
|
+
def string
|
|
277
|
+
out = "".b
|
|
278
|
+
@pos += 1
|
|
279
|
+
loop do
|
|
280
|
+
c = @s.getbyte(@pos)
|
|
281
|
+
raise Invalid, "a string that does not end" if c.nil?
|
|
282
|
+
|
|
283
|
+
if c == 0x22
|
|
284
|
+
@pos += 1
|
|
285
|
+
return out.force_encoding(Encoding::UTF_8)
|
|
286
|
+
elsif c == 0x5C
|
|
287
|
+
escape(out)
|
|
288
|
+
elsif c < 0x20
|
|
289
|
+
raise Invalid, "a control character in a string, at byte #{@pos}"
|
|
290
|
+
elsif c < 0x80
|
|
291
|
+
out << c
|
|
292
|
+
@pos += 1
|
|
293
|
+
else
|
|
294
|
+
utf8(out, c)
|
|
295
|
+
end
|
|
296
|
+
end
|
|
297
|
+
end
|
|
298
|
+
|
|
299
|
+
def escape(out)
|
|
300
|
+
e = @s.getbyte(@pos + 1)
|
|
301
|
+
if ESCAPES.key?(e)
|
|
302
|
+
out << ESCAPES[e]
|
|
303
|
+
@pos += 2
|
|
304
|
+
return
|
|
305
|
+
end
|
|
306
|
+
raise Invalid, "a bad escape at byte #{@pos}" unless e == 0x75
|
|
307
|
+
|
|
308
|
+
cp = hex4(@pos + 2)
|
|
309
|
+
@pos += 6
|
|
310
|
+
if cp.between?(0xD800, 0xDBFF) && @s.getbyte(@pos) == 0x5C && @s.getbyte(@pos + 1) == 0x75
|
|
311
|
+
low = hex4(@pos + 2)
|
|
312
|
+
if low.between?(0xDC00, 0xDFFF)
|
|
313
|
+
cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00)
|
|
314
|
+
@pos += 6
|
|
315
|
+
end
|
|
316
|
+
end
|
|
317
|
+
out << [cp].pack("U").b
|
|
318
|
+
end
|
|
319
|
+
|
|
320
|
+
def hex4(at)
|
|
321
|
+
m = HEX4.match(@s, at)
|
|
322
|
+
raise Invalid, "a bad \\u escape at byte #{at - 2}" if m.nil?
|
|
323
|
+
|
|
324
|
+
m[0].hex
|
|
325
|
+
end
|
|
326
|
+
|
|
327
|
+
# One character written as UTF-8 in the text itself: checked (no overlong form, no surrogate, at most U+10FFFF).
|
|
328
|
+
def utf8(out, c)
|
|
329
|
+
n, least = if c.between?(0xC2, 0xDF) then [2, 0x80]
|
|
330
|
+
elsif c.between?(0xE0, 0xEF) then [3, 0x800]
|
|
331
|
+
elsif c.between?(0xF0, 0xF4) then [4, 0x10000]
|
|
332
|
+
else raise Invalid, "text that is not UTF-8, at byte #{@pos}"
|
|
333
|
+
end
|
|
334
|
+
bytes = @s.byteslice(@pos, n)
|
|
335
|
+
rest = bytes.bytes.drop(1)
|
|
336
|
+
raise Invalid, "text that is not UTF-8, at byte #{@pos}" unless rest.length == n - 1 && rest.all? { |b| b & 0xC0 == 0x80 }
|
|
337
|
+
|
|
338
|
+
cp = rest.reduce(c & (0xFF >> (n + 1))) { |a, b| (a << 6) | (b & 0x3F) }
|
|
339
|
+
raise Invalid, "text that is not UTF-8, at byte #{@pos}" if cp < least || cp > 0x10FFFF || cp.between?(0xD800, 0xDFFF)
|
|
340
|
+
|
|
341
|
+
out << bytes
|
|
342
|
+
@pos += n
|
|
343
|
+
end
|
|
344
|
+
end
|
|
345
|
+
end
|
|
346
|
+
|
|
347
|
+
# A break in an audit log's hash chain, at the first record where it does not hold: +seq+ is that record's, and
|
|
348
|
+
# +reason+ says what failed: :seq (its seq does not follow the record before), :prev (its prev is not the h of the
|
|
349
|
+
# record before), :hash (its h is not the SHA-256 of its text) or :unreadable (its text is not a record, or a
|
|
350
|
+
# withheld record carries no h to go on from).
|
|
351
|
+
class AuditChainError < StandardError
|
|
352
|
+
attr_reader :seq, :reason
|
|
353
|
+
|
|
354
|
+
def initialize(seq, reason, message)
|
|
355
|
+
super(message)
|
|
356
|
+
@seq = seq
|
|
357
|
+
@reason = reason
|
|
358
|
+
end
|
|
359
|
+
end
|
|
360
|
+
|
|
361
|
+
# A check of a sandbox's audit log's hash chain, exactly as redu describes it (GET /v1/capabilities, sandboxes
|
|
362
|
+
# audit_log): seq counts 1, 2, 3 without gaps; prev is the h of the record before, 64 zeros for seq 1; and h is the
|
|
363
|
+
# SHA-256, in lowercase hex, of the record without its h, written as Python's json.dumps(record, sort_keys=True,
|
|
364
|
+
# separators=(",", ":")) writes it (keys sorted at every level, no white space, ASCII only with \uXXXX escapes in
|
|
365
|
+
# lowercase hex, floats as Python writes them), as UTF-8.
|
|
366
|
+
#
|
|
367
|
+
# chain = ReduSandbox::AuditChain.new
|
|
368
|
+
# redu.sandboxes.each_audit_event(sandbox.id) { |event| chain.add(event) }
|
|
369
|
+
# puts "#{chain.checked} records checked, #{chain.withheld} withheld, up to #{chain.seq}"
|
|
370
|
+
#
|
|
371
|
+
# A withheld record's own text is not answered, so its h cannot be checked; the order across it can (its seq, prev
|
|
372
|
+
# and h). Read from since 0 to check from the first record, or start from the seq and h of the last record checked
|
|
373
|
+
# before. A page read with kind leaves the records of other kinds out: check each record's own h with
|
|
374
|
+
# AuditChain.verify_each. The chain has no key or signature: it shows a record changed or removed in the middle, not a
|
|
375
|
+
# log cut at its end or replaced as a whole.
|
|
376
|
+
class AuditChain
|
|
377
|
+
# The prev of the log's first record.
|
|
378
|
+
GENESIS = ("0" * 64).freeze
|
|
379
|
+
HASH = /\A[0-9a-f]{64}\z/
|
|
380
|
+
|
|
381
|
+
# The last record checked (its seq and h); how many records' own h were checked, and how many were withheld.
|
|
382
|
+
attr_reader :seq, :h, :checked, :withheld
|
|
383
|
+
|
|
384
|
+
# +seq+ and +h+: the record the check goes on from (0 and GENESIS: the log's first record comes next).
|
|
385
|
+
def initialize(seq: 0, h: GENESIS)
|
|
386
|
+
raise ArgumentError, "seq must be a whole number, 0 or more." unless seq.is_a?(Integer) && !seq.negative?
|
|
387
|
+
raise ArgumentError, "h must be 64 lowercase hex characters." unless h.is_a?(String) && HASH.match?(h)
|
|
388
|
+
|
|
389
|
+
@seq = seq
|
|
390
|
+
@h = h
|
|
391
|
+
@checked = 0
|
|
392
|
+
@withheld = 0
|
|
393
|
+
end
|
|
394
|
+
|
|
395
|
+
# The next AuditEvent of the log, in order. Returns self; raises AuditChainError at a break, and then nothing
|
|
396
|
+
# changes.
|
|
397
|
+
def add(event)
|
|
398
|
+
s = event.seq
|
|
399
|
+
raise AuditChainError.new(s, :seq, "Record #{s} does not follow record #{@seq}.") unless s == @seq + 1
|
|
400
|
+
unless event.prev == @h
|
|
401
|
+
raise AuditChainError.new(s, :prev, "Record #{s}'s prev is not the h of record #{@seq}: a record before it " \
|
|
402
|
+
"was changed or removed.")
|
|
403
|
+
end
|
|
404
|
+
|
|
405
|
+
if event.withheld?
|
|
406
|
+
raise AuditChainError.new(s, :unreadable, "Withheld record #{s} carries no h to go on from.") unless HASH.match?(event.h.to_s)
|
|
407
|
+
|
|
408
|
+
@withheld += 1
|
|
409
|
+
else
|
|
410
|
+
AuditChain.check(event)
|
|
411
|
+
@checked += 1
|
|
412
|
+
end
|
|
413
|
+
@seq = s
|
|
414
|
+
@h = event.h
|
|
415
|
+
self
|
|
416
|
+
end
|
|
417
|
+
|
|
418
|
+
# The chain of +events+ (in order, from the record after +seq+, whose h is +h+): the AuditChain at their end, or
|
|
419
|
+
# AuditChainError at the first break.
|
|
420
|
+
def self.verify(events, seq: 0, h: GENESIS)
|
|
421
|
+
chain = new(seq: seq, h: h)
|
|
422
|
+
events.each { |e| chain.add(e) }
|
|
423
|
+
chain
|
|
424
|
+
end
|
|
425
|
+
|
|
426
|
+
# Each record's own h only, not the order: for a page read with kind, which leaves the other kinds out. Withheld
|
|
427
|
+
# records are passed over. Returns how many records were checked, or raises AuditChainError (:hash or :unreadable).
|
|
428
|
+
def self.verify_each(events)
|
|
429
|
+
events.count do |e|
|
|
430
|
+
next false if e.withheld?
|
|
431
|
+
|
|
432
|
+
check(e)
|
|
433
|
+
true
|
|
434
|
+
end
|
|
435
|
+
end
|
|
436
|
+
|
|
437
|
+
# The h a record's JSON text gives: the SHA-256, in lowercase hex, of #canonical. AuditJson::Invalid when the text
|
|
438
|
+
# is not a JSON object.
|
|
439
|
+
def self.digest(text)
|
|
440
|
+
Digest::SHA256.hexdigest(canonical(text))
|
|
441
|
+
end
|
|
442
|
+
|
|
443
|
+
# What the h of a record's JSON text covers: the record without its h, as Python's json.dumps(record,
|
|
444
|
+
# sort_keys=True, separators=(",", ":")) writes it.
|
|
445
|
+
def self.canonical(text)
|
|
446
|
+
node = AuditJson.parse(text)
|
|
447
|
+
raise AuditJson::Invalid, "a record is a JSON object" unless node.type == :object
|
|
448
|
+
|
|
449
|
+
AuditJson.canonical(node, without: "h")
|
|
450
|
+
end
|
|
451
|
+
|
|
452
|
+
# One whole record's own h: raises AuditChainError (:hash, or :unreadable when its text is not a record).
|
|
453
|
+
def self.check(event)
|
|
454
|
+
got = begin
|
|
455
|
+
digest(event.text)
|
|
456
|
+
rescue AuditJson::Invalid => e
|
|
457
|
+
raise AuditChainError.new(event.seq, :unreadable, "Record #{event.seq} cannot be read: #{e.message}.")
|
|
458
|
+
end
|
|
459
|
+
return if got == event.h
|
|
460
|
+
|
|
461
|
+
raise AuditChainError.new(event.seq, :hash, "Record #{event.seq}'s h is not the SHA-256 of its text: it was changed.")
|
|
462
|
+
end
|
|
463
|
+
end
|
|
464
|
+
|
|
465
|
+
# One event of a sandbox's audit log, as redu answered it: a record exactly as the sandbox service wrote it, or a
|
|
466
|
+
# record withheld in its place (+withheld+ set), with its chain fields. Nothing of a record is renamed or left out:
|
|
467
|
+
# +raw+ is the whole record (String keys), and +text+ its own JSON text, which the chain hashes (AuditChain).
|
|
468
|
+
#
|
|
469
|
+
# seq:: its place in the log: 1, 2, 3 without gaps.
|
|
470
|
+
# kind:: what happened: exec.request, exec.result, exec.kill, file.write, file.read, egress.connect, egress.close,
|
|
471
|
+
# egress.error, egress.refused, rule.deny, rule.match, proc.exec, proc.exit, sandbox.claim, vm.paused, vm.resumed,
|
|
472
|
+
# vm.suspended, vm.snapshot, vm.destroyed and others.
|
|
473
|
+
# source:: "api", "net", "rule", "engine" or "guest".
|
|
474
|
+
# trust:: "host": written by the host from what it saw (an exec.result's exit code, durations and output are what
|
|
475
|
+
# the agent inside the sandbox answered); "guest": reported from inside the sandbox, which a program with root there
|
|
476
|
+
# can stop or forge.
|
|
477
|
+
# prev, h:: the h of the record before (64 zeros for seq 1), and its own.
|
|
478
|
+
# t_ns, mono_ns:: the host's wall clock and monotonic clock, in nanoseconds (whole numbers past 2**53, exact).
|
|
479
|
+
# sandbox_id, data:: the sandbox, and what the record says (never a command's env, its output or a file's content).
|
|
480
|
+
# at, withheld, bytes:: a withheld record's time (ISO 8601), why it is withheld ("platform_detail", "too_large" or
|
|
481
|
+
# "not_json"), and the size of its text. +withheld+ is nil for a whole record.
|
|
482
|
+
AuditEvent = Data.define(:seq, :kind, :source, :trust, :prev, :h, :t_ns, :mono_ns, :sandbox_id, :data, :at,
|
|
483
|
+
:withheld, :bytes, :text, :raw) do
|
|
484
|
+
include Shape
|
|
485
|
+
|
|
486
|
+
# An event from its Node in the answer, and the answer's bytes.
|
|
487
|
+
def self.from_node(node, page)
|
|
488
|
+
d = AuditJson.native(node)
|
|
489
|
+
new(seq: Read.int(d["seq"]) || 0, kind: Read.str(d["kind"]), source: Read.str(d["source"]),
|
|
490
|
+
trust: Read.str(d["trust"]), prev: Read.str(d["prev"]), h: Read.str(d["h"]), t_ns: Read.int(d["t_ns"]),
|
|
491
|
+
mono_ns: Read.int(d["mono_ns"]), sandbox_id: Read.str(d["sandbox_id"]), data: d["data"], at: Read.str(d["at"]),
|
|
492
|
+
withheld: Read.str(d["withheld"]), bytes: Read.int(d["bytes"]),
|
|
493
|
+
text: page.byteslice(node.from, node.to - node.from).force_encoding(Encoding::UTF_8), raw: d)
|
|
494
|
+
end
|
|
495
|
+
|
|
496
|
+
def withheld?
|
|
497
|
+
!withheld.nil?
|
|
498
|
+
end
|
|
499
|
+
end
|
|
500
|
+
|
|
501
|
+
# One page of a sandbox's audit log (GET /v1/sandboxes/:id/audit): its events, oldest first; +next_since+, the since
|
|
502
|
+
# of the next page; +more+, whether more of the log may follow it. +raw+ is the whole answer (String keys).
|
|
503
|
+
AuditLog = Data.define(:events, :next_since, :more, :raw) do
|
|
504
|
+
include Shape
|
|
505
|
+
|
|
506
|
+
# A page from the text of redu's answer, or nil when the text is not one.
|
|
507
|
+
def self.parse(text)
|
|
508
|
+
node = AuditJson.parse(text)
|
|
509
|
+
return nil unless node.type == :object
|
|
510
|
+
|
|
511
|
+
f = node.value.to_h
|
|
512
|
+
events = f["events"]
|
|
513
|
+
since = f["next_since"]
|
|
514
|
+
more = f["more"]
|
|
515
|
+
return nil unless events&.type == :array && events.value.all? { |e| e.type == :object }
|
|
516
|
+
return nil unless since&.type == :number && since.value.match?(/\A\d+\z/) && %i[true false].include?(more&.type)
|
|
517
|
+
|
|
518
|
+
page = text.b
|
|
519
|
+
new(events: events.value.map { |e| AuditEvent.from_node(e, page) }.freeze, next_since: Integer(since.value, 10),
|
|
520
|
+
more: more.type == :true, raw: AuditJson.native(node))
|
|
521
|
+
rescue AuditJson::Invalid
|
|
522
|
+
nil
|
|
523
|
+
end
|
|
524
|
+
end
|
|
525
|
+
end
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ReduSandbox
|
|
4
|
+
# A client for the redu.cloud API.
|
|
5
|
+
#
|
|
6
|
+
# api_key:: an API key, sent as Authorization: Bearer. It reaches sandboxes only when it was granted sandbox:* or
|
|
7
|
+
# the route's own sandbox:<action>: a full-access * key does not include them (403 insufficient_scope). Default:
|
|
8
|
+
# REDU_API_KEY from the environment, when no token is given.
|
|
9
|
+
# token:: a signed-in session's access token instead (also sent as Authorization: Bearer), or anything that answers
|
|
10
|
+
# #call with a fresh one for each request (a Proc, a method). Give api_key or token, not both.
|
|
11
|
+
# base_url:: where the API is. Default: REDU_API_BASE from the environment, else https://console.redu.cloud.
|
|
12
|
+
# timeout:: how long one HTTP request may take, in seconds. Default 120: redu holds a sandbox request up to about
|
|
13
|
+
# 40 s before it answers 202, and this leaves room for that.
|
|
14
|
+
# poll_interval:: how often a request that answered 202 is read again, in seconds. Default 5.
|
|
15
|
+
# max_rate_limit_retries:: how many times a request refused by redu's rate limits (429 rate_limited) is sent again
|
|
16
|
+
# after its Retry-After. Default 2.
|
|
17
|
+
# user_agent:: sent as User-Agent.
|
|
18
|
+
class Client
|
|
19
|
+
attr_reader :sandboxes, :options
|
|
20
|
+
|
|
21
|
+
def initialize(api_key: nil, token: nil, base_url: nil, timeout: nil, poll_interval: nil,
|
|
22
|
+
max_rate_limit_retries: nil, user_agent: nil)
|
|
23
|
+
@options = Transport.resolve_options(
|
|
24
|
+
api_key: api_key, token: token, base_url: base_url, timeout: timeout, poll_interval: poll_interval,
|
|
25
|
+
max_rate_limit_retries: max_rate_limit_retries, user_agent: user_agent
|
|
26
|
+
)
|
|
27
|
+
@transport = Transport.new(@options)
|
|
28
|
+
@sandboxes = Sandboxes.new(@transport)
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# The base URL this client calls.
|
|
32
|
+
def base_url
|
|
33
|
+
@options.base_url
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# GET /v1/capabilities: what the API offers this caller (its scopes, and which features are on for it), as a Hash.
|
|
37
|
+
def capabilities
|
|
38
|
+
a = @transport.request("GET", "/v1/capabilities")
|
|
39
|
+
a.body.is_a?(Hash) ? a.body : {}
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Whether sandboxes are on for this caller's account, from GET /v1/capabilities (its sandboxes block, which
|
|
43
|
+
# follows the same gate as the routes). A key still needs a sandbox scope.
|
|
44
|
+
def sandboxes_enabled?
|
|
45
|
+
s = capabilities["sandboxes"]
|
|
46
|
+
s.is_a?(Hash) && s["enabled"] == true
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Closes the connection this thread keeps to the API (calls keep one open between them, up to 55 s idle); the next
|
|
50
|
+
# call opens a new one.
|
|
51
|
+
def close
|
|
52
|
+
@transport.close
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def inspect
|
|
56
|
+
"#<ReduSandbox::Client base_url=#{base_url.inspect}>"
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
end
|