@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,462 @@
1
+ """The archive checker's configuration, its local run, and the provisioning and audit of the deployed one.
2
+
3
+ archive.py is the only caller. The judgement is archive_health's, and the deployed checker is the Lambda in
4
+ archive_checker_lambda.py. This module reads the checker configuration, runs a check against a local remote, and
5
+ for an S3 remote prints the script that deploys the Lambda and reads back how the deployment differs from it.
6
+ See archiving-checker.md.
7
+ """
8
+
9
+ import base64
10
+ import hashlib
11
+ import io
12
+ import json
13
+ import os
14
+ import shlex
15
+ import sys
16
+ import zipfile
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+
20
+ import archive_checker_lambda
21
+ import archive_health
22
+ import archive_remote
23
+ from archive_remote import Refused
24
+
25
+ # Every setting a checker configuration may hold, and what kind of value it takes.
26
+ FIELDS = {"remote": "path", "journal": "path?", "alerts": "path?", "quiet": "windows?"}
27
+ # The two a local remote needs, and what each directory holds. The deployed checker has fixed AWS names instead.
28
+ LOCAL_ONLY = {"journal": "check records", "alerts": "alerts"}
29
+
30
+ # What provisioning names in the account. One checker per account, so the names are fixed, not configured.
31
+ FUNCTION = "evidence-archive-checker"
32
+ ROLE = "evidence-archive-checker"
33
+ SCHEDULE_ROLE = "evidence-archive-checker-schedule"
34
+ SCHEDULE = "evidence-archive-check"
35
+ TOPIC = "evidence-archive-alerts"
36
+ JOURNAL = "evidence-archive-checks"
37
+ RUNTIME = "python3.13"
38
+ HANDLER = "archive_checker_lambda.handler"
39
+ TIMEOUT_SECONDS = 60
40
+ MEMORY_MB = 128
41
+ RATE = "rate(10 minutes)"
42
+ SETTINGS = archive_checker_lambda.SETTINGS
43
+
44
+
45
+ def load_checker(path):
46
+ """A checker configuration: every field checked, relative paths taken from the file's directory."""
47
+ path = Path(path).expanduser().absolute()
48
+ try:
49
+ doc = json.loads(path.read_text())
50
+ except OSError as error:
51
+ raise Refused(f"cannot read the checker configuration {path}: {error.strerror}") from None
52
+ except ValueError:
53
+ raise Refused(f"the checker configuration {path} is not valid JSON") from None
54
+ if not isinstance(doc, dict):
55
+ raise Refused(f"the checker configuration {path} is not a JSON object")
56
+ conf, problems = {"config": path}, []
57
+
58
+ def place(value):
59
+ held = Path(value).expanduser()
60
+ return held if held.is_absolute() else path.parent / held
61
+ for field in sorted(set(doc) - set(FIELDS)):
62
+ problems.append(f"{field} is not a checker setting")
63
+ for field, kind in FIELDS.items():
64
+ value = doc.get(field)
65
+ conf[field] = [] if kind.startswith("windows") else None
66
+ if value is None:
67
+ if not kind.endswith("?"):
68
+ problems.append(f"{field} is required")
69
+ elif kind.startswith("windows"):
70
+ problems += archive_health.quiet_problems(value)
71
+ conf[field] = value
72
+ elif not isinstance(value, str) or not value:
73
+ problems.append(f"{field} must be a path")
74
+ else:
75
+ conf[field] = place(value)
76
+ # The remote's own problems join the list, so one refusal names every fault in both files.
77
+ remote = None
78
+ if conf["remote"] is not None:
79
+ try:
80
+ remote = archive_remote.load_remote(conf["remote"])
81
+ except Refused as why:
82
+ problems.append(str(why))
83
+ if remote is not None:
84
+ unready = archive_remote.check(remote)
85
+ if unready:
86
+ problems.append(archive_remote.explain(remote, unready))
87
+ if remote.kind == "local":
88
+ problems += [f"{field} is required for a local remote: the directory its {held} go to"
89
+ for field, held in LOCAL_ONLY.items() if conf[field] is None]
90
+ else:
91
+ problems += [f"{field} is a local remote's setting: the deployed checker appends to the log group "
92
+ f"{JOURNAL} and alerts through the topic {TOPIC}" for field in LOCAL_ONLY if doc.get(field) is not None]
93
+ if problems:
94
+ raise Refused(f"the checker configuration {path} is not usable: {'; '.join(problems)}")
95
+ conf["remote"] = remote
96
+ return conf
97
+
98
+
99
+ def run_local(conf, now=None):
100
+ """One check against a local remote, recorded in the configured journal, alerting into the alerts directory."""
101
+ now = now or datetime.now(timezone.utc)
102
+ remote = conf["remote"]
103
+ if remote.kind != "local":
104
+ raise Refused(f"checker run reads a local remote, and {remote.path} is an {remote.kind} one: the deployed checker "
105
+ "is the Lambda, so invoke it with aws lambda invoke, as archiving-checker.md shows")
106
+ store = archive_remote.open_store(remote, "recovery")
107
+ faults = store.faults
108
+ journal = archive_health.StoreJournal(archive_remote.LocalStore(conf["journal"], faults))
109
+ alerts = archive_health.StoreAlerts(archive_remote.LocalStore(conf["alerts"], faults))
110
+ return archive_health.run(store, journal, alerts, now, conf["quiet"])
111
+
112
+
113
+ # ---- the deployment package --------------------------------------------------------------------------
114
+
115
+ # What the Lambda runs: the judgement and the handler. boto3 is the runtime's own.
116
+ PACKAGE = ("archive_health.py", "archive_checker_lambda.py")
117
+
118
+
119
+ def package_bytes():
120
+ """The Lambda's deployment package, the same bytes for the same checkout every time.
121
+
122
+ Stored uncompressed, with a fixed time and mode on each entry, so no zlib version or file time can change a
123
+ byte. The audit hashes it the way Lambda reports CodeSha256 and compares the two, which is how it tells
124
+ whether the deployed code is this checkout's.
125
+ """
126
+ buffer = io.BytesIO()
127
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_STORED) as zipped:
128
+ for name in PACKAGE:
129
+ entry = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
130
+ entry.create_system, entry.external_attr = 3, 0o100644 << 16
131
+ zipped.writestr(entry, (Path(__file__).parent / name).read_bytes())
132
+ return buffer.getvalue()
133
+
134
+
135
+ def code_sha256(data):
136
+ """A package's hash as Lambda reports it: the base64 of its SHA-256 digest."""
137
+ return base64.b64encode(hashlib.sha256(data).digest()).decode()
138
+
139
+
140
+ def write_package(out):
141
+ data = package_bytes()
142
+ out = Path(out).absolute()
143
+ try:
144
+ out.parent.mkdir(parents=True, exist_ok=True)
145
+ out.write_bytes(data)
146
+ except OSError as error:
147
+ raise Refused(f"cannot write the package to {out}: {error.strerror or error}") from None
148
+ return {"package": str(out), "bytes": len(data), "code_sha256": code_sha256(data)}
149
+
150
+
151
+ # ---- provisioning and its audit ------------------------------------------------------------------------
152
+ #
153
+ # Everything the script creates is written here once, as data, and both the script and the audit read it, so the
154
+ # two cannot come to disagree about what a correct deployment is.
155
+
156
+ def require_s3(conf, verb):
157
+ remote = conf["remote"]
158
+ if remote.kind != "s3":
159
+ raise Refused(f"checker {verb} applies to an s3 remote, and {remote.path} is a {remote.kind} one")
160
+ return remote
161
+
162
+
163
+ def deployment(conf):
164
+ """What a correct deployment holds: the two roles, the function, its settings, the schedule, topic and journal."""
165
+ remote = conf["remote"]
166
+ account, region, bucket = remote.get("account"), remote.get("region"), remote.get("bucket")
167
+ prefix = remote.get("prefix") or ""
168
+ prefix = prefix if not prefix or prefix.endswith("/") else f"{prefix}/"
169
+ topic = f"arn:aws:sns:{region}:{account}:{TOPIC}"
170
+ function = f"arn:aws:lambda:{region}:{account}:function:{FUNCTION}"
171
+ journal = f"arn:aws:logs:{region}:{account}:log-group:{JOURNAL}"
172
+ own_log = f"arn:aws:logs:{region}:{account}:log-group:/aws/lambda/{FUNCTION}"
173
+ health = f"{prefix}health/*"
174
+ checker_policy = {"Version": "2012-10-17", "Statement": [
175
+ # The health snapshots' names and no others, which is all archive_health.newest lists. archiving-checker.md
176
+ # says why the checker carries the condition the uploader's grant must not.
177
+ {"Sid": "HealthList", "Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": f"arn:aws:s3:::{bucket}",
178
+ "Condition": {"StringLike": {"s3:prefix": health}}},
179
+ {"Sid": "HealthRead", "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": f"arn:aws:s3:::{bucket}/{health}"},
180
+ {"Sid": "AlertPublish", "Effect": "Allow", "Action": ["sns:Publish"], "Resource": topic},
181
+ {"Sid": "ChecksAppend", "Effect": "Allow", "Action": ["logs:CreateLogStream", "logs:PutLogEvents", "logs:GetLogEvents"],
182
+ "Resource": [journal, f"{journal}:*"]},
183
+ {"Sid": "ChecksNeverRemoved", "Effect": "Deny",
184
+ "Action": ["logs:DeleteLogGroup", "logs:DeleteLogStream", "logs:PutRetentionPolicy", "logs:DeleteRetentionPolicy"],
185
+ "Resource": [journal, f"{journal}:*"]},
186
+ {"Sid": "FunctionLog", "Effect": "Allow", "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
187
+ "Resource": [own_log, f"{own_log}:*"]}]}
188
+ schedule_policy = {"Version": "2012-10-17", "Statement": [
189
+ {"Sid": "InvokeChecker", "Effect": "Allow", "Action": ["lambda:InvokeFunction"], "Resource": [function, f"{function}:*"]}]}
190
+
191
+ def trust(service, **condition):
192
+ return {"Version": "2012-10-17", "Statement": [dict(
193
+ {"Effect": "Allow", "Principal": {"Service": service}, "Action": "sts:AssumeRole"},
194
+ **({"Condition": condition} if condition else {}))]}
195
+ settings = {"bucket": bucket, "prefix": prefix, "region": region, "topic": topic, "journal": JOURNAL,
196
+ "quiet": conf["quiet"]}
197
+ try:
198
+ archive_checker_lambda.load_settings(json.dumps(settings))
199
+ except ValueError as why:
200
+ raise Refused(f"the checker could not run with what this configuration provisions: {why}") from None
201
+ return {
202
+ "account": account, "region": region, "topic": topic, "function_arn": function, "settings": settings,
203
+ "roles": {ROLE: {"arn": f"arn:aws:iam::{account}:role/{ROLE}", "trust": trust("lambda.amazonaws.com"),
204
+ "policy": checker_policy, "description": "Evidence archive checker: reads health snapshots, appends checks, alerts"},
205
+ SCHEDULE_ROLE: {"arn": f"arn:aws:iam::{account}:role/{SCHEDULE_ROLE}",
206
+ "trust": trust("scheduler.amazonaws.com", StringEquals={"aws:SourceAccount": account}),
207
+ "policy": schedule_policy, "description": "Evidence archive checker schedule: invokes the checker"}},
208
+ "function": {"Runtime": RUNTIME, "Handler": HANDLER, "Role": f"arn:aws:iam::{account}:role/{ROLE}",
209
+ "Timeout": TIMEOUT_SECONDS, "MemorySize": MEMORY_MB},
210
+ "environment": {"Variables": {SETTINGS: json.dumps(settings, sort_keys=True)}},
211
+ "schedule": {"ScheduleExpression": RATE, "State": "ENABLED", "FlexibleTimeWindow": {"Mode": "OFF"},
212
+ "Target": {"Arn": function, "RoleArn": f"arn:aws:iam::{account}:role/{SCHEDULE_ROLE}", "Input": "{}"}},
213
+ }
214
+
215
+
216
+ def provision_script(conf):
217
+ """The shell script that deploys the checker. It is printed for an owner to read and run, and runs again safely."""
218
+ remote = require_s3(conf, "provision")
219
+ wanted = deployment(conf)
220
+ account, region = wanted["account"], wanted["region"]
221
+ profile = f" --profile {shlex.quote(remote.get('profile'))}" if remote.get("profile") else ""
222
+ aws = f"aws --region {region}{profile}"
223
+ # The same account as environment variables, for the aws commands the guidance gives the owner to run.
224
+ environment = f"AWS_REGION={region}" + (f" AWS_PROFILE={remote.get('profile')}" if remote.get("profile") else "")
225
+ quote = lambda doc: shlex.quote(json.dumps(doc, sort_keys=True))
226
+ fn = wanted["function"]
227
+ configure = (f"--runtime {fn['Runtime']} --handler {fn['Handler']} --role {fn['Role']} \\\n"
228
+ f" --timeout {fn['Timeout']} --memory-size {fn['MemorySize']} \\\n"
229
+ f" --environment {quote(wanted['environment'])}")
230
+ schedule = wanted["schedule"]
231
+ timing = (f"--schedule-expression {shlex.quote(schedule['ScheduleExpression'])} --state {schedule['State']} \\\n"
232
+ f" --flexible-time-window {quote(schedule['FlexibleTimeWindow'])} \\\n"
233
+ f" --target {quote(schedule['Target'])}")
234
+ python = shlex.quote(sys.executable)
235
+ # The Sids of a function's resource policy, read from the JSON document `get-policy` returns as a string.
236
+ sids = shlex.quote('import json, sys; print(" ".join(s["Sid"] for s in json.load(sys.stdin)["Statement"]))')
237
+ lines = [
238
+ "#!/usr/bin/env bash",
239
+ f"# Deploy the evidence archive checker to account {account} in {region}. archive.py printed this and ran",
240
+ "# none of it: read it, then run it as an administrator of that account. A rerun updates everything in place,",
241
+ "# which is how a changed quiet window reaches the checker, and removes the extra policies, layers, resource",
242
+ "# policy statements and retention policy `checker audit` reports, so that running it again fixes that drift.",
243
+ "set -euo pipefail",
244
+ ': "${ALERT_EMAIL:?set it to the address alerts go to: it is passed to SNS and written to no file}"',
245
+ f'test "$({aws} sts get-caller-identity --query Account --output text)" = {account}',
246
+ 'exists() { "$@" >/dev/null 2>&1; }',
247
+ "# IAM can take a few seconds before Lambda or Scheduler may assume a role it has just created.",
248
+ 'retry() { local n; for n in 1 2 3 4 5 6; do "$@" && return 0; [ "$n" = 6 ] || sleep 10; done; return 1; }',
249
+ 'PACKAGE="$(mktemp -d)/evidence-archive-checker.zip"',
250
+ f'{python} {shlex.quote(str(Path(__file__).parent / "archive.py"))} checker package --out "$PACKAGE"',
251
+ "",
252
+ "# The topic alerts go to, and the owner's address on it. #317's budget alert publishes to this topic too.",
253
+ f"{aws} sns create-topic --name {TOPIC}",
254
+ f'{aws} sns subscribe --topic-arn {wanted["topic"]} --protocol email --notification-endpoint "$ALERT_EMAIL"',
255
+ "",
256
+ "# The journal check records are appended to. It has no retention policy, so no record ever expires.",
257
+ f"exists {aws} logs describe-log-streams --log-group-name {JOURNAL} --limit 1 \\",
258
+ f" || {aws} logs create-log-group --log-group-name {JOURNAL}",
259
+ "# Log groups list in name order, so the first under this prefix is the journal itself.",
260
+ f"retention=\"$({aws} logs describe-log-groups --log-group-name-prefix {JOURNAL} \\",
261
+ " --query 'logGroups[0].retentionInDays' --output text)\"",
262
+ f'[ "$retention" = None ] || {aws} logs delete-retention-policy --log-group-name {JOURNAL}',
263
+ "",
264
+ ]
265
+ for name, role in wanted["roles"].items():
266
+ lines += [f"exists {aws} iam get-role --role-name {name} \\",
267
+ f" || {aws} iam create-role --role-name {name} --description {shlex.quote(role['description'])} \\",
268
+ f" --assume-role-policy-document {quote(role['trust'])}",
269
+ f"{aws} iam update-assume-role-policy --role-name {name} --policy-document {quote(role['trust'])}",
270
+ f"{aws} iam put-role-policy --role-name {name} --policy-name {name} \\",
271
+ f" --policy-document {quote(role['policy'])}",
272
+ "# The role holds this one inline policy and no managed policy.",
273
+ f"policies=\"$({aws} iam list-role-policies --role-name {name} --query 'PolicyNames[]' --output text)\"",
274
+ "for policy in $policies; do",
275
+ f' [ "$policy" = {name} ] || {aws} iam delete-role-policy --role-name {name} --policy-name "$policy"',
276
+ "done",
277
+ f"policies=\"$({aws} iam list-attached-role-policies --role-name {name} \\",
278
+ " --query 'AttachedPolicies[].PolicyArn' --output text)\"",
279
+ "for policy in $policies; do",
280
+ f' {aws} iam detach-role-policy --role-name {name} --policy-arn "$policy"',
281
+ "done", ""]
282
+ lines += [
283
+ f"if exists {aws} lambda get-function --function-name {FUNCTION}; then",
284
+ f' {aws} lambda update-function-code --function-name {FUNCTION} --zip-file "fileb://$PACKAGE"',
285
+ f" {aws} lambda wait function-updated-v2 --function-name {FUNCTION}",
286
+ " # An empty Layers list removes every layer, whose modules would come before the runtime's boto3.",
287
+ f" {aws} lambda update-function-configuration --function-name {FUNCTION} {configure} \\",
288
+ " --cli-input-json '{\"Layers\": []}'",
289
+ f" {aws} lambda wait function-updated-v2 --function-name {FUNCTION}",
290
+ " # The schedule invokes the function through its own role, so the function's resource policy allows nothing.",
291
+ f" if exists {aws} lambda get-policy --function-name {FUNCTION}; then",
292
+ f" statements=\"$({aws} lambda get-policy --function-name {FUNCTION} --query Policy --output text | {python} -c {sids})\"",
293
+ " for statement in $statements; do",
294
+ f' {aws} lambda remove-permission --function-name {FUNCTION} --statement-id "$statement"',
295
+ " done",
296
+ " fi",
297
+ "else",
298
+ f' retry {aws} lambda create-function --function-name {FUNCTION} --zip-file "fileb://$PACKAGE" {configure}',
299
+ f" {aws} lambda wait function-active-v2 --function-name {FUNCTION}",
300
+ "fi",
301
+ "# A failed check is not retried: the next one is ten minutes away, and a retry would append a second record.",
302
+ f"{aws} lambda put-function-event-invoke-config --function-name {FUNCTION} --maximum-retry-attempts 0",
303
+ "",
304
+ f"if exists {aws} scheduler get-schedule --name {SCHEDULE}; then",
305
+ f" {aws} scheduler update-schedule --name {SCHEDULE} {timing}",
306
+ "else",
307
+ f" retry {aws} scheduler create-schedule --name {SCHEDULE} {timing}",
308
+ "fi",
309
+ "",
310
+ "echo " + shlex.quote("Next: confirm the subscription from the email AWS sent, then run python3 "
311
+ f"{shlex.quote(str(Path(__file__).parent / 'archive.py'))} checker audit --config "
312
+ f"{shlex.quote(str(conf['config']))}"),
313
+ "echo " + shlex.quote(f"The commands in archiving-checker.md take the account from: export {environment}"),
314
+ "",
315
+ ]
316
+ return "\n".join(lines)
317
+
318
+
319
+ ABSENT = ("NoSuchEntity", "ResourceNotFoundException", "NotFound")
320
+
321
+
322
+ def read_deployed(operator, service, *args):
323
+ """One read of the deployment as the operator's own credentials: the reply, or None when the thing is absent.
324
+
325
+ Any other failure raises. S3Store.document_of is not reused because it answers None for every failure, and a
326
+ refused read taken for an absent resource would be reported as a missing one, or pass where it should stop.
327
+ """
328
+ status, out, text = operator.call(*args, "--output", "json", service=service)
329
+ if status == 0:
330
+ try:
331
+ return json.loads(out or b"{}")
332
+ except ValueError as error:
333
+ raise archive_remote.StoreError(f"{service} {args[0]} returned a reply that is not JSON: {error}") from error
334
+ code = (archive_remote.AWS_ERROR_CODE.search(text) or [None, None])[1]
335
+ if code in ABSENT:
336
+ return None
337
+ raise archive_remote.StoreError(f"{service} {args[0]} failed with {code or 'no error code'}: {text}")
338
+
339
+
340
+ def statements(doc):
341
+ """A policy's statements by Sid, each with its Action and Resource as sorted lists, for comparing exactly."""
342
+ held = (doc or {}).get("Statement") or []
343
+ held = [held] if isinstance(held, dict) else held
344
+ found = {}
345
+ for index, statement in enumerate(held):
346
+ if not isinstance(statement, dict):
347
+ continue
348
+ normal = dict(statement)
349
+ for field in ("Action", "Resource"):
350
+ if field in normal:
351
+ normal[field] = sorted(archive_remote.as_list(normal[field]))
352
+ found[statement.get("Sid") or f"(unnamed {index + 1})"] = json.dumps(normal, sort_keys=True)
353
+ return found
354
+
355
+
356
+ def policy_problems(name, held, wanted):
357
+ """How one role's inline policy differs from the one provisioning writes, statement by statement."""
358
+ have, want = statements(held), statements(wanted)
359
+ problems = [f"the role {name}'s policy lacks statement {sid}" for sid in sorted(set(want) - set(have))]
360
+ problems += [f"the role {name}'s policy has statement {sid}, which provisioning does not write"
361
+ for sid in sorted(set(have) - set(want))]
362
+ problems += [f"the role {name}'s policy statement {sid} differs from what provisioning writes"
363
+ for sid in sorted(set(have) & set(want)) if have[sid] != want[sid]]
364
+ return problems
365
+
366
+
367
+ def audit(conf):
368
+ """How the deployed checker differs from what the provisioning script writes, read as the operator's own credentials.
369
+
370
+ Each resource is held to the script exactly: an extra statement, permission, policy or setting is a problem
371
+ however harmless it looks, and the fix is to run the script again. The one exception is a subscription to the
372
+ topic, which the script adds and never removes. Every one that is not email is reported, and with ALERT_EMAIL in
373
+ the environment, so is the lack of a subscription for it, without the address being printed. A read the
374
+ operator is refused stops the audit with an error rather than passing what it could not see.
375
+ """
376
+ remote = require_s3(conf, "audit")
377
+ wanted = deployment(conf)
378
+ operator = archive_remote.S3Store(remote.get("bucket"), None, None, remote.get("region"), remote.get("profile"))
379
+ problems = []
380
+ for name, role in wanted["roles"].items():
381
+ found = read_deployed(operator, "iam", "get-role", "--role-name", name)
382
+ if found is None:
383
+ problems.append(f"the role {name} does not exist")
384
+ continue
385
+ if statements(found["Role"].get("AssumeRolePolicyDocument")) != statements(role["trust"]):
386
+ problems.append(f"the role {name} has a trust policy other than the one provisioning writes")
387
+ names = read_deployed(operator, "iam", "list-role-policies", "--role-name", name)["PolicyNames"]
388
+ problems += [f"the role {name} has the inline policy {extra}, which provisioning does not write"
389
+ for extra in sorted(set(names) - {name})]
390
+ if name in names:
391
+ policy = read_deployed(operator, "iam", "get-role-policy", "--role-name", name, "--policy-name", name)
392
+ problems += policy_problems(name, policy["PolicyDocument"], role["policy"])
393
+ else:
394
+ problems.append(f"the role {name} lacks its inline policy {name}")
395
+ attached = read_deployed(operator, "iam", "list-attached-role-policies", "--role-name", name)["AttachedPolicies"]
396
+ problems += [f"the role {name} has the managed policy {policy.get('PolicyName')} attached, which provisioning "
397
+ f"does not attach" for policy in attached]
398
+ function = read_deployed(operator, "lambda", "get-function-configuration", "--function-name", FUNCTION)
399
+ if function is None:
400
+ problems.append(f"the function {FUNCTION} does not exist")
401
+ else:
402
+ problems += [f"the function's {field} is {function.get(field)!r}, not {value!r}"
403
+ for field, value in wanted["function"].items() if function.get(field) != value]
404
+ # A layer's modules come before the runtime's on the path, so one could replace the boto3 the handler
405
+ # imports while the function's own code still hashes to this checkout's.
406
+ problems += [f"the function has the layer {layer.get('Arn')}, which provisioning does not add"
407
+ for layer in function.get("Layers") or []]
408
+ if read_deployed(operator, "lambda", "get-policy", "--function-name", FUNCTION) is not None:
409
+ problems.append("the function has a resource policy, which provisioning does not write: the schedule "
410
+ "invokes it through its own role, so nothing else should be allowed to")
411
+ variables = (function.get("Environment") or {}).get("Variables") or {}
412
+ try:
413
+ deployed = json.loads(variables.get(SETTINGS) or "null")
414
+ except ValueError:
415
+ deployed = None
416
+ if deployed != wanted["settings"] or set(variables) != {SETTINGS}:
417
+ problems.append(f"the function's {SETTINGS} settings are not the ones this configuration provisions: "
418
+ "a changed quiet window reaches the checker only when the script runs again")
419
+ if function.get("CodeSha256") != code_sha256(package_bytes()):
420
+ problems.append(f"the function's code is not this checkout's checker: its CodeSha256 is "
421
+ f"{function.get('CodeSha256')}, and this checkout's package hashes to {code_sha256(package_bytes())}")
422
+ retries = read_deployed(operator, "lambda", "get-function-event-invoke-config", "--function-name", FUNCTION)
423
+ if (retries or {}).get("MaximumRetryAttempts") != 0:
424
+ problems.append(f"the function's failed invocations are retried "
425
+ f"{'twice, by default' if retries is None else retries.get('MaximumRetryAttempts')}, not 0 times")
426
+ schedule = read_deployed(operator, "scheduler", "get-schedule", "--name", SCHEDULE)
427
+ if schedule is None:
428
+ problems.append(f"the schedule {SCHEDULE} does not exist")
429
+ else:
430
+ for field, setting in wanted["schedule"].items():
431
+ for key, value in (setting.items() if isinstance(setting, dict) else [(None, setting)]):
432
+ have = schedule.get(field) if key is None else (schedule.get(field) or {}).get(key)
433
+ if have != value:
434
+ problems.append(f"the schedule's {field if key is None else f'{field}.{key}'} is {have!r}, not {value!r}")
435
+ if read_deployed(operator, "sns", "get-topic-attributes", "--topic-arn", wanted["topic"]) is None:
436
+ problems.append(f"the topic {wanted['topic']} does not exist")
437
+ else:
438
+ found = read_deployed(operator, "sns", "list-subscriptions-by-topic", "--topic-arn", wanted["topic"])
439
+ subscriptions = (found or {}).get("Subscriptions") or []
440
+ # Alerts carry the check's reasons, so a subscription other than the owner's email is a reader nobody chose.
441
+ problems += [f"the topic {TOPIC} has a {s.get('Protocol')} subscription, and provisioning makes only the "
442
+ "owner's email one: unsubscribe it" for s in subscriptions if s.get("Protocol") != "email"]
443
+ emails = [s for s in subscriptions if s.get("Protocol") == "email"]
444
+ expected = os.environ.get("ALERT_EMAIL")
445
+ owners = [s for s in emails if s.get("Endpoint") == expected] if expected else emails
446
+ if not emails:
447
+ problems.append(f"the topic {TOPIC} has no email subscription, so no alert reaches anyone")
448
+ elif not owners:
449
+ problems.append(f"the topic {TOPIC} has no email subscription for ALERT_EMAIL, so alerts go to someone else")
450
+ elif len(emails) > 1:
451
+ problems.append(f"the topic {TOPIC} has {len(emails)} email subscriptions, and provisioning makes one, "
452
+ "the owner's: unsubscribe the others, which a run with another ALERT_EMAIL leaves behind")
453
+ elif all(s.get("SubscriptionArn") in ("PendingConfirmation", "pending confirmation", None) for s in owners):
454
+ problems.append(f"the email subscription to {TOPIC} is not confirmed: follow the link in the email AWS sent")
455
+ groups = read_deployed(operator, "logs", "describe-log-groups", "--log-group-name-prefix", JOURNAL)
456
+ group = next((g for g in (groups or {}).get("logGroups") or [] if g.get("logGroupName") == JOURNAL), None)
457
+ if group is None:
458
+ problems.append(f"the log group {JOURNAL} does not exist")
459
+ elif group.get("retentionInDays"):
460
+ problems.append(f"the log group {JOURNAL} expires its events after {group['retentionInDays']} days, "
461
+ "and check records must never expire")
462
+ return problems
@@ -0,0 +1,155 @@
1
+ """The deployed archive checker: an AWS Lambda that an EventBridge Scheduler schedule invokes every ten minutes.
2
+
3
+ It lists and reads the evidence bucket's health snapshots with its role's read-only grant, judges them with
4
+ archive_health exactly as `archive.py checker run` does, appends the check record to a CloudWatch Logs group the
5
+ role can only append to, and alerts through an SNS topic. boto3 comes with the Lambda runtime, so the package is
6
+ this file and archive_health.py and nothing else. The settings arrive as JSON in ARCHIVE_CHECKER, which
7
+ provisioning writes. See archiving-checker.md.
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ from datetime import datetime, timedelta, timezone
14
+
15
+ import archive_health
16
+
17
+ # The settings contract with provisioning: archive_checker writes these fields under this name, and checks what
18
+ # it writes with load_settings below before it prints anything.
19
+ SETTINGS = "ARCHIVE_CHECKER"
20
+ FIELDS = ("bucket", "prefix", "region", "topic", "journal", "quiet")
21
+ REGION = re.compile(r"[a-z]{2}(-[a-z]+)+-[0-9]")
22
+ TOPIC_ARN = re.compile(r"arn:aws:sns:[a-z]{2}(-[a-z]+)+-[0-9]:[0-9]{12}:[A-Za-z0-9_-]{1,256}")
23
+ LOG_GROUP = re.compile(r"[A-Za-z0-9_./#-]{1,512}")
24
+ # GetLogEvents can answer with an empty page while older events exist, so the read follows the backward token
25
+ # this many times before it decides a stream holds nothing.
26
+ LOG_PAGES = 10
27
+
28
+
29
+ def clock():
30
+ """Now, in UTC. The tests replace it, which is the only way a check's time is chosen."""
31
+ return datetime.now(timezone.utc)
32
+
33
+
34
+ def error_code(error):
35
+ """The AWS error code a botocore ClientError carries, or None for any other exception."""
36
+ response = getattr(error, "response", None)
37
+ return (response.get("Error") or {}).get("Code") if isinstance(response, dict) else None
38
+
39
+
40
+ def load_settings(text):
41
+ """The checker's settings from the ARCHIVE_CHECKER JSON, or ValueError naming every problem at once."""
42
+ if text is None:
43
+ raise ValueError(f"{SETTINGS} is not set: provisioning sets it on the function")
44
+ try:
45
+ doc = json.loads(text)
46
+ except ValueError as error:
47
+ raise ValueError(f"{SETTINGS} is not JSON: {error}") from None
48
+ if not isinstance(doc, dict):
49
+ raise ValueError(f"{SETTINGS} is not a JSON object")
50
+ problems = [f"{field} is not a checker setting" for field in sorted(set(doc) - set(FIELDS))]
51
+ problems += [f"{field} is missing" for field in FIELDS if field not in doc]
52
+ if not isinstance(doc.get("bucket"), str) or not doc.get("bucket"):
53
+ problems.append("bucket must name the evidence bucket")
54
+ if not isinstance(doc.get("prefix"), str):
55
+ problems.append("prefix must be the bucket's key prefix, empty for none")
56
+ for field, shape, needs in (("region", REGION, "the bucket's region, such as us-east-1"),
57
+ ("topic", TOPIC_ARN, "the alert topic's ARN, arn:aws:sns:<region>:<account>:<name>"),
58
+ ("journal", LOG_GROUP, "the log group check records are appended to")):
59
+ if not isinstance(doc.get(field), str) or not shape.fullmatch(doc[field]):
60
+ problems.append(f"{field} {doc.get(field)!r} is not {needs}")
61
+ problems += archive_health.quiet_problems(doc.get("quiet", []))
62
+ if problems:
63
+ raise ValueError(f"{SETTINGS} is not usable: {'; '.join(problems)}")
64
+ return doc
65
+
66
+
67
+ class S3Health:
68
+ """The evidence bucket as archive_health's store: list names under a prefix, read one object's bytes."""
69
+
70
+ def __init__(self, client, bucket, prefix):
71
+ self.client, self.bucket, self.prefix = client, bucket, prefix
72
+
73
+ def list(self, prefix):
74
+ names, token = [], None
75
+ while True:
76
+ page = self.client.list_objects_v2(Bucket=self.bucket, Prefix=self.prefix + prefix,
77
+ **({"ContinuationToken": token} if token else {}))
78
+ names += [item["Key"][len(self.prefix):] for item in page.get("Contents") or []
79
+ if item.get("Key", "").startswith(self.prefix)]
80
+ if not page.get("IsTruncated"):
81
+ return sorted(names)
82
+ token = page["NextContinuationToken"]
83
+
84
+ def read(self, name):
85
+ try:
86
+ return self.client.get_object(Bucket=self.bucket, Key=self.prefix + name)["Body"].read()
87
+ except Exception as error:
88
+ if error_code(error) in ("NoSuchKey", "404"):
89
+ return None
90
+ raise
91
+
92
+
93
+ class LogsJournal:
94
+ """Check records as events in a CloudWatch Logs group, one stream per UTC day, which the role can only append to."""
95
+
96
+ def __init__(self, client, group):
97
+ self.client, self.group = client, group
98
+
99
+ def append(self, record):
100
+ stream = record["at"][:10]
101
+ try:
102
+ self.client.create_log_stream(logGroupName=self.group, logStreamName=stream)
103
+ except Exception as error:
104
+ if error_code(error) != "ResourceAlreadyExistsException":
105
+ raise
106
+ when = archive_health.parse_time(record["at"])
107
+ self.client.put_log_events(logGroupName=self.group, logStreamName=stream, logEvents=[
108
+ {"timestamp": int(when.timestamp() * 1000), "message": json.dumps(record, sort_keys=True)}])
109
+
110
+ def latest(self, today):
111
+ """The newest record from today's stream, or yesterday's when today's has none, or None."""
112
+ for day in (today, today - timedelta(days=1)):
113
+ token = None
114
+ for _ in range(LOG_PAGES):
115
+ try:
116
+ page = self.client.get_log_events(logGroupName=self.group, logStreamName=day.isoformat(),
117
+ startFromHead=False, limit=1, **({"nextToken": token} if token else {}))
118
+ except Exception as error:
119
+ if error_code(error) == "ResourceNotFoundException":
120
+ break
121
+ raise
122
+ if page.get("events"):
123
+ return json.loads(page["events"][-1]["message"])
124
+ if not page.get("nextBackwardToken") or page["nextBackwardToken"] == token:
125
+ break
126
+ token = page["nextBackwardToken"]
127
+ return None
128
+
129
+
130
+ class SnsAlerts:
131
+ """Alerts published to the SNS topic the owner's email subscribes to."""
132
+
133
+ def __init__(self, client, topic):
134
+ self.client, self.topic = client, topic
135
+
136
+ def send(self, alert):
137
+ return self.client.publish(TopicArn=self.topic, Subject=alert["subject"], Message=alert["message"])["MessageId"]
138
+
139
+
140
+ def handler(event, context):
141
+ """One scheduled check. The record is printed to the function's own log and returned. A record the journal did
142
+ not take fails the invocation, so it shows in the function's error count. Nothing else does: a failed alert
143
+ is in the record and the next check sends it again."""
144
+ settings = load_settings(os.environ.get(SETTINGS))
145
+ import boto3 # the Lambda runtime's, imported here so the settings are checked before any client is made
146
+
147
+ def client(service):
148
+ return boto3.client(service, region_name=settings["region"])
149
+ record = archive_health.run(S3Health(client("s3"), settings["bucket"], settings["prefix"]),
150
+ LogsJournal(client("logs"), settings["journal"]),
151
+ SnsAlerts(client("sns"), settings["topic"]), clock(), settings["quiet"])
152
+ print(json.dumps(record, sort_keys=True))
153
+ if not record["recorded"]:
154
+ raise RuntimeError(f"the checker could not record the check at {record['at']}: {record['errors'][-1]}")
155
+ return record