Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions .github/scripts/iam_diff.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
"""The permission changes of a release, for its release notes.

Every role, policy and resource policy of the native templates (the parent,
access.json and each part) is compared with the previous release's, both
resolved the way the install's updater compares them before an update
(lambda/updater/handler.py, resource_on and resource_difference): policy
documents as IAM means them, order ignored, so only a real difference in
actions, resources or conditions is listed. Here no install's values are
known, so each parameter stays its own name on both sides and both branches
of a condition are kept.

iam_diff.py previous TAG < releases.json
The release a TAG install moves from: the newest published release
below TAG (any for a beta, a stable one for a stable TAG). releases.json
is `gh release list --json tagName,isPrerelease,isDraft`.
iam_diff.py diff OLD_DIR NEW_DIR [FROM_TAG]
Markdown for the release notes. Each DIR holds coderhelm.json,
access.json and stacks/*.json, as the release's native files do.
"""

import importlib.util
import json
import pathlib
import sys

HANDLER = pathlib.Path(__file__).resolve().parents[2] / "lambda" / "updater" / "handler.py"
_spec = importlib.util.spec_from_file_location("iam_diff_updater", HANDLER)
u = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(u)

PSEUDO = ("AWS::AccountId", "AWS::Region", "AWS::Partition", "AWS::URLSuffix", "AWS::StackName", "AWS::StackId",
"AWS::NotificationARNs")


def previous(tag, releases):
"""The tag of the release an install of `tag` moves from, or None."""
beta = bool(u.parse_version(tag) and u.parse_version(tag)[3])
best = None
for r in releases or []:
t = r.get("tagName") or ""
p = u.parse_version(t)
if not p or r.get("isDraft") or t == tag:
continue
if not beta and (p[3] or r.get("isPrerelease")):
continue
if u.compare(t, tag) >= 0:
continue
if best is None or u.compare(t, best) > 0:
best = t
return best


def templates(root):
root = pathlib.Path(root)
out = {}
for rel in ["coderhelm.json", "access.json"] + sorted(f"stacks/{p.name}" for p in (root / "stacks").glob("*.json")):
f = root / rel
if f.is_file():
out[rel] = json.loads(f.read_text())
return out


def side(t):
values = {name: "${" + name + "}" for name in (t.get("Parameters") or {})}
values.update({p: "${" + p + "}" for p in PSEUDO})
return {"t": t, "values": values, "symbolic": True}


def is_permission(res):
t = res.get("Type") or ""
if t.startswith("AWS::IAM::") or t in u.POLICY_TYPES:
return True
return any(k in (res.get("Properties") or {}) for k in u.POLICY_PROPERTIES)


def diff(old_dir, new_dir):
"""[(file, resource, type, what changes)]."""
old, new = templates(old_dir), templates(new_dir)
out = []
for rel in sorted(set(old) | set(new)):
a, b = old.get(rel) or {}, new.get(rel) or {}
ra, rb = a.get("Resources") or {}, b.get("Resources") or {}
sa, sb = side(a), side(b)
for lid in sorted(set(ra) | set(rb)):
if not (is_permission(ra.get(lid) or {}) or is_permission(rb.get(lid) or {})):
continue
kind = (rb.get(lid) or ra.get(lid) or {}).get("Type") or ""
if lid not in ra:
out.append((rel, lid, kind, "added"))
continue
if lid not in rb:
out.append((rel, lid, kind, "removed"))
continue
try:
what = u.resource_difference(u.resource_on(sa, lid), u.resource_on(sb, lid))
except u.Unknown as e:
what = f"couldn't be compared ({e})"
if what:
out.append((rel, lid, kind, what))
for name in sorted(set(a.get("Conditions") or {}) | set(b.get("Conditions") or {})):
ca, cb = (a.get("Conditions") or {}).get(name), (b.get("Conditions") or {}).get(name)
if json.dumps(ca, sort_keys=True) != json.dumps(cb, sort_keys=True):
out.append((rel, name, "Condition", "added" if ca is None else "removed" if cb is None else "changes"))
return out


def markdown(changes, from_tag):
since = f"since {from_tag}" if from_tag else "since the previous release"
if not changes:
return (f"## Permission changes {since}\n\nNone: every role, policy and resource policy grants exactly what "
f"{from_tag or 'the previous release'}'s does (compared as the updater compares them).\n")
lines = [f"## Permission changes {since}", "",
"An update with these waits for an admin's OK; nothing else about permissions changes.", ""]
for rel, lid, kind, what in changes:
lines.append(f"- `{rel}` {lid} ({kind}): {what}")
return "\n".join(lines) + "\n"


def main(argv):
if len(argv) >= 2 and argv[0] == "previous":
found = previous(argv[1], json.load(sys.stdin))
if found:
print(found)
return 0
if len(argv) >= 3 and argv[0] == "diff":
print(markdown(diff(argv[1], argv[2]), argv[3] if len(argv) > 3 else ""), end="")
return 0
print(__doc__, file=sys.stderr)
return 2


if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
97 changes: 97 additions & 0 deletions .github/scripts/test_iam_diff.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""The release notes' permission changes: only a real difference in a role's
or a policy's actions, resources or conditions is listed, compared the way
the install's updater compares them.

Run: python3 -m unittest discover -s .github/scripts
"""

import copy
import json
import pathlib
import sys
import tempfile
import unittest

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
import iam_diff # noqa: E402

IMP = "Imp0123456789ab"
POLICY = {"Type": "AWS::IAM::Policy", "Properties": {
"PolicyName": "WorkerRoleDefaultPolicy", "Roles": [{"Ref": "WorkerRole"}],
"PolicyDocument": {"Version": "2012-10-17", "Statement": [
{"Effect": "Allow", "Action": ["dynamodb:GetItem", "dynamodb:Query"], "Resource": [{"Ref": IMP}]},
{"Effect": "Allow", "Action": "s3:GetObject",
"Resource": {"Fn::If": ["HasBucket", {"Fn::Sub": "arn:${AWS::Partition}:s3:::${Bucket}/*"}, {"Ref": "AWS::NoValue"}]}},
]}}}


def release(root, policy, conditions=None):
worker = {"Parameters": {IMP: {"Type": "String"}, "Bucket": {"Type": "String"}},
"Conditions": conditions or {"HasBucket": {"Fn::Not": [{"Fn::Equals": [{"Ref": "Bucket"}, ""]}]}},
"Resources": {"WorkerRole": {"Type": "AWS::IAM::Role", "Properties": {}}, "WorkerRoleDefaultPolicy": policy,
"Queue": {"Type": "AWS::SQS::Queue", "Properties": {"VisibilityTimeout": 30}}}}
(root / "stacks").mkdir(parents=True)
(root / "stacks" / "Worker.json").write_text(json.dumps(worker))
(root / "coderhelm.json").write_text(json.dumps({"Resources": {}}))


class Diff(unittest.TestCase):
def setUp(self):
self.tmp = pathlib.Path(tempfile.mkdtemp())

def run_diff(self, old, new, **kw):
release(self.tmp / "old", old)
release(self.tmp / "new", new, **kw)
return iam_diff.diff(self.tmp / "old", self.tmp / "new")

def test_the_same_policy_in_another_order_is_no_change(self):
p = copy.deepcopy(POLICY)
p["Properties"]["PolicyDocument"]["Statement"].reverse()
p["Properties"]["PolicyDocument"]["Statement"][1]["Action"].reverse()
self.assertEqual(self.run_diff(POLICY, p), [])
self.assertIn("None: every role", iam_diff.markdown([], "v1.0.0"))

def test_an_added_action_is_listed(self):
p = copy.deepcopy(POLICY)
p["Properties"]["PolicyDocument"]["Statement"][0]["Action"].append("dynamodb:PutItem")
(change,) = self.run_diff(POLICY, p)
self.assertEqual(change[:3], ("stacks/Worker.json", "WorkerRoleDefaultPolicy", "AWS::IAM::Policy"))
self.assertIn("allows dynamodb:PutItem", change[3])
md = iam_diff.markdown([change], "v1.0.0")
self.assertIn("## Permission changes since v1.0.0", md)
self.assertIn("dynamodb:PutItem", md)

def test_a_change_in_a_branch_no_value_takes_is_listed(self):
p = copy.deepcopy(POLICY)
p["Properties"]["PolicyDocument"]["Statement"][1]["Resource"]["Fn::If"][1] = "*"
self.assertEqual(len(self.run_diff(POLICY, p)), 1)

def test_a_changed_condition_is_listed(self):
out = self.run_diff(POLICY, POLICY, conditions={"HasBucket": {"Fn::Equals": ["a", "a"]}})
self.assertEqual([(c[1], c[2]) for c in out], [("HasBucket", "Condition")])

def test_added_and_removed_resources(self):
release(self.tmp / "old", POLICY)
release(self.tmp / "new", POLICY)
t = json.loads((self.tmp / "new" / "stacks" / "Worker.json").read_text())
t["Resources"]["Extra"] = {"Type": "AWS::Lambda::Permission", "Properties": {"Principal": "s3.amazonaws.com"}}
(self.tmp / "new" / "stacks" / "Worker.json").write_text(json.dumps(t))
self.assertEqual([c[1:] for c in iam_diff.diff(self.tmp / "old", self.tmp / "new")],
[("Extra", "AWS::Lambda::Permission", "added")])


class Previous(unittest.TestCase):
RELEASES = [{"tagName": "v1.3.0-beta.20261102", "isPrerelease": True}, {"tagName": "v1.2.0", "isPrerelease": False},
{"tagName": "v1.3.0-beta.20261101", "isPrerelease": True}, {"tagName": "v1.4.0", "isDraft": True},
{"tagName": "v1.1.0", "isPrerelease": False}]

def test_a_beta_moves_from_the_newest_release_below_it(self):
self.assertEqual(iam_diff.previous("v1.3.0-beta.20261103", self.RELEASES), "v1.3.0-beta.20261102")

def test_a_stable_release_moves_from_the_last_stable(self):
self.assertEqual(iam_diff.previous("v1.3.0", self.RELEASES), "v1.2.0")
self.assertIsNone(iam_diff.previous("v1.0.0", self.RELEASES))


if __name__ == "__main__":
unittest.main()
31 changes: 31 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,31 @@ jobs:
cfn-lint -i W3005 -i W2531 -- "$RUNNER_TEMP/native/coderhelm.json" "$RUNNER_TEMP/native/access.json" "$RUNNER_TEMP/native"/stacks/*.json
cp "$RUNNER_TEMP/native/coderhelm.json" ../dist/coderhelm.json
tar -czf ../dist/coderhelm-native.tar.gz -C "$RUNNER_TEMP/native" access.json stacks assets
# The release notes say what this release changes about permissions:
# every role, policy and resource policy of the native templates against
# the release an install moves from, compared as the install's updater
# compares them before an update (.github/scripts/iam_diff.py), so only
# a real difference in actions, resources or conditions is listed.
- name: Permission changes since the previous release
env:
GH_TOKEN: ${{ github.token }}
run: |
NOTE="$RUNNER_TEMP/notes/permission-changes.md"
mkdir -p "$RUNNER_TEMP/notes" "$RUNNER_TEMP/prev"
PREV="$(gh release list -R "$GITHUB_REPOSITORY" --limit 100 --json tagName,isPrerelease,isDraft | python3 .github/scripts/iam_diff.py previous "$TAG")"
if [ -n "$PREV" ] && gh release download "$PREV" -R "$GITHUB_REPOSITORY" -p coderhelm.json -p coderhelm-native.tar.gz -D "$RUNNER_TEMP/prev"; then
tar -xzf "$RUNNER_TEMP/prev/coderhelm-native.tar.gz" -C "$RUNNER_TEMP/prev" access.json stacks
python3 .github/scripts/iam_diff.py diff "$RUNNER_TEMP/prev" "$RUNNER_TEMP/native" "$PREV" > "$NOTE"
else
printf '## Permission changes\n\nNo earlier release with native templates to compare with.\n' > "$NOTE"
fi
cat "$NOTE" | tee -a "$GITHUB_STEP_SUMMARY"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-notes
path: ${{ runner.temp }}/notes/
if-no-files-found: error
retention-days: 3
- name: Checksums
run: |
(cd dist && sha256sum gateway.zip worker.zip mcp-proxy.zip dashboard.tar.gz source.tar.gz coderhelm-selfhost.tgz install.sh coderhelm.json coderhelm-native.tar.gz models.json coderhelm-log-reader.yaml coderhelm-log-reader-update.yaml coderhelm-bedrock-export.yaml > SHA256SUMS)
Expand Down Expand Up @@ -383,6 +408,11 @@ jobs:
with:
name: release-dist
path: dist
# Kept beside dist/, never in it: dist holds exactly what SHA256SUMS lists.
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: release-notes
path: notes
- name: The files are the ones the build listed
run: |
cd dist
Expand Down Expand Up @@ -437,6 +467,7 @@ jobs:
pre=false
case "$TAG" in *-*) pre=true ;; esac
NOTES="Self-host release ${TAG}. Install: npx -y github:${GITHUB_REPOSITORY}#${TAG} init, then deploy. Update: npx -y github:${GITHUB_REPOSITORY}#${TAG} update --to ${TAG}. Check an install: npx -y github:${GITHUB_REPOSITORY} doctor. Verify it yourself: docs/self-host/updates-security.md."
NOTES="${NOTES}"$'\n\n'"$(cat notes/permission-changes.md)"
if DRAFT=$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" --jq .draft 2>/dev/null); then
mkdir -p "$RUNNER_TEMP/old"
if gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p SHA256SUMS -D "$RUNNER_TEMP/old"; then
Expand Down
5 changes: 5 additions & 0 deletions docs/incidents/vu_unattended_beta_and_alarms.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# vu. `vu_unattended_beta_and_alarms`

**What happened:** A self-hosted install on the beta channel never took a beta by itself, and a broken install went unnoticed. Every release looked like a permission change: CloudFormation reports a Modify for each policy that names another part's output, because that value is known only after apply, even when the policy documents are byte for byte the same. The updater counted any IAM Modify, and a scheduled update that changes permissions waits for a person, so the hourly check never applied one. The maintenance window was one hour a week (or a day), so at most one of several daily betas could install. After an update the watch probed only the worker and the gateway; Chat runs in its own function with its own role, lost a grant, and refused every question while both stayed healthy. The alarms counted Lambda Errors, which stay at 0 because the services catch and log every error, so none moved.

**The guarantee:** A Modify counts as a permission change only when the resource differs once both sides are resolved the way the template resolves them: the running stack's parameter values before, the change set's after, and an import known only after apply keeps its running value when the parent feeds it the same way and its source output is the same. An Add, a real widening, and anything that can't be compared still wait for a person, as before. The release notes list the same comparison against the previous release. On the beta channel, `day: "any"` installs at any hour, at least `gap_hours` after the last install; the stable channel keeps its window. The watch asks the streaming function to make Chat's own calls (the member check every stream runs and each DynamoDB action its role is granted), and a refusal rolls the release back like a failed worker probe. Every install alarms on ERROR lines per function, GitHub rate-limit lines and Chat answers that failed, each as a share of the traffic, into the alerts topic.
8 changes: 8 additions & 0 deletions docs/self-host/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ Each step checks what you did before it moves on. When a check fails, fix it and

**`update` says there isn't enough space.** Releases are kept in `~/.coderhelm/releases`. Delete old ones (keep the one you run), or set `CODERHELM_HOME` to a bigger disk.

## The install's own alarms

Every install alarms into its alerts topic (`<prefix>-alerts`; subscribe an email or a chat channel to it). The services catch and log their errors, so Lambda's own `Errors` metric stays at 0 even when they fail; these alarms read the log lines instead, each as a share of the traffic over most of an hour, never a count:

- **`<prefix>-gateway-error-lines`, `-worker-error-lines`, `-streaming-error-lines`, `-updater-error-lines`**: that function logged an ERROR line on 10% or more of its invocations. Read the ERROR lines in its log group.
- **`<prefix>-github-rate-limited`**: GitHub refused or held back requests on 20% or more of the worker's invocations. The installation's hourly budget is spent; runs, reviews and checks wait for the next hour.
- **`<prefix>-chat-answer-failed`**: Chat couldn't answer 20% or more of the questions asked (its sign-in check or the model failed). Read the "Chat couldn't answer" lines in the streaming function's log group.

## Links point to localhost

Links in comments and emails come from the public URL. Without a domain it is read from SSM (`/coderhelm-<stage>/public-url`) when a function starts; if a function started before the first deploy finished, it retries every 30 seconds. Check the parameter exists, then send a request (any page) to refresh it.
Loading