@krysoworks/kryso 0.0.0-stage → 2.0.0-rc.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.
Files changed (162) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -2
  3. package/bin/kryso +31 -0
  4. package/bin/ship-it-status +14 -0
  5. package/bin/ship-ledger +14 -0
  6. package/bin/ship-loop +14 -0
  7. package/bin/ship-pass +14 -0
  8. package/bin/warden +14 -0
  9. package/dist/answer.d.ts +38 -0
  10. package/dist/answer.js +48 -0
  11. package/dist/bytes.d.ts +5 -0
  12. package/dist/bytes.js +35 -0
  13. package/dist/cleanup.d.ts +1 -0
  14. package/dist/cleanup.js +629 -0
  15. package/dist/commands.d.ts +48 -0
  16. package/dist/commands.js +293 -0
  17. package/dist/completions.d.ts +24 -0
  18. package/dist/completions.js +239 -0
  19. package/dist/daemon.d.ts +15 -0
  20. package/dist/daemon.js +23 -0
  21. package/dist/diagnose.d.ts +47 -0
  22. package/dist/diagnose.js +314 -0
  23. package/dist/doctor.d.ts +1 -0
  24. package/dist/doctor.js +241 -0
  25. package/dist/env.d.ts +9 -0
  26. package/dist/env.js +17 -0
  27. package/dist/evidence.d.ts +39 -0
  28. package/dist/evidence.js +327 -0
  29. package/dist/home.d.ts +3 -0
  30. package/dist/home.js +27 -0
  31. package/dist/install.d.ts +59 -0
  32. package/dist/install.js +137 -0
  33. package/dist/isolate.d.ts +28 -0
  34. package/dist/isolate.js +402 -0
  35. package/dist/leftovers.d.ts +5 -0
  36. package/dist/leftovers.js +156 -0
  37. package/dist/machine.d.ts +6 -0
  38. package/dist/machine.js +185 -0
  39. package/dist/palette.d.ts +147 -0
  40. package/dist/palette.js +167 -0
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +133 -0
  43. package/dist/proc.d.ts +23 -0
  44. package/dist/proc.js +23 -0
  45. package/dist/read.d.ts +1 -0
  46. package/dist/read.js +297 -0
  47. package/dist/readiness.d.ts +5 -0
  48. package/dist/readiness.js +64 -0
  49. package/dist/remote.d.ts +6 -0
  50. package/dist/remote.js +85 -0
  51. package/dist/self-update.d.ts +1 -0
  52. package/dist/self-update.js +224 -0
  53. package/dist/semver.d.ts +7 -0
  54. package/dist/semver.js +42 -0
  55. package/dist/style.d.ts +71 -0
  56. package/dist/style.js +187 -0
  57. package/dist/update.d.ts +47 -0
  58. package/dist/update.js +190 -0
  59. package/dist/work.d.ts +25 -0
  60. package/dist/work.js +449 -0
  61. package/dist/workflows.d.ts +4 -0
  62. package/dist/workflows.js +73 -0
  63. package/docker/entrypoint.sh +44 -0
  64. package/docker/runner.Dockerfile +39 -0
  65. package/package.json +65 -4
  66. package/scripts/install-skills.sh +607 -0
  67. package/skills/code-review/SKILL.md +231 -0
  68. package/skills/kryso/SKILL.md +107 -0
  69. package/skills/kryso/golden/help.rounded.ansi +23 -0
  70. package/skills/kryso/golden/help.square.ansi +23 -0
  71. package/skills/kryso/golden/help.txt +23 -0
  72. package/skills/kryso/golden/table-narrow.json +11 -0
  73. package/skills/kryso/golden/table-narrow.rounded.ansi +4 -0
  74. package/skills/kryso/golden/table-narrow.square.ansi +4 -0
  75. package/skills/kryso/golden/table.ansi +5 -0
  76. package/skills/kryso/golden/table.json +11 -0
  77. package/skills/kryso/ledger.sh +2146 -0
  78. package/skills/kryso/palette.json +57 -0
  79. package/skills/kryso/reference/resuming.md +30 -0
  80. package/skills/kryso/reference/routing.md +23 -0
  81. package/skills/kryso/reference/stage-1-claim.md +79 -0
  82. package/skills/kryso/reference/stage-2-build.md +133 -0
  83. package/skills/kryso/reference/stage-3-prove.md +51 -0
  84. package/skills/kryso/reference/stage-4-pr.md +76 -0
  85. package/skills/kryso/reference/stage-5-reconcile.md +81 -0
  86. package/skills/kryso/reference/stage-6-merge-or-park.md +73 -0
  87. package/skills/kryso/reference/stage-7-close-out.md +62 -0
  88. package/skills/kryso/reference/terminal.md +7 -0
  89. package/skills/kryso/ship-it-status.sh +1503 -0
  90. package/skills/kryso/ui.py +274 -0
  91. package/skills/kryso/ui.sh +609 -0
  92. package/skills/kryso-build/SKILL.md +168 -0
  93. package/skills/kryso-shift/SKILL.md +167 -0
  94. package/skills/kryso-shift/archive.py +2784 -0
  95. package/skills/kryso-shift/archive_checker.py +462 -0
  96. package/skills/kryso-shift/archive_checker_lambda.py +155 -0
  97. package/skills/kryso-shift/archive_health.py +364 -0
  98. package/skills/kryso-shift/archive_launchd.py +140 -0
  99. package/skills/kryso-shift/archive_remote.py +990 -0
  100. package/skills/kryso-shift/archiving-checker.md +140 -0
  101. package/skills/kryso-shift/archiving-keep.md +115 -0
  102. package/skills/kryso-shift/archiving-recovery.md +112 -0
  103. package/skills/kryso-shift/archiving-remote.md +166 -0
  104. package/skills/kryso-shift/archiving.md +146 -0
  105. package/skills/kryso-shift/coverage.schema.json +225 -0
  106. package/skills/kryso-shift/deadline.sh +254 -0
  107. package/skills/kryso-shift/feedback.schema.json +35 -0
  108. package/skills/kryso-shift/feedback.sh +228 -0
  109. package/skills/kryso-shift/history-manifest.schema.json +331 -0
  110. package/skills/kryso-shift/keep-after.sh +55 -0
  111. package/skills/kryso-shift/measure.sh +611 -0
  112. package/skills/kryso-shift/merge-ready.sh +207 -0
  113. package/skills/kryso-shift/outcome.schema.json +16 -0
  114. package/skills/kryso-shift/pass-rules.md +8 -0
  115. package/skills/kryso-shift/profile.schema.json +42 -0
  116. package/skills/kryso-shift/reader.sh +692 -0
  117. package/skills/kryso-shift/reads.sh +151 -0
  118. package/skills/kryso-shift/reference/allowance.md +21 -0
  119. package/skills/kryso-shift/reference/driver.md +95 -0
  120. package/skills/kryso-shift/reference/measuring.md +67 -0
  121. package/skills/kryso-shift/reference/outputs.md +21 -0
  122. package/skills/kryso-shift/reference/pass-script.md +115 -0
  123. package/skills/kryso-shift/reference/reconcile-and-merge.md +55 -0
  124. package/skills/kryso-shift/reference/second-reader.md +9 -0
  125. package/skills/kryso-shift/reference/sweeps.md +83 -0
  126. package/skills/kryso-shift/repair.schema.json +14 -0
  127. package/skills/kryso-shift/report-template.html +679 -0
  128. package/skills/kryso-shift/report.py +389 -0
  129. package/skills/kryso-shift/report_fixture.py +65 -0
  130. package/skills/kryso-shift/reporting.md +58 -0
  131. package/skills/kryso-shift/result.sh +91 -0
  132. package/skills/kryso-shift/runner.sh +1178 -0
  133. package/skills/kryso-shift/ship-loop.sh +3977 -0
  134. package/skills/kryso-shift/ship-pass.sh +4987 -0
  135. package/skills/kryso-shift/steps.jq +19 -0
  136. package/skills/kryso-shift/workflow.mjs +830 -0
  137. package/skills/kryso-shift/workflows/default.json +22 -0
  138. package/skills/kryso-shift/workflows/ralph.json +13 -0
  139. package/skills/kryso-watch/SKILL.md +100 -0
  140. package/skills/kryso-watch/answer.schema.json +23 -0
  141. package/skills/kryso-watch/base-refs.sh +44 -0
  142. package/skills/kryso-watch/board.sh +58 -0
  143. package/skills/kryso-watch/reference/config.md +23 -0
  144. package/skills/kryso-watch/reference/outputs.md +30 -0
  145. package/skills/kryso-watch/reference/report.md +29 -0
  146. package/skills/kryso-watch/reference/scheduler.md +32 -0
  147. package/skills/kryso-watch/reference/settlement.md +29 -0
  148. package/skills/kryso-watch/reference/shift.md +44 -0
  149. package/skills/kryso-watch/reference/shim-limits.md +22 -0
  150. package/skills/kryso-watch/reference/triage.md +26 -0
  151. package/skills/kryso-watch/schema.jq +40 -0
  152. package/skills/kryso-watch/settle.schema.json +36 -0
  153. package/skills/kryso-watch/stage-common.sh +187 -0
  154. package/skills/kryso-watch/stages/report.sh +525 -0
  155. package/skills/kryso-watch/stages/settle.sh +722 -0
  156. package/skills/kryso-watch/stages/shift.sh +466 -0
  157. package/skills/kryso-watch/stages/triage.sh +379 -0
  158. package/skills/kryso-watch/tracker.sh +27 -0
  159. package/skills/kryso-watch/triage.schema.json +77 -0
  160. package/skills/kryso-watch/warden.launchd.plist +50 -0
  161. package/skills/kryso-watch/warden.schema.json +98 -0
  162. package/skills/kryso-watch/warden.sh +1004 -0
@@ -0,0 +1,990 @@
1
+ """The remote side of the archive command: a remote's configuration, the object-storage seam, age, and provisioning.
2
+
3
+ archive.py is the only caller. It reads a remote configuration file, asks whether it is ready for the operation,
4
+ and hands the result to its upload, verify, restore and health code. The storage seam has two adapters, a local directory
5
+ that can inject faults and Amazon S3, so no caller handles a provider's details. age is run as a command.
6
+ `provision` prints the script that makes the private bucket and `audit` compares the deployed bucket with it.
7
+ See archiving-remote.md.
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import shlex
14
+ import shutil
15
+ import signal
16
+ import subprocess
17
+ import tempfile
18
+ from pathlib import Path
19
+
20
+
21
+ class Refused(Exception):
22
+ """The command cannot do what was asked. It is raised before any object, snapshot or restored file is written."""
23
+
24
+
25
+ REMOTE_SCHEMA = "ship-archive-remote/1"
26
+ KINDS = ("s3", "local")
27
+ ACCOUNT = re.compile(r"[0-9]{12}")
28
+ REGION = re.compile(r"[a-z]{2}(-[a-z]+)+-[0-9]")
29
+ # S3's bucket naming rules: 3 to 63 characters, lowercase letters, digits, dots and dashes only, starting and
30
+ # ending with a letter or a digit. No underscores, no uppercase.
31
+ BUCKET = re.compile(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]")
32
+ PROFILE = re.compile(r"[A-Za-z0-9._-]{1,64}")
33
+ # An IAM role or user ARN. Only a role is supported: every operation gets its credentials from sts assume-role,
34
+ # and STS cannot assume a user. A user ARN still matches here so `check` can refuse it by name rather than call
35
+ # it malformed. The leaf after the last slash is the IAM role name, and anything before it is the role's path.
36
+ IDENTITY_ARN = re.compile(r"arn:(?P<partition>aws[a-z-]*):iam::[0-9]{12}:(?P<kind>role|user)/[A-Za-z0-9+=,.@_/-]{1,512}")
37
+ # Every S3 resource this module builds is an arn:aws one, so a bucket in another partition would never be
38
+ # matched by the policies it writes or the audit it runs. GovCloud and China are refused until both construct
39
+ # the partition from the configuration.
40
+ COMMERCIAL_PARTITION = "aws"
41
+ # An IAM role name is the leaf of the ARN's resource part: 1 to 64 characters and no slash, because IAM's name
42
+ # arguments reject one. The path is what comes before it.
43
+ ROLE_NAME = re.compile(r"[A-Za-z0-9+=,.@_-]{1,64}")
44
+ PREFIX = re.compile(r"[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*/?")
45
+ RECIPIENT = re.compile(r"age1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{58}")
46
+ # Private key material of any kind. The uploader's configuration must never hold it.
47
+ PRIVATE_KEY = re.compile(r"AGE-SECRET-KEY-|PRIVATE KEY")
48
+ # S3 has no soft-delete window: a deleted or replaced object survives only as a noncurrent version, and only
49
+ # while no lifecycle rule expires it. The configuration states that guarantee instead of a number of days.
50
+ RETENTION = ("versioned-forever",)
51
+
52
+
53
+ class Remote:
54
+ """One remote's configuration, as the file states it."""
55
+
56
+ def __init__(self, path, doc):
57
+ self.path, self.doc = path, doc
58
+ self.kind = doc.get("kind")
59
+
60
+ def get(self, dotted):
61
+ node = self.doc
62
+ for part in dotted.split("."):
63
+ if not isinstance(node, dict) or part not in node:
64
+ return None
65
+ node = node[part]
66
+ return node
67
+
68
+
69
+ def load_remote(path):
70
+ try:
71
+ doc = json.loads(Path(path).read_text())
72
+ except OSError as error:
73
+ raise Refused(f"cannot read the remote configuration {path}: {error.strerror}") from error
74
+ except ValueError as error:
75
+ raise Refused(f"the remote configuration {path} is not valid JSON: {error}") from error
76
+ if not isinstance(doc, dict):
77
+ raise Refused(f"the remote configuration {path} is not a JSON object")
78
+ if doc.get("kind") not in KINDS:
79
+ raise Refused(f"the remote configuration {path} names kind {doc.get('kind')!r}, and the kinds are {', '.join(KINDS)}")
80
+ return Remote(Path(path), doc)
81
+
82
+
83
+ def secrets_in(node, path=""):
84
+ """The dotted path of every string in the configuration that holds private key material."""
85
+ if isinstance(node, dict):
86
+ return [hit for key, value in node.items() for hit in secrets_in(value, f"{path}.{key}" if path else key)]
87
+ if isinstance(node, list):
88
+ return [hit for index, value in enumerate(node) for hit in secrets_in(value, f"{path}.{index}")]
89
+ return [path] if isinstance(node, str) and PRIVATE_KEY.search(node) else []
90
+
91
+
92
+ def identity_parts(arn):
93
+ """(partition, kind, path, name) for an identity ARN, or None when it is not one.
94
+
95
+ IAM's name arguments take the leaf alone and carry the path separately, so `role/team/evidence-uploader`
96
+ is the role named evidence-uploader at path /team/. One place parses it, because the provisioning script
97
+ and the audit each need the same two pieces and reading the ARN twice is how they came to disagree.
98
+ """
99
+ found = IDENTITY_ARN.fullmatch(arn) if isinstance(arn, str) else None
100
+ if not found:
101
+ return None
102
+ resource = arn.split(":", 5)[5].split("/", 1)[1]
103
+ path, _, name = resource.rpartition("/")
104
+ return found.group("partition"), found.group("kind"), f"/{path}/" if path else "/", name
105
+
106
+
107
+ def check(remote):
108
+ """What is missing or wrong in the remote's configuration, as {field, problem} pairs. Reads nothing else."""
109
+ problems = []
110
+
111
+ def want(field, pattern, needs):
112
+ value = remote.get(field)
113
+ if value is None or value == "":
114
+ problems.append({"field": field, "problem": f"missing: {needs}"})
115
+ elif not isinstance(value, str) or not pattern.fullmatch(value):
116
+ problems.append({"field": field, "problem": f"{value!r} is not valid: {needs}"})
117
+
118
+ for field in secrets_in(remote.doc):
119
+ problems.append({"field": field, "problem": "holds private key material, which never belongs in a remote configuration"})
120
+ if remote.kind == "local":
121
+ root = remote.get("root")
122
+ if not isinstance(root, str) or not root:
123
+ problems.append({"field": "root", "problem": "missing: the directory the local store keeps its objects in"})
124
+ else:
125
+ want("account", ACCOUNT, "the 12-digit AWS account id that owns the bucket")
126
+ want("region", REGION, "the bucket's single region, such as eu-west-1")
127
+ bucket = remote.get("bucket")
128
+ want("bucket", BUCKET, "the private bucket's name, 3 to 63 lowercase letters, digits, dots or dashes")
129
+ if isinstance(bucket, str) and BUCKET.fullmatch(bucket) and (
130
+ bucket.startswith("xn--") or bucket.endswith("-s3alias") or ".." in bucket
131
+ or re.fullmatch(r"\d+\.\d+\.\d+\.\d+", bucket)):
132
+ problems.append({"field": "bucket", "problem": f"{bucket!r} is not valid: a bucket name cannot start with xn--, end with -s3alias, hold two dots in a row or look like an IP address"})
133
+ profile = remote.get("profile")
134
+ if profile is not None and (not isinstance(profile, str) or not PROFILE.fullmatch(profile)):
135
+ problems.append({"field": "profile", "problem": f"{profile!r} is not valid: an optional named profile the aws CLI reads credentials from"})
136
+ prefix = remote.get("prefix")
137
+ if prefix is not None and (not isinstance(prefix, str) or not PREFIX.fullmatch(prefix) or ".." in prefix.split("/")):
138
+ problems.append({"field": "prefix", "problem": f"{prefix!r} is not valid: an optional folder such as evidence/, with no leading slash or .. part"})
139
+ retention = remote.get("retention")
140
+ if retention is None:
141
+ problems.append({"field": "retention", "problem": f"missing: the retention the bucket guarantees, which is {RETENTION[0]}"})
142
+ elif retention not in RETENTION:
143
+ problems.append({"field": "retention", "problem": f"{retention!r} is not valid: S3 keeps a replaced or deleted object only as a "
144
+ f"noncurrent version and only while no lifecycle rule expires it, so the one retention is {RETENTION[0]}"})
145
+ want("uploader.identity", IDENTITY_ARN, "the IAM role ARN that uploads, such as arn:aws:iam::<account>:role/<name>")
146
+ want("recovery.identity", IDENTITY_ARN, "the separate IAM role ARN that reads for recovery")
147
+ for role in ("uploader", "recovery"):
148
+ arn = remote.get(f"{role}.identity")
149
+ parts = identity_parts(arn)
150
+ if parts is None:
151
+ continue
152
+ partition, kind, _, name = parts
153
+ if remote.get("account") and arn.split(":")[4] != remote.get("account"):
154
+ problems.append({"field": f"{role}.identity", "problem": f"{arn!r} is in account {arn.split(':')[4]}, not the configured {remote.get('account')}"})
155
+ if partition != COMMERCIAL_PARTITION:
156
+ problems.append({"field": f"{role}.identity", "problem": f"{arn!r} is in the {partition} partition, and this module builds every "
157
+ f"S3 resource as an arn:{COMMERCIAL_PARTITION} one, so the policies it writes and the "
158
+ f"audit it runs would not match that bucket: only {COMMERCIAL_PARTITION} is supported"})
159
+ if kind == "user":
160
+ problems.append({"field": f"{role}.identity", "problem": f"{arn!r} is a user, and every upload, verify and restore gets its credentials "
161
+ f"from sts assume-role, which cannot assume a user: name an IAM role"})
162
+ if not ROLE_NAME.fullmatch(name):
163
+ problems.append({"field": f"{role}.identity", "problem": f"{arn!r} ends in {name!r}, which is not an IAM name: the part after the last "
164
+ f"slash is 1 to 64 of the characters A-Z a-z 0-9 +=,.@_-"})
165
+ if remote.get("uploader.identity") and remote.get("uploader.identity") == remote.get("recovery.identity"):
166
+ problems.append({"field": "recovery.identity", "problem": "is the uploader's identity: recovery must be independent of the uploader"})
167
+ want("encryption.recipient", RECIPIENT, "the public age recipient raw evidence is encrypted to, age1 followed by 58 characters")
168
+ if remote.get("encryption.tool") not in (None, "age"):
169
+ problems.append({"field": "encryption.tool", "problem": f"{remote.get('encryption.tool')!r} is not supported: the tool is age"})
170
+ return problems
171
+
172
+
173
+ def explain(remote, problems):
174
+ """Every prerequisite the configuration still lacks, in one sentence."""
175
+ listed = "; ".join(f"{p['field']}: {p['problem']}" for p in problems)
176
+ return f"the remote configuration {remote.path} is not ready: {listed}"
177
+
178
+
179
+ def require_ready(remote):
180
+ """Refuse, naming every prerequisite at once, when the configuration is not ready for an operation."""
181
+ problems = check(remote)
182
+ if problems:
183
+ raise Refused(explain(remote, problems))
184
+
185
+
186
+ # ---- the object-storage seam ---------------------------------------------------------------------
187
+ #
188
+ # A store is a private namespace whose objects are created once and read back. It has three operations, create,
189
+ # read and list, and none overwrites or deletes: that is the uploader's whole permission. List names what is under
190
+ # a prefix and reads no bytes, so a reader can find the newest health snapshot. An adapter fills the seam for one
191
+ # provider, and callers never see the provider.
192
+
193
+ class StoreError(Exception):
194
+ """The provider failed: the network, a permission, or a response that cannot be trusted."""
195
+
196
+
197
+ def publish(final, data):
198
+ """Write data at final once, never over an existing file. True when this call wrote it."""
199
+ final.parent.mkdir(parents=True, exist_ok=True)
200
+ fd, tmp = tempfile.mkstemp(dir=final.parent, prefix=".tmp-")
201
+ try:
202
+ with os.fdopen(fd, "wb") as handle:
203
+ handle.write(data)
204
+ os.chmod(tmp, 0o444)
205
+ try:
206
+ os.link(tmp, final)
207
+ except FileExistsError:
208
+ return False
209
+ return True
210
+ finally:
211
+ os.unlink(tmp)
212
+
213
+
214
+ class LocalStore:
215
+ """A directory standing in for a bucket, with faults injected from the file ARCHIVE_STORE_FAULTS names.
216
+
217
+ The file is a JSON list of rules, {"op": "create" | "read" | "list", "match": <part of an object name or a
218
+ listed prefix>, "fault": ...}:
219
+ `error` fails the call as a dropped connection would, `lose-response` creates the object and then fails the
220
+ call, `corrupt` returns the object with a flipped byte, and `drop` returns it as absent. `deny` fails the call
221
+ as a refused permission would. `interrupt` kills the process before the call, and `interrupt-after` kills it
222
+ once a create has landed, so nothing after the write runs: the process dying is the fault, not an error it
223
+ could catch. An empty match takes every object, which is how a store that is offline is injected.
224
+
225
+ When ARCHIVE_STORE_CALLS names a file, each call appends one line to it, `<op> <name>`, before any fault, so a
226
+ test can tell which objects a run read and which it created.
227
+ """
228
+
229
+ def __init__(self, root, faults=None, calls=None):
230
+ self.root = Path(root)
231
+ self.faults = faults or []
232
+ self.calls = Path(calls) if calls else None
233
+
234
+ def fault(self, op, name):
235
+ if self.calls:
236
+ with open(self.calls, "a") as log:
237
+ log.write(f"{op} {name}\n")
238
+ found = next((rule["fault"] for rule in self.faults if rule["op"] == op and rule["match"] in name), None)
239
+ if found == "interrupt":
240
+ os.kill(os.getpid(), signal.SIGKILL)
241
+ if found == "deny":
242
+ doing = {"create": "creating", "read": "reading", "list": "listing"}[op]
243
+ raise StoreError(f"injected: permission denied while {doing} {name}")
244
+ return found
245
+
246
+ def path(self, name):
247
+ parts = name.split("/")
248
+ if name.startswith("/") or any(part in ("", ".", "..") for part in parts):
249
+ raise StoreError(f"{name!r} is not an object name")
250
+ return self.root.joinpath(*parts)
251
+
252
+ def create(self, name, data):
253
+ fault = self.fault("create", name)
254
+ if fault == "error":
255
+ raise StoreError(f"injected: the connection dropped while creating {name}")
256
+ created = publish(self.path(name), data)
257
+ if fault == "interrupt-after":
258
+ os.kill(os.getpid(), signal.SIGKILL)
259
+ if fault == "lose-response":
260
+ raise StoreError(f"injected: the response for creating {name} was lost")
261
+ return created
262
+
263
+ def read(self, name):
264
+ fault = self.fault("read", name)
265
+ if fault == "error":
266
+ raise StoreError(f"injected: the connection dropped while reading {name}")
267
+ path = self.path(name)
268
+ if fault == "drop" or not path.is_file():
269
+ return None
270
+ data = path.read_bytes()
271
+ return bytes([data[0] ^ 0xFF]) + data[1:] if fault == "corrupt" and data else data
272
+
273
+ def list(self, prefix):
274
+ """Every object name under a prefix ending in a slash, sorted. None is an empty list, never an error."""
275
+ if self.fault("list", prefix) == "error":
276
+ raise StoreError(f"injected: the connection dropped while listing {prefix}")
277
+ top = self.path(prefix.rstrip("/"))
278
+ if not top.is_dir():
279
+ return []
280
+ return sorted(path.relative_to(self.root).as_posix() for path in top.rglob("*")
281
+ if path.is_file() and not path.name.startswith(".tmp-"))
282
+
283
+
284
+ S3_TIMEOUT_SECONDS = 120
285
+ # The aws CLI's own exit codes, which say whether the call reached S3 at all. 254 is a reply carrying an error
286
+ # code, 255 and 253 are a failure before or around the request, and 252 is a bad command line.
287
+ AWS_API_ERROR = 254
288
+ # The error codes that mean the credentials ran out rather than that the call was wrong.
289
+ AWS_STALE = ("ExpiredToken", "ExpiredTokenException", "InvalidClientTokenId", "RequestExpired", "TokenRefreshRequired")
290
+ # The error codes a conditional create answers with when the object is already there.
291
+ AWS_EXISTS = ("PreconditionFailed", "ConditionalRequestConflict")
292
+ AWS_DENIED = ("AccessDenied", "AccessDeniedException", "AllAccessDisabled", "UnauthorizedOperation", "Forbidden")
293
+ AWS_ABSENT = ("NoSuchKey", "NoSuchBucket", "404")
294
+ AWS_ERROR_CODE = re.compile(r"An error occurred \(([A-Za-z0-9.]+)\)")
295
+
296
+
297
+ class S3Store:
298
+ """A bucket reached through `aws s3api`, as one IAM role.
299
+
300
+ Temporary credentials come from `aws sts assume-role --role-arn <identity>`, so no key file is held anywhere
301
+ and nothing long-lived is written. With no identity the operator's own credentials are used, which is how the
302
+ audit reads the bucket's configuration. Every create carries `If-None-Match: *`, which makes S3 refuse rather
303
+ than replace an existing object, and the uploader's policy denies a PutObject that does not carry it, so the
304
+ refusal does not depend on this adapter asking for it.
305
+ Shelling out to the CLI keeps each call's own outcome visible and leaves SigV4 signing to it.
306
+ ARCHIVE_S3_ENDPOINT points the adapter at a stand-in server, and nothing else reads it.
307
+ """
308
+
309
+ def __init__(self, bucket, prefix, identity, region=None, profile=None):
310
+ self.bucket, self.identity, self.region, self.profile = bucket, identity, region, profile
311
+ self.prefix = prefix if prefix is None or prefix.endswith("/") else f"{prefix}/"
312
+ self.prefix = self.prefix or ""
313
+ self.endpoint = (os.environ.get("ARCHIVE_S3_ENDPOINT") or "").rstrip("/")
314
+ self.cached = None
315
+
316
+ def aws(self):
317
+ command = shutil.which("aws")
318
+ if not command:
319
+ raise Refused("the aws CLI is not installed: it signs the requests the S3 adapter makes (brew install awscli)")
320
+ return command
321
+
322
+ def credentials(self, fresh=False):
323
+ """The environment one call runs with: assumed-role credentials for an identity, the operator's own otherwise."""
324
+ if self.identity is None:
325
+ return {}
326
+ if self.cached and not fresh:
327
+ return self.cached
328
+ session = f"ship-archive-{self.identity.rsplit('/', 1)[-1]}"[:64]
329
+ try:
330
+ done = subprocess.run([self.aws(), "sts", "assume-role", "--role-arn", self.identity,
331
+ "--role-session-name", session, "--output", "json",
332
+ *(["--profile", self.profile] if self.profile else [])],
333
+ capture_output=True, text=True, timeout=S3_TIMEOUT_SECONDS)
334
+ except subprocess.TimeoutExpired as error:
335
+ # Without this the whole operation waits on STS for ever. A StoreError is the stop the callers
336
+ # already report as visible and resumable, so a hung assume-role reads like any other outage.
337
+ raise StoreError(f"the aws CLI did not finish assuming {self.identity} within "
338
+ f"{S3_TIMEOUT_SECONDS} seconds") from error
339
+ try:
340
+ issued = json.loads(done.stdout)["Credentials"]
341
+ except (ValueError, KeyError, TypeError):
342
+ issued = None
343
+ if done.returncode != 0 or not issued:
344
+ raise Refused(f"the aws CLI could not assume {self.identity}: "
345
+ f"{done.stderr.strip() or 'no credentials returned'}")
346
+ self.cached = {"AWS_ACCESS_KEY_ID": issued["AccessKeyId"], "AWS_SECRET_ACCESS_KEY": issued["SecretAccessKey"],
347
+ "AWS_SESSION_TOKEN": issued["SessionToken"], "AWS_PROFILE": ""}
348
+ return self.cached
349
+
350
+ def call(self, *args, service="s3api"):
351
+ """(code, stdout, stderr). Credentials that ran out are replaced once. A failure to reach S3 is a StoreError."""
352
+ for attempt in (1, 2):
353
+ issued = self.credentials(fresh=attempt == 2)
354
+ environment = {k: v for k, v in dict(os.environ, **issued).items() if v != ""}
355
+ if self.profile and self.identity is None:
356
+ environment["AWS_PROFILE"] = self.profile
357
+ if self.region:
358
+ environment["AWS_DEFAULT_REGION"] = self.region
359
+ environment["AWS_EC2_METADATA_DISABLED"] = "true"
360
+ command = [self.aws(), service, *args, *(["--endpoint-url", self.endpoint] if self.endpoint else [])]
361
+ try:
362
+ done = subprocess.run(command, capture_output=True, timeout=S3_TIMEOUT_SECONDS, env=environment)
363
+ except (subprocess.TimeoutExpired, OSError) as error:
364
+ raise StoreError(f"cannot reach S3: {error}") from error
365
+ text = done.stderr.decode(errors="replace").strip()
366
+ if done.returncode == 0:
367
+ return 0, done.stdout, text
368
+ code = (AWS_ERROR_CODE.search(text) or [None, None])[1]
369
+ if done.returncode != AWS_API_ERROR:
370
+ raise StoreError(f"the aws CLI could not reach S3: {text or f'exit {done.returncode}'}")
371
+ if code in AWS_STALE and attempt == 1 and self.identity is not None:
372
+ continue
373
+ return done.returncode, done.stdout, text
374
+ raise StoreError("unreachable")
375
+
376
+ def refusal(self, code, message, doing):
377
+ if code in AWS_DENIED:
378
+ return StoreError(f"permission denied for {self.identity or OWN_CREDENTIALS} while {doing}: {message}")
379
+ return StoreError(f"{doing} failed with {code or 'no error code'}: {message}")
380
+
381
+ def create(self, name, data):
382
+ with tempfile.NamedTemporaryFile(prefix=".archive-upload-") as body:
383
+ body.write(data)
384
+ body.flush()
385
+ status, _, text = self.call("put-object", "--bucket", self.bucket, "--key", self.prefix + name,
386
+ "--body", body.name, "--if-none-match", "*")
387
+ if status == 0:
388
+ return True
389
+ code = (AWS_ERROR_CODE.search(text) or [None, None])[1]
390
+ if code in AWS_EXISTS:
391
+ return False
392
+ raise self.refusal(code, text, f"creating {name}")
393
+
394
+ def document(self, *args):
395
+ """One of the bucket's configurations, as the `aws s3api` call named by args states it. {} when it is unset.
396
+
397
+ --output json is passed rather than assumed: an operator whose profile or AWS_DEFAULT_OUTPUT asks for
398
+ text, table or yaml would otherwise make a healthy bucket fail the audit on a parse error.
399
+ """
400
+ status, out, text = self.call(*args, "--bucket", self.bucket, "--output", "json")
401
+ if status == 0:
402
+ try:
403
+ return json.loads(out or b"{}")
404
+ except ValueError as error:
405
+ raise StoreError(f"{args[0]} returned a reply that is not JSON: {error}") from error
406
+ code = (AWS_ERROR_CODE.search(text) or [None, None])[1]
407
+ # Every one of these reads answers with its own absence code when nobody ever set that configuration.
408
+ if code and code.startswith("NoSuch") and code not in ("NoSuchBucket",):
409
+ return {}
410
+ raise self.refusal(code, text, f"reading the bucket's {args[0].removeprefix('get-').replace('-', ' ')}")
411
+
412
+ def document_of(self, verb, kind, name, field, *more):
413
+ """One field of what IAM holds for a role or a user, or None when it cannot be read at all."""
414
+ status, out, _ = self.call(verb, f"--{kind}-name", name, *more, "--output", "json", service="iam")
415
+ if status != 0:
416
+ return None
417
+ try:
418
+ return json.loads(out or b"{}").get(field)
419
+ except ValueError:
420
+ return None
421
+
422
+ def read(self, name):
423
+ with tempfile.TemporaryDirectory(prefix=".archive-download-") as directory:
424
+ into = Path(directory) / "object"
425
+ status, _, text = self.call("get-object", "--bucket", self.bucket, "--key", self.prefix + name, str(into))
426
+ if status == 0:
427
+ return into.read_bytes()
428
+ code = (AWS_ERROR_CODE.search(text) or [None, None])[1]
429
+ if code in AWS_ABSENT:
430
+ return None
431
+ raise self.refusal(code, text, f"reading {name}")
432
+
433
+ def list(self, prefix):
434
+ """Every object name under a prefix, sorted, from `list-objects-v2`, which follows the pages itself.
435
+
436
+ A missing bucket is an error here, unlike a missing key on a read: an empty answer would read as no health
437
+ snapshot at all, when the truth is that nothing could be asked.
438
+ """
439
+ status, out, text = self.call("list-objects-v2", "--bucket", self.bucket, "--prefix", self.prefix + prefix,
440
+ "--output", "json")
441
+ if status != 0:
442
+ code = (AWS_ERROR_CODE.search(text) or [None, None])[1]
443
+ raise self.refusal(code, text, f"listing {prefix}")
444
+ try:
445
+ listed = json.loads(out or b"{}") or {}
446
+ except ValueError as error:
447
+ raise StoreError(f"listing {prefix} returned a reply that is not JSON: {error}") from error
448
+ keys = [item.get("Key") for item in listed.get("Contents") or [] if isinstance(item, dict)]
449
+ return sorted(key[len(self.prefix):] for key in keys if isinstance(key, str) and key.startswith(self.prefix))
450
+
451
+
452
+ def open_store(remote, role):
453
+ """The store for a remote, opened as its uploader or its recovery identity."""
454
+ if remote.kind == "local":
455
+ faults_file = os.environ.get("ARCHIVE_STORE_FAULTS")
456
+ return LocalStore(remote.get("root"), json.loads(Path(faults_file).read_text()) if faults_file else None,
457
+ os.environ.get("ARCHIVE_STORE_CALLS"))
458
+ return S3Store(remote.get("bucket"), remote.get("prefix"), remote.get(f"{role}.identity"),
459
+ remote.get("region"), remote.get("profile"))
460
+
461
+
462
+ OBJECT_NAME = re.compile(r"objects/([0-9a-f]{64})\.age")
463
+
464
+
465
+ def object_name(ciphertext_sha256):
466
+ return f"objects/{ciphertext_sha256}.age"
467
+
468
+
469
+ def manifest_name(snapshot):
470
+ return f"snapshots/{snapshot}/manifest.json"
471
+
472
+
473
+ def complete_name(snapshot):
474
+ return f"snapshots/{snapshot}/complete.json"
475
+
476
+
477
+ # Health snapshot names are archive_health's, which the deployed checker shares.
478
+
479
+
480
+ # ---- encryption ----------------------------------------------------------------------------------
481
+
482
+ class Age:
483
+ """age, the supported encryption tool, run as a command: bytes in, bytes out."""
484
+
485
+ def __init__(self):
486
+ self.command = shutil.which("age")
487
+ if not self.command:
488
+ raise Refused("age is not installed: encrypted upload and restore need it (brew install age)")
489
+
490
+ def run(self, args, data, what):
491
+ done = subprocess.run([self.command, *args], input=data, capture_output=True)
492
+ if done.returncode != 0:
493
+ raise Refused(f"age could not {what}: {done.stderr.decode(errors='replace').strip() or 'exit ' + str(done.returncode)}")
494
+ return done.stdout
495
+
496
+ def encrypt(self, data, recipient):
497
+ return self.run(["-r", recipient], data, "encrypt")
498
+
499
+ def decrypt(self, data, identity):
500
+ return self.run(["-d", "-i", str(identity)], data, "decrypt")
501
+
502
+
503
+ # ---- provisioning and its audit ------------------------------------------------------------------
504
+
505
+ # What each identity may do on the bucket's objects: the uploader creates and reads back, the recovery identity
506
+ # only reads. s3:PutObject alone also permits replacing an object, and with versioning on the replacement simply
507
+ # becomes the current version, so no delete action is ever evaluated and DENIES cannot reach that case. Two
508
+ # conditional denies close it: CREATE_ONLY_DENIES makes a PUT that is not a conditional create unauthorised in
509
+ # IAM, not merely refused by a well-behaved client. Together the grant, the unconditional denies and the
510
+ # conditional ones are what make a created object final.
511
+ GRANTS = {"uploader": ("s3:PutObject", "s3:GetObject"), "recovery": ("s3:GetObject",)}
512
+ # s3:ListBucket is granted beside the object actions, on the bucket rather than on the objects, because a
513
+ # GetObject for a key that is not there answers 404 NoSuchKey only to a principal holding it and 403
514
+ # AccessDenied otherwise. The first upload of a snapshot reads its complete.json before creating anything, and
515
+ # the adapter turns a 403 into a StoreError rather than None, so without this grant a first upload stops.
516
+ #
517
+ # The grant carries no condition, and that is deliberate. An s3:prefix condition held it to the archive's own
518
+ # prefix, which reads like a tightening and is a hazard: s3:prefix is a condition key on ListBucket alone, so a
519
+ # GetObject request never carries it, and IAM reads a positive operator over a key absent from the request as
520
+ # false. The statement would then not apply to the GetObject at all, the caller would count as lacking
521
+ # s3:ListBucket, and the first upload would get the 403 this grant exists to prevent. AWS does not say outright
522
+ # whether the permission check behind the 403-or-404 split evaluates conditions, so the risk is not certain,
523
+ # but it is one-sided: the condition cannot narrow a request that does not carry the key, so on the GetObject
524
+ # path it can only break things, never restrict them.
525
+ # It buys nothing either. Both identities already hold s3:GetObject on <bucket>/*, so a prefix condition on
526
+ # ListBucket never stopped them reading another prefix's object bytes. All it withheld was the ability to
527
+ # enumerate key names outside the archive prefix, and no caller lists there: the adapter's `list`, which
528
+ # archive_health.py uses to find health snapshots, puts the archive prefix in front of every prefix it asks
529
+ # for, and every other call is a get-object or a put-object. What the grant widens is exactly that, the listing of key names in this one
530
+ # bucket, and it exposes no object's contents that s3:GetObject does not already reach.
531
+ BUCKET_GRANT = "s3:ListBucket"
532
+ DENIES = ("s3:DeleteObject", "s3:DeleteObjectVersion", "s3:PutObjectAcl", "s3:PutBucketPolicy",
533
+ "s3:PutBucketVersioning", "s3:PutLifecycleConfiguration", "s3:DeleteBucket", "s3:DeleteBucketPolicy")
534
+ # s3:if-none-match is a String condition key on s3:PutObject that carries the request's If-None-Match header, and
535
+ # PutObject accepts no value for it but "*". Both statements are needed, and neither can be folded into the other:
536
+ # Null true matches only when the header is absent, while StringNotEquals matches both a wrong value and, because
537
+ # IAM reads a negated operator as true for a key that is not in the request, an absent one. Put in one statement
538
+ # the two conditions would be ANDed, could never both hold, and the deny would never fire. Each is a separate
539
+ # statement so either alone closes the hole.
540
+ # No s3:ObjectCreationOperation exemption is set: that key is what AWS's own examples use to keep multipart
541
+ # uploads working, and this uploader creates every object with one PutObject. Leaving it out denies the multipart
542
+ # calls too, which cannot carry a conditional header, and a stricter deny opens nothing.
543
+ CREATE_ONLY_DENIES = ({"Null": {"s3:if-none-match": "true"}},
544
+ {"StringNotEquals": {"s3:if-none-match": "*"}})
545
+ # Named so the refusal message need not quote an apostrophe inside an f-string expression, which is a
546
+ # syntax error before Python 3.12 and this module supports 3.10.
547
+ OWN_CREDENTIALS = "the operator's own credentials"
548
+ # A principal in a bucket policy that opens the bucket to anyone who asks.
549
+ PUBLIC_PRINCIPALS = ("*", "arn:aws:iam::*:root")
550
+ # The trust policy each created role gets, as a printf format: the one %s is the operator allowed to assume it.
551
+ # It holds no other % so nothing else in it is a conversion.
552
+ TRUST_POLICY = json.dumps({"Version": "2012-10-17", "Statement": [
553
+ {"Effect": "Allow", "Principal": {"AWS": "%s"}, "Action": "sts:AssumeRole"}]})
554
+
555
+
556
+ def require_s3(remote, verb):
557
+ require_ready(remote)
558
+ if remote.kind != "s3":
559
+ raise Refused(f"{verb} applies to an s3 remote, and {remote.path} is a {remote.kind} one")
560
+
561
+
562
+ def policy_document(remote, role):
563
+ """The identity policy one role holds: what it may do on the bucket, and what it may never do."""
564
+ bucket, objects = f"arn:aws:s3:::{remote.get('bucket')}", f"arn:aws:s3:::{remote.get('bucket')}/*"
565
+ statements = [{"Sid": f"Evidence{role.capitalize()}Allow", "Effect": "Allow",
566
+ "Action": list(GRANTS[role]), "Resource": objects},
567
+ {"Sid": f"Evidence{role.capitalize()}List", "Effect": "Allow", "Action": [BUCKET_GRANT],
568
+ "Resource": bucket}]
569
+ if role == "uploader":
570
+ statements.append({"Sid": "EvidenceNeverReplaceOrRemove", "Effect": "Deny",
571
+ "Action": list(DENIES), "Resource": [bucket, objects]})
572
+ statements += [{"Sid": f"EvidenceCreateOnly{n}", "Effect": "Deny", "Action": ["s3:PutObject"],
573
+ "Resource": [objects], "Condition": condition}
574
+ for n, condition in enumerate(CREATE_ONLY_DENIES, start=1)]
575
+ return {"Version": "2012-10-17", "Statement": statements}
576
+
577
+
578
+ def provision_script(remote):
579
+ """The shell script that makes the private destination. It is printed for an owner to read and run."""
580
+ require_s3(remote, "provision")
581
+ account, bucket, region = remote.get("account"), remote.get("bucket"), remote.get("region")
582
+ profile = [f"--profile {shlex.quote(remote.get('profile'))}"] if remote.get("profile") else []
583
+ aws = " ".join(["aws", *profile])
584
+ roles = {role: remote.get(f"{role}.identity") for role in ("uploader", "recovery")}
585
+ # us-east-1 is the one region S3 rejects as a LocationConstraint, because it is what a request with no
586
+ # configuration at all creates. Under set -e the script would stop on its first command.
587
+ locate = "" if region == "us-east-1" else f" \\\n --create-bucket-configuration LocationConstraint={region}"
588
+ lines = [
589
+ "#!/usr/bin/env bash",
590
+ f"# Provision the private evidence bucket s3://{bucket}. archive.py printed this and ran none of it:",
591
+ f"# read it, then run it as an administrator of account {account}. It sets no lifecycle rule, so nothing in",
592
+ "# the bucket expires, and versioning keeps every replaced or deleted object as a noncurrent version.",
593
+ "set -euo pipefail",
594
+ ': "${UPLOADER_OPERATOR:?set it to the principal allowed to assume the uploader role, such as arn:aws:iam::123456789012:user/you}"',
595
+ ': "${RECOVERY_OPERATOR:?set it to the principal allowed to assume the recovery role, a different person or machine}"',
596
+ f'test "$({aws} sts get-caller-identity --query Account --output text)" = {account}',
597
+ "",
598
+ f"{aws} s3api create-bucket --bucket {bucket} --region {region} "
599
+ f"--object-ownership BucketOwnerEnforced{locate}",
600
+ f"{aws} s3api put-public-access-block --bucket {bucket} --public-access-block-configuration \\",
601
+ " BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true",
602
+ f"{aws} s3api put-bucket-versioning --bucket {bucket} --versioning-configuration Status=Enabled",
603
+ f"{aws} s3api put-bucket-encryption --bucket {bucket} --server-side-encryption-configuration \\",
604
+ " '" + json.dumps({"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"},
605
+ "BucketKeyEnabled": True}]}) + "'",
606
+ "",
607
+ ]
608
+ # check refuses a user ARN, so every identity here is a role the script creates and attaches a policy to.
609
+ # IAM's --role-name takes the leaf alone and the path goes to create-role as --path.
610
+ for role, arn in roles.items():
611
+ _, _, path, name = identity_parts(arn)
612
+ operator = f"{role.upper()}_OPERATOR"
613
+ # The operator's ARN is a shell variable, so the trust policy is assembled at run time instead of being
614
+ # quoted whole: single quotes would send IAM the literal string "$UPLOADER_OPERATOR" as the principal.
615
+ # printf substitutes the value as data into a single-quoted template, so a value holding shell or JSON
616
+ # metacharacters cannot reach the script's syntax or the rest of the document.
617
+ lines += [f'{role.upper()}_TRUST="$(printf {shlex.quote(TRUST_POLICY)} "${operator}")"',
618
+ f"{aws} iam create-role --role-name {shlex.quote(name)} \\",
619
+ *([f" --path {shlex.quote(path)} \\"] if path != "/" else []),
620
+ f" --description {shlex.quote(f'Evidence archive {role}')} \\",
621
+ f' --assume-role-policy-document "${role.upper()}_TRUST"', ""]
622
+ for role, arn in roles.items():
623
+ lines += [f"{aws} iam put-role-policy --role-name {shlex.quote(identity_parts(arn)[3])} \\",
624
+ f" --policy-name evidence-archive-{role} \\",
625
+ " --policy-document '" + json.dumps(policy_document(remote, role)) + "'", ""]
626
+ lines += ["echo " + shlex.quote(f"Next: python3 archive.py audit --remote {shlex.quote(str(remote.path))}"), ""]
627
+ return "\n".join(lines)
628
+
629
+
630
+ def audit(remote):
631
+ """What the deployed bucket does differently from the provisioning script, read as the operator's own credentials."""
632
+ require_s3(remote, "audit")
633
+ operator = S3Store(remote.get("bucket"), None, None, remote.get("region"), remote.get("profile"))
634
+ blocked = operator.document("get-public-access-block")
635
+ versioning = operator.document("get-bucket-versioning")
636
+ lifecycle = operator.document("get-bucket-lifecycle-configuration")
637
+ location = operator.document("get-bucket-location")
638
+ policy = operator.document("get-bucket-policy")
639
+ problems = []
640
+ block = blocked.get("PublicAccessBlockConfiguration") or {}
641
+ for setting in ("BlockPublicAcls", "IgnorePublicAcls", "BlockPublicPolicy", "RestrictPublicBuckets"):
642
+ if block.get(setting) is not True:
643
+ problems.append(f"the public access block has {setting} {block.get(setting)!r}, not true")
644
+ if versioning.get("Status") != "Enabled":
645
+ problems.append(f"versioning is {versioning.get('Status') or 'never enabled'}, not Enabled, so a deleted "
646
+ f"or replaced object leaves nothing behind")
647
+ for rule in lifecycle.get("Rules") or []:
648
+ if rule.get("Status") != "Enabled":
649
+ continue
650
+ expiring = [key for key in ("Expiration", "NoncurrentVersionExpiration", "AbortIncompleteMultipartUpload",
651
+ "Transitions", "NoncurrentVersionTransitions") if rule.get(key)]
652
+ if expiring:
653
+ problems.append(f"lifecycle rule {rule.get('ID') or '(unnamed)'} sets {', '.join(expiring)}, "
654
+ f"and evidence must never expire or move automatically")
655
+ # An empty LocationConstraint is us-east-1, as the API has always reported it.
656
+ held = location.get("LocationConstraint") or "us-east-1"
657
+ if held != remote.get("region"):
658
+ problems.append(f"the bucket is in {held}, not the configured region {remote.get('region')}")
659
+ try:
660
+ statements = json.loads(policy.get("Policy") or "{}").get("Statement") or []
661
+ except ValueError as error:
662
+ raise StoreError(f"the bucket policy is not JSON: {error}") from error
663
+ if isinstance(statements, dict):
664
+ statements = [statements]
665
+ problems += bucket_policy_problems(statements, remote)
666
+ problems += identity_problems(operator, remote)
667
+ return problems
668
+
669
+
670
+ def bucket_policy_problems(statements, remote):
671
+ """What the bucket policy grants that the provisioning script does not, which attaches no bucket policy at all.
672
+
673
+ A bucket policy is resource-based, so what it allows is unioned with what the identity policies allow: an
674
+ Allow of s3:PutObject naming the recovery role makes recovery able to upload however read-only its own
675
+ policy is. Checking only for a public principal missed that, so every Allow is judged against the two
676
+ configured identities as well, and a statement whose principals or actions cannot be read is reported
677
+ rather than passed over.
678
+
679
+ What it judges is the two identities and a public principal. An Allow naming some third principal in the
680
+ account is left alone: who else may read the bucket is the account's business, and this audit's subject is
681
+ whether the uploader and the recovery identity hold what the provisioning script gave them.
682
+ """
683
+ identities = {remote.get(f"{role}.identity"): role for role in ("uploader", "recovery")}
684
+ problems = []
685
+ for statement in statements:
686
+ if statement.get("Effect") != "Allow":
687
+ continue
688
+ principal, where = statement.get("Principal"), statement.get("Sid") or "(unnamed)"
689
+ if statement.get("NotPrincipal") is not None:
690
+ problems.append(f"bucket policy statement {where} allows with NotPrincipal, which the audit does not "
691
+ f"evaluate: the provisioning script attaches no bucket policy, so remove it")
692
+ continue
693
+ named = [principal] if isinstance(principal, str) else sum(
694
+ ([value] if isinstance(value, str) else list(value) for value in (principal or {}).values()), [])
695
+ for who in named:
696
+ if who in PUBLIC_PRINCIPALS:
697
+ problems.append(f"the bucket policy allows {who}, and the bucket must not be public")
698
+ elif who in identities:
699
+ granted, unreadable = judge([{"Statement": [statement]}], remote.get("bucket"))
700
+ problems += [f"the bucket policy {construct}" for construct in unreadable]
701
+ problems += [f"the bucket policy allows the {identities[who]} identity {who} {action}, and the "
702
+ f"provisioning script attaches no bucket policy: what each identity may do is its "
703
+ f"own policy's to say" for action in sorted(a for a, e in granted.items() if "Allow" in e)]
704
+ return problems
705
+
706
+
707
+ def identity_problems(operator, remote):
708
+ """What the uploader and recovery identities hold on the bucket, compared with what the script attaches.
709
+
710
+ Each identity's policies are read back from IAM: the inline policy the script wrote, every other inline policy,
711
+ and every attached managed policy. An action beyond the identity's allowed set, a missing allowed action, or a
712
+ missing deny on the uploader is a problem. A managed policy's own document is not read, because its contents can
713
+ change without the identity changing, so one being attached at all is reported.
714
+
715
+ The uploader's create-only denies are judged on their conditions rather than their action lists: they deny an
716
+ action the uploader is also granted, so what they rule out is the condition, and an action list cannot show
717
+ whether one still matches the request it exists to stop.
718
+
719
+ Everywhere else, a statement the evaluator cannot read exactly is reported rather than skipped. NotAction,
720
+ NotResource, a wildcard action pattern wider than one action and a condition on a deny that is supposed to
721
+ be unconditional all become problems naming the construct, because a policy the audit half-understands is
722
+ the one that passes while permitting something.
723
+
724
+ It reads only what is attached to these two identities. A permission granted higher up, by a service control
725
+ policy on the account or the organisation, or by a resource policy on something else, is invisible to it, so the
726
+ restriction check in the runbook is still needed. A role's group memberships are not read either, which is one
727
+ more reason only roles are supported: a role has no groups, while a user's permissions could come through one.
728
+ """
729
+ objects = f"arn:aws:s3:::{remote.get('bucket')}/*"
730
+ problems = []
731
+ for who, allowed in GRANTS.items():
732
+ arn = remote.get(f"{who}.identity")
733
+ allowed = tuple(allowed) + (BUCKET_GRANT,)
734
+ held, attached, listed = read_policies(operator, "role", identity_parts(arn)[3])
735
+ if held is None:
736
+ problems.append(f"the audit could not read the {who} identity {arn} from IAM, so it cannot tell what that identity holds")
737
+ continue
738
+ problems += [f"the {who} identity {arn} has the managed policy {policy} attached, and the audit cannot judge "
739
+ f"what it allows: only the inline evidence-archive-{who} policy should be there" for policy in attached]
740
+ problems += [f"the {who} identity {arn} has the extra inline policy {policy}, which the provisioning script "
741
+ f"does not attach" for policy in listed if policy != f"evidence-archive-{who}"]
742
+ decisions, unreadable = judge(held, remote.get("bucket"))
743
+ problems += [f"the {who} identity {arn} {construct}" for construct in unreadable]
744
+ # An Allow that an unconditional Deny of the same action overrides leaves the identity unable to do what
745
+ # it needs: the deny wins, so restore cannot read and upload cannot create.
746
+ problems += [f"the {who} identity {arn} is not allowed {action} on the bucket, which it needs"
747
+ for action in allowed if "Allow" not in decisions.get(action, set())]
748
+ problems += [f"the {who} identity {arn} is allowed {action} and also denied it unconditionally, so the deny "
749
+ f"wins and every {action} it needs fails" for action in allowed
750
+ if {"Allow", "Deny"} <= decisions.get(action, set())]
751
+ problems += [f"the {who} identity {arn} is allowed {action}, which the {who} may not hold: it may hold only "
752
+ f"{', '.join(allowed)}" for action in sorted(decisions)
753
+ if "Allow" in decisions[action] and action not in allowed]
754
+ if who == "uploader":
755
+ problems += [f"the uploader {arn} does not deny {action} unconditionally, so a created object is not final"
756
+ for action in DENIES if "Deny" not in decisions.get(action, set())]
757
+ problems += create_only_problems(held, objects, arn)
758
+ return problems
759
+
760
+
761
+ def create_only_problems(documents, objects, arn):
762
+ """What is missing from the uploader's conditional create-only denies, which no action list can show.
763
+
764
+ s3:PutObject is granted, so a PUT that carries no If-None-Match is authorised by the grant alone and replaces
765
+ the object. Each condition in CREATE_ONLY_DENIES has to appear on a Deny of s3:PutObject covering the bucket's
766
+ objects, with its operator, its key and its value exactly as the script writes them. A deny whose condition was
767
+ widened, renamed or given another value no longer matches the request it is there to stop, and a deny that does
768
+ not match is worth no more than none at all, so each is reported by the condition it should have carried.
769
+
770
+ The shape is held exactly rather than reasoned about, so a policy that denies the same thing by another route,
771
+ such as one naming s3:* instead of s3:PutObject, is still reported. Reading a policy loosely is what let an
772
+ unconditional PutObject pass for a create-only one, so a wrong report here is the safe direction: it names a
773
+ policy the provisioning script did not write, and the fix is to reprovision.
774
+ """
775
+ problems = []
776
+ for wanted in CREATE_ONLY_DENIES:
777
+ if any(condition_of(statement) == wanted for statement in put_denials(documents, objects)):
778
+ continue
779
+ shape = json.dumps(wanted, sort_keys=True)
780
+ problems.append(f"the uploader {arn} has no Deny of s3:PutObject on the bucket's objects conditioned on "
781
+ f"{shape}, so an unconditional PUT can replace an object the grant already allowed")
782
+ return problems
783
+
784
+
785
+ def put_denials(documents, objects):
786
+ """Every Deny statement in these policies that names s3:PutObject exactly and covers the bucket's objects.
787
+
788
+ The action is matched by name rather than by pattern on purpose: this check is about one statement the
789
+ provisioning script writes, and a policy denying the same thing some other way is reported as missing
790
+ rather than accepted. judge is where patterns are read, and it reports what it cannot enumerate.
791
+ """
792
+ for document in documents:
793
+ statements = document.get("Statement") or []
794
+ if isinstance(statements, dict):
795
+ statements = [statements]
796
+ for statement in statements:
797
+ if statement.get("Effect") != "Deny" or statement.get("NotAction") is not None:
798
+ continue
799
+ if "s3:PutObject" not in as_list(statement.get("Action")):
800
+ continue
801
+ if statement.get("NotResource") is not None:
802
+ continue
803
+ # Protection again, so coverage rather than overlap: a create-only deny scoped to another prefix
804
+ # leaves every archive object replaceable, and is reported missing rather than found.
805
+ if any(resource_covers(resource, objects) for resource in as_list(statement.get("Resource"))):
806
+ yield statement
807
+
808
+
809
+ def condition_of(statement):
810
+ """One statement's Condition block, with every operator, key and value normalised to a single string value.
811
+
812
+ IAM accepts a condition value as a string or as a list holding one, and reads the two the same way, so the
813
+ comparison would otherwise call an equivalent policy missing.
814
+ """
815
+ block = statement.get("Condition")
816
+ if not isinstance(block, dict):
817
+ return None
818
+ read = {}
819
+ for operator, keyed in block.items():
820
+ if not isinstance(keyed, dict):
821
+ return None
822
+ for key, value in keyed.items():
823
+ if isinstance(value, list):
824
+ if len(value) != 1:
825
+ return None
826
+ value = value[0]
827
+ read.setdefault(operator, {})[key] = value
828
+ return read
829
+
830
+
831
+ def read_policies(operator, kind, name):
832
+ """(the identity's inline policy documents, its attached managed policies, its inline policy names).
833
+
834
+ The aws CLI follows Marker to the end of a truncated IAM listing and merges the pages, so these reads return
835
+ everything the identity holds. A partial read would look exactly like a clean audit, so the test serves the
836
+ listings one page at a time to hold that behaviour in place. Nothing here may pass --no-paginate.
837
+ """
838
+ listed = operator.document_of(f"list-{kind}-policies", kind, name, "PolicyNames")
839
+ attached = operator.document_of(f"list-attached-{kind}-policies", kind, name, "AttachedPolicies")
840
+ if listed is None or attached is None:
841
+ return None, None, None
842
+ documents = []
843
+ for policy in listed:
844
+ found = operator.document_of(f"get-{kind}-policy", kind, name, "PolicyDocument", "--policy-name", policy)
845
+ if found is None:
846
+ return None, None, None
847
+ documents.append(found)
848
+ return documents, sorted(p.get("PolicyName", "(unnamed)") for p in attached), sorted(listed)
849
+
850
+
851
+ # S3 splits its actions by the resource type they act on, and a statement reaches an action only when its
852
+ # Resource names that type: a bucket action needs the bucket ARN and an object action needs an object ARN under
853
+ # it. A deny scoped to the bucket alone therefore denies no object write, however its action list reads.
854
+ BUCKET_ACTIONS = ("s3:ListBucket", "s3:PutBucketPolicy", "s3:PutBucketVersioning", "s3:PutLifecycleConfiguration",
855
+ "s3:DeleteBucket", "s3:DeleteBucketPolicy")
856
+
857
+
858
+ def judged_actions():
859
+ """Every action the audit has an opinion about, which is what it can report an Allow or a Deny of."""
860
+ return set(GRANTS["uploader"]) | set(GRANTS["recovery"]) | set(DENIES) | {BUCKET_GRANT}
861
+
862
+
863
+ def judge(documents, bucket):
864
+ """({action: the effects these policies reach it with}, [what the audit could not evaluate]).
865
+
866
+ One statement reaches one action when its Effect, its actions and its resources all line up, each judged
867
+ exactly: the action by name or by a wildcard that covers it, the resource by whether it names the bucket or
868
+ an object under it as that action requires. An unconditional Deny is reported as a Deny and a conditional
869
+ one is not, because a condition is what decides whether the deny ever matches a request, and the uploader's
870
+ create-only denies are the only conditional ones the script writes. create_only_problems judges those on
871
+ their conditions, so the two checks stay apart.
872
+
873
+ The second half of the pair is every construct the evaluator does not model. Reporting them is the point:
874
+ NotAction and NotResource invert the match, a wildcard reaching more than one judged action says nothing
875
+ about what else it reaches, and each used to be read as something convenient and wrong.
876
+ """
877
+ decisions, unreadable = {}, []
878
+ objects, bucket_arn = f"arn:aws:s3:::{bucket}/*", f"arn:aws:s3:::{bucket}"
879
+ for document in documents:
880
+ statements = document.get("Statement") or []
881
+ if isinstance(statements, dict):
882
+ statements = [statements]
883
+ for statement in statements:
884
+ effect, where = statement.get("Effect"), statement.get("Sid") or "(unnamed)"
885
+ if effect not in ("Allow", "Deny"):
886
+ unreadable.append(f"has statement {where} with Effect {effect!r}, which is neither Allow nor Deny")
887
+ continue
888
+ for field, why in (("NotAction", "matches every action except the ones it lists"),
889
+ ("NotResource", "matches every resource except the ones it lists")):
890
+ if statement.get(field) is not None:
891
+ unreadable.append(f"has statement {where} using {field}, which {why} and the audit does not "
892
+ f"evaluate: the provisioning script writes only Action and Resource")
893
+ if statement.get("NotAction") is not None or statement.get("NotResource") is not None:
894
+ continue
895
+ named = as_list(statement.get("Action"))
896
+ resources = as_list(statement.get("Resource"))
897
+ wide = [action for action in named if "*" in action or "?" in action
898
+ if len({a for a in judged_actions() if action_matches(action, a)}) > 1]
899
+ unreadable += [f"has statement {where} naming {action}, a pattern reaching more than one action, and "
900
+ f"the audit cannot tell what else it reaches: name each action"
901
+ f"" for action in sorted(set(wide))]
902
+ conditioned = statement.get("Condition") is not None
903
+ # A grant is judged by whether it could reach an archive object, a deny by whether it covers every
904
+ # one. The effect picks the direction, so a deny scoped to another prefix records nothing.
905
+ reaches = resource_overlaps if effect == "Allow" else resource_covers
906
+ for action in judged_actions():
907
+ if not any(action_matches(pattern, action) for pattern in named):
908
+ continue
909
+ wanted = bucket_arn if action in BUCKET_ACTIONS else objects
910
+ if not any(reaches(resource, wanted) for resource in resources):
911
+ continue
912
+ # A conditional deny is not the unconditional protection the required-deny check looks for, and
913
+ # an Allow is counted however it is conditioned: a grant that may apply is a grant.
914
+ if effect == "Deny" and conditioned:
915
+ continue
916
+ decisions.setdefault(action, set()).add(effect)
917
+ return decisions, unreadable
918
+
919
+
920
+ def as_list(value):
921
+ """A policy field that IAM accepts as a string or a list of them, always as a list."""
922
+ return [value] if isinstance(value, str) else [v for v in (value or ()) if isinstance(v, str)]
923
+
924
+
925
+ def action_matches(pattern, action):
926
+ """Whether one Action entry names this action. IAM's * is any run of characters and ? is exactly one."""
927
+ return re.fullmatch(wildcard(pattern), action, re.IGNORECASE) is not None
928
+
929
+
930
+ # A Resource entry is compared against the ARN an action needs in one of two directions, and which one is the
931
+ # safe direction depends on the effect. A grant is a problem when it reaches any archive object, so an Allow
932
+ # asks whether the two could overlap at all and over-reports rather than miss one. A deny is the protection the
933
+ # audit is looking for, so it has to cover every archive object, and only the resources the provisioning script
934
+ # writes are accepted as doing that. Reading both the same way is what let a deny on `bucket/other/*` pass for
935
+ # the protection on `bucket/*`. Two functions rather than one with a flag: the direction is the whole meaning,
936
+ # and the call site names which it wants.
937
+
938
+ def resource_overlaps(pattern, wanted):
939
+ """Whether a Resource entry could name any ARN the wanted pattern covers. For judging a grant.
940
+
941
+ Both `bucket/*` and `bucket/evidence/*` reach an object under `bucket/*`, so the comparison runs each way:
942
+ an extra grant on a narrower prefix is still an extra grant on the archive's objects. Matching a pattern
943
+ against a pattern over-reports here, which is the direction a grant check should err in.
944
+ """
945
+ return _segments(pattern, wanted, lambda held, asked: _like(held, asked) or _like(asked, held))
946
+
947
+
948
+ def resource_covers(pattern, wanted):
949
+ """Whether a Resource entry is one the provisioning script writes for this ARN. For judging protection.
950
+
951
+ The wanted side is a pattern, not a key: `arn:aws:s3:::bucket/*` is the whole set of objects, and the
952
+ audit holds only two of them, that set and the bucket itself. Deciding coverage by matching the Resource
953
+ against that text cannot prove the Resource reaches every key the text denotes, and it answered yes to
954
+ things that reach almost none: `bucket/?` covers only single-character keys, while every archive object
955
+ is a 64-character hash or a snapshots/ path, yet `?` matched the literal `*` and the deny was counted.
956
+
957
+ So coverage is the exact resource or a bare `*`, which genuinely does cover everything. The script writes
958
+ `[<bucket>, <bucket>/*]` for the unconditional deny and `[<bucket>/*]` for each create-only one, so this
959
+ accepts what it writes and reports anything else missing. A policy that protects the same objects by some
960
+ other spelling is reported too, and the fix for that report is to reprovision. Working out which IAM
961
+ patterns contain which others is a real evaluator with its own false cleans, and every false clean found
962
+ in this audit so far has come from reading a policy more loosely than it was written.
963
+ """
964
+ # A bare "*" is every resource in every service, so it does cover the wanted one.
965
+ return pattern == wanted or pattern == "*"
966
+
967
+
968
+ def _segments(pattern, wanted, decide):
969
+ """`decide` applied segment by segment to an ARN pair. A wildcard cannot span an ARN's colons.
970
+
971
+ A bare `*` is every resource, so it short-circuits before the segments are compared, and an ARN with a
972
+ different number of colon-separated segments is not the one asked about whatever `decide` would say.
973
+ """
974
+ if pattern == "*":
975
+ return True
976
+ held, asked = pattern.split(":"), wanted.split(":")
977
+ if len(held) != len(asked):
978
+ return False
979
+ return all(decide(h, a) for h, a in zip(held, asked))
980
+
981
+
982
+ def _like(pattern, wanted):
983
+ """Whether one ARN segment's IAM pattern matches the other segment. Only resource_overlaps needs it."""
984
+ return re.fullmatch(wildcard(pattern), wanted) is not None
985
+
986
+
987
+ def wildcard(pattern):
988
+ """One IAM pattern as a regular expression, with * and ? as IAM reads them and everything else literal."""
989
+ return "".join(".*" if part == "*" else "." if part == "?" else re.escape(part)
990
+ for part in re.split(r"([*?])", pattern))