From 7ff72daf38487620424145a9ae3a898749984314 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 4 Dec 2026 14:02:15 -0500 Subject: [PATCH 1/2] An update continues its own version, and permission holds name only what is newly allowed A scheduled update held for a person (it changes permissions) left no update "running", so the next hourly check prepared the same release again and marked the waiting one superseded by its own version, every hour, and it never applied. A change set CloudFormation took longer than the running limit to make was refused the same way. - begin: a second start for the same version (the hourly check, an admin's press, a waiting press) continues the prepared change set (same_version_open, continue_open). An admin's press with their OK for permission changes lets that change set apply. A newer release still replaces an older one that hasn't run. - Permission changes are compared as grants (who, action, resource, condition) across every role, policy and resource policy of a part together (grant_difference). Only a grant no running one covers, or a deny or boundary the new release drops, holds an update, and the hold says what becomes newly allowed. A statement moved between a role's policies, a different order, a log group's ARN with or without ":*", an added condition or a removed action applies by itself. NotAction, NotResource and NotPrincipal statements, and anything that can't be compared, still count whenever they differ. The release notes (iam_diff.py) use the same comparison. - The hourly check: a refused start writes its row and the check goes on (reminders, the digest); the second refusal in a row of the same version emails the admins once (the update notice), and the status route returns it as auto_refused. - Tests: hourly ticks and 5-minute polls against a slow change set end applied with one change set and nothing superseded; a held update is never prepared again and applies on the admin's OK; widening, narrowing, equivalent and new-ARN cases for the grant comparison. Incident case xs. --- .github/scripts/iam_diff.py | 14 +- .github/scripts/test_iam_diff.py | 15 + .../xs_update_continues_its_own_version.md | 5 + docs/self-host/updates.md | 8 +- lambda/tests/test_updater_grants.py | 270 ++++++++++ lambda/tests/test_updater_native.py | 13 +- lambda/tests/test_updater_real_permissions.py | 10 +- lambda/tests/test_updater_same_version.py | 219 ++++++++ lambda/updater/handler.py | 491 +++++++++++++++++- .../xs_update_continues_its_own_version.rs | 76 +++ 10 files changed, 1109 insertions(+), 12 deletions(-) create mode 100644 docs/incidents/xs_update_continues_its_own_version.md create mode 100644 lambda/tests/test_updater_grants.py create mode 100644 lambda/tests/test_updater_same_version.py create mode 100644 services/worker/src/passes/incidents/xs_update_continues_its_own_version.rs diff --git a/.github/scripts/iam_diff.py b/.github/scripts/iam_diff.py index 0cd647fc1..5ab65ce65 100644 --- a/.github/scripts/iam_diff.py +++ b/.github/scripts/iam_diff.py @@ -81,10 +81,22 @@ def diff(old_dir, new_dir): 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) + # Roles, policies and resource policies: what the new release newly + # allows, every one of the file together (u.grant_difference). + grants = {lid for lid in set(ra) | set(rb) if u.grant_kind(ra.get(lid)) or u.grant_kind(rb.get(lid))} + changed = {lid: "Add" if lid not in ra else "Remove" if lid not in rb else "Modify" for lid in grants + if json.dumps(ra.get(lid), sort_keys=True) != json.dumps(rb.get(lid), sort_keys=True)} + widened, unknown = u.grant_difference(sa, sb, changed) if changed else ({}, {}) 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 in grants: + if lid in unknown: + out.append((rel, lid, kind, f"couldn't be compared ({unknown[lid]})")) + elif widened.get(lid): + out.append((rel, lid, kind, "; ".join(widened[lid]))) + continue if lid not in ra: out.append((rel, lid, kind, "added")) continue @@ -107,7 +119,7 @@ def diff(old_dir, new_dir): 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 " + return (f"## Permission changes {since}\n\nNone: every role, policy and resource policy allows no more than " 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.", ""] diff --git a/.github/scripts/test_iam_diff.py b/.github/scripts/test_iam_diff.py index 57260acb3..5f98de177 100644 --- a/.github/scripts/test_iam_diff.py +++ b/.github/scripts/test_iam_diff.py @@ -61,6 +61,21 @@ def test_an_added_action_is_listed(self): self.assertIn("## Permission changes since v1.0.0", md) self.assertIn("dynamodb:PutItem", md) + def test_a_narrowed_or_moved_statement_is_no_change(self): + p = copy.deepcopy(POLICY) + p["Properties"]["PolicyDocument"]["Statement"][0]["Action"] = ["dynamodb:GetItem"] + self.assertEqual(self.run_diff(POLICY, p), []) + # The second statement moved to an overflow policy of the same role. + release(self.tmp / "old2", POLICY) + release(self.tmp / "new2", p) + t = json.loads((self.tmp / "new2" / "stacks" / "Worker.json").read_text()) + moved = t["Resources"]["WorkerRoleDefaultPolicy"]["Properties"]["PolicyDocument"]["Statement"].pop() + t["Resources"]["WorkerRoleDefaultPolicy"]["Properties"]["PolicyDocument"]["Statement"][0]["Action"] = ["dynamodb:GetItem", "dynamodb:Query"] + t["Resources"]["WorkerRoleOverflowPolicy1"] = {"Type": "AWS::IAM::ManagedPolicy", "Properties": { + "Roles": [{"Ref": "WorkerRole"}], "PolicyDocument": {"Version": "2012-10-17", "Statement": [moved]}}} + (self.tmp / "new2" / "stacks" / "Worker.json").write_text(json.dumps(t)) + self.assertEqual(iam_diff.diff(self.tmp / "old2", self.tmp / "new2"), []) + 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] = "*" diff --git a/docs/incidents/xs_update_continues_its_own_version.md b/docs/incidents/xs_update_continues_its_own_version.md new file mode 100644 index 000000000..72be009c1 --- /dev/null +++ b/docs/incidents/xs_update_continues_its_own_version.md @@ -0,0 +1,5 @@ +# xs. `xs_update_continues_its_own_version` + +**What happened:** A self-hosted install with auto-update on, on the beta channel at any hour, stayed on one release. Each beta was held for a person because it changed permissions, and a held update is not "running", so the next hourly check started the same release again: a new change set, and the one waiting was marked superseded, "replaced by the update to" the same version, every hour. None was ever applied. Half of each hold was no widening at all: aws-cdk-lib rewrote a log-read statement in a role's overflow policy with the log group's bare ARN beside its `:*` ARN, and compared policy by policy as text it read as "resources or conditions change". The other half was real, and still waits for a person: a new schedule allowed to send to a queue. When the hourly check couldn't start an update at all, it stopped the rest of the check and nobody was told. + +**The guarantee:** An update never replaces an update to the same version. The next hourly check, or an admin's press of **Update**, continues the change set already prepared for that version, and an admin's press with their OK for permission changes lets that same change set apply. A newer release still replaces an older one that hasn't run. Permission changes are compared as what they allow, across every role, policy and resource policy of a part together: only a grant no running one covers, or a deny or boundary the new release drops, holds an update, and the hold names it in plain words. A move between policies of the same role, a different order, a log group's ARN with or without `:*`, a condition added or an action removed applies by itself. An hourly check that can't start its update writes the row, goes on with the rest of the check, and at the second refusal in a row emails the admins once. The Python tests in `lambda/tests/test_updater_same_version.py` and `lambda/tests/test_updater_grants.py` replay each one; this case holds the wiring. diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index 5ac311383..05d26e713 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -56,7 +56,7 @@ A new release doesn't email anyone, and neither does an update that finished: ** |---|---| | **update to vX needs your OK** | A prepared update waits for an admin: to confirm the data or permission changes it lists, to press **Apply**, or for someone with administrator rights in the AWS account. Also when [the model check](#the-model-check) refuses a model the release calls. | | **update to vX still needs your OK** | The same update still waits 7 days later. Sent once. | -| **update to vX failed** / **rolled back** | The update stopped, or CloudFormation put the previous release back. The email says where the install is now and what to do. | +| **update to vX failed** / **rolled back** | The update stopped, or CloudFormation put the previous release back. The email says where the install is now and what to do. Also when auto-update couldn't start vX at two hourly checks in a row (nothing changed): the email says what stopped it, and **Update history** has a row for each try. | | **the new address is live** / **the address change failed** / **back on the AWS address** | A [domain](./domains.md) change finished, failed, or was undone. | | **what's new, up to vX** | The digest, below. | @@ -132,7 +132,7 @@ The **Version** section of **Settings, then System** shows one state at a time, Under the status, **Check for updates** sits next to when GitHub last answered ("Checked 2 min ago"). The steps of a running update read **Check the release**, **Prepare the change** and **Apply it**, with the current one marked; there is no percentage, because AWS doesn't give a reliable one. -There is only ever one update waiting. A newer prepared update replaces an older one that hasn't run, and the history lists the older one as **Replaced**. An update that AWS is still preparing or already applying is never replaced. +There is only ever one update waiting. A newer release's prepared update replaces an older one that hasn't run, and the history lists the older one as **Replaced**. A second start for the same version (the next hourly check, or another press of **Update**) continues the one prepared, and never replaces it. An update that AWS is still preparing or already applying is never replaced. ## Permissions @@ -213,13 +213,13 @@ On an install made with Launch Stack, an update is a stack update of `coderhelm- 4. **Applies it, through the deploy role.** **Settings, then System** shows the change set's summary while it runs: how many resources are added, changed and removed, which ones are replaced, which parts it touches, and a link to it in the CloudFormation console if you want to look. - **You pressed Update:** it applies as soon as it is prepared. The card says next to the button that one press includes any change to what CoderHelm's own roles may do; those always stay inside the install's permissions boundary, and the deploy role can't change itself or the boundary. When it would replace or remove data, it stops: the card lists what it replaces or removes, in words, and **Replace the data and apply** applies exactly those changes (if they changed since the page showed them, it asks again). The raw CloudFormation list is under **Technical details**. - **The maintenance window started it (auto-update on):** it applies by itself, except when it would replace or remove data or change permissions: then it waits, admins get an email, and you confirm it on the page the same way. If auto-update was turned off before it ran, it waits for you to press **Apply**. - - **What counts as a permission change.** CloudFormation reports a policy that names another part's output as changed on every update, because that value is known only once the update runs. So the updater compares each such policy, role or resource policy with the running release's: both resolved the way the template resolves them, policy documents as IAM reads them (order doesn't matter). Only a difference in what it allows, on which resources or under which conditions, counts. A new role or policy, and one that can't be compared, always counts. Each release's notes list its permission changes against the release before it, compared the same way. + - **What counts as a permission change.** CloudFormation reports a policy that names another part's output as changed on every update, because that value is known only once the update runs. So the updater compares what the new release allows with what the running one allows, both resolved the way the template resolves them: every role, policy and resource policy of a part together, as grants of an action on a resource, to someone, under a condition. Only something newly allowed counts: a grant no running one covers, or a deny or a permissions boundary the new release drops. A statement moved to another policy of the same role (CDK splits a large role policy into overflow policies), a different order, a log group's ARN written with or without `:*`, a condition added, or an action or resource removed allows nothing new and applies by itself. A statement with `NotAction`, `NotResource` or `NotPrincipal`, and anything that can't be compared, counts whenever it differs. The hold names what becomes newly allowed, for example "newly allows sqs:SendMessage on TicketQueue for the AWS service events.amazonaws.com when aws:SourceArn is MonthTurnSchedule". Each release's notes list its permission changes against the release before it, compared the same way. - **The deploy role and the permissions boundaries never change in an update.** The deploy role can't change itself or a boundary (that is what keeps it from giving itself more), and executing the change set in the AWS console doesn't get around it: the stack's service role is the deploy role, so AWS runs it as that role whoever presses **Execute**. So every update keeps your install's own deploy role and boundaries exactly as they are, and the rest of the release installs. A release that needs newer ones lists them under [Permissions](#permissions), as a separate step. - **Before it runs**, the updater checks every IAM call the change set needs against the deploy role's own policy and boundary, as IAM has them now. If one would be refused, the update stops before anything changes and says which call and which rule refused it. 5. **Follows it.** The updater reads the change set and the stack every 5 minutes until the update ends, and again each time **Settings, then System** asks, so the page never shows an older state than CloudFormation's. An update executed outside the app (in the AWS console or the AWS CLI) is followed the same way, and the history records it as applied in the AWS console. Before it calls the update a success, it checks that the stack reports the new release. When the stack update starts, the install's own copy step checks every file of the release against the sha256 that `coderhelm.json` lists before any part changes. If a part fails, CloudFormation rolls the whole stack back to the previous release by itself. 6. **Reports.** The history in **Settings, then System** shows the version, when, who (or "auto") and the result: succeeded, failed, or rolled back. A try that didn't succeed says in plain words what happened, where your install is now and what to do next; CloudFormation's own text (for the first resource that failed) is under **Technical details**. Admins get an email when it failed or rolled back; a finished update is only in the history. -A change set that waits too long can go stale (the stack changed since it was made); the history then says so, and **Update** prepares a new one. Pressing **Update** while an older prepared update waits replaces it (nothing was changed by the older one), and the history lists the older one as **Replaced**. Pressing it while AWS still prepares or already applies an update is refused, with the reason; pressing it again for the update already in progress just shows that update. +A change set that waits too long can go stale (the stack changed since it was made); the history then says so, and **Update** prepares a new one. Pressing **Update** while an older prepared update waits replaces it (nothing was changed by the older one), and the history lists the older one as **Replaced**. An update is never replaced by one to the same version: pressing **Update** for the version already prepared (or the hourly check finding it again) continues that one, and your press counts as your OK for its permission changes. Pressing it while AWS still prepares or already applies an update is refused, with the reason; pressing it again for the update already in progress just shows that update. Pressing **Update** while the release check still runs is never an error: the press is recorded (who, which version, when), the card shows **Checking vX before it can be applied**, and the update starts by itself once the check passes. If the check fails, the card says why. Pressing again, or a newer release coming out meanwhile, replaces the waiting press: **Update** always means the newest release. While an update is checked, prepared or applied, a newer release is only mentioned on the card ("it's next after this one"); it is offered once the current one finishes. diff --git a/lambda/tests/test_updater_grants.py b/lambda/tests/test_updater_grants.py new file mode 100644 index 000000000..e07610a09 --- /dev/null +++ b/lambda/tests/test_updater_grants.py @@ -0,0 +1,270 @@ +"""Permission changes compared as what they allow. A release's policies are +read as grants (who, action, resource, condition), every policy of a stack +together, against the running release's: only a grant no running one covers +holds an update for a person, and the hold names it. A statement moved to +another policy of the same role, a list in another order, a log group's ARN +written with or without ":*", an added condition or a dropped action apply +by themselves. + +Run: python3 -m unittest discover -s lambda/tests +""" + +import copy +import json +import unittest + +import test_updater_native as base +import test_updater_real_permissions as rp + +u = base.u +VALUES = {"Stage": "prod", "AWS::Partition": "aws", "AWS::Region": "us-east-1", "AWS::AccountId": "111122223333"} +ROLE = {"Type": "AWS::IAM::Role", "Properties": {"AssumeRolePolicyDocument": {"Statement": [ + {"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}}} +LOGS = {"Type": "AWS::Logs::LogGroup", "Properties": {"RetentionInDays": 30}} +QUEUE = {"Type": "AWS::SQS::Queue", "Properties": {}} +RULE = {"Type": "AWS::Events::Rule", "Properties": {"ScheduleExpression": "rate(1 hour)"}} +READ_LOGS = ["logs:FilterLogEvents", "logs:GetLogEvents", "logs:DescribeLogStreams"] + + +def statement(actions, resource, **kw): + return dict({"Effect": "Allow", "Action": actions, "Resource": resource}, **kw) + + +def policy(kind, statements, name="WorkerRoleDefaultPolicy1A2B3C4D"): + props = {"Roles": [{"Ref": "WorkerRole"}], "PolicyDocument": {"Version": "2012-10-17", "Statement": statements}} + props["PolicyName" if kind == "AWS::IAM::Policy" else "Description"] = name + return {"Type": kind, "Properties": props} + + +TABLE = statement(["dynamodb:GetItem", "dynamodb:Query"], {"Fn::Sub": "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${Stage}-jobs"}) +READ = statement(READ_LOGS, {"Fn::GetAtt": ["BuildLogGroupF00DBA11", "Arn"]}) + + +def send_from(rule): + return {"Effect": "Allow", "Principal": {"Service": "events.amazonaws.com"}, + "Action": ["sqs:SendMessage", "sqs:GetQueueAttributes", "sqs:GetQueueUrl"], + "Resource": {"Fn::GetAtt": ["JobQueue5E6F7A8B", "Arn"]}, + "Condition": {"ArnEquals": {"aws:SourceArn": {"Fn::GetAtt": [rule, "Arn"]}}}} + + +def queue_policy(*rules): + return {"Type": "AWS::SQS::QueuePolicy", "Properties": { + "Queues": [{"Ref": "JobQueue5E6F7A8B"}], + "PolicyDocument": {"Version": "2012-10-17", "Statement": [send_from(r) for r in rules]}}} + + +def stack(**resources): + base_res = {"WorkerRole": ROLE, "BuildLogGroupF00DBA11": LOGS, "JobQueue5E6F7A8B": QUEUE, + "NightlySweepSchedule1A2B3C4D": RULE, "MonthTurnScheduleA1B2C3D4": RULE, + "Default": policy("AWS::IAM::Policy", [TABLE, READ]), + "JobQueuePolicy9C8D7E6F": queue_policy("NightlySweepSchedule1A2B3C4D")} + base_res.update(resources) + return {"Parameters": {"Stage": {"Type": "String"}}, "Resources": {k: v for k, v in base_res.items() if v is not None}} + + +def side(t): + return {"t": t, "values": dict(VALUES), "replaced": set(), "scope": "Worker"} + + +def compare(new, old=None, changed=None): + old = old or stack() + if changed is None: + changed = {lid: "Modify" for lid in set(old["Resources"]) | set(new["Resources"]) + if json.dumps(old["Resources"].get(lid), sort_keys=True) != json.dumps(new["Resources"].get(lid), sort_keys=True)} + for lid in changed: + if lid not in old["Resources"]: + changed[lid] = "Add" + elif lid not in new["Resources"]: + changed[lid] = "Remove" + return u.grant_difference(side(old), side(new), changed) + + +class Widening(unittest.TestCase): + """Held: the hold says what becomes newly allowed, and for whom.""" + + def test_an_added_action_holds_and_is_named(self): + new = stack(Default=policy("AWS::IAM::Policy", [statement(TABLE["Action"] + ["dynamodb:DeleteItem"], TABLE["Resource"]), READ])) + widened, unknown = compare(new) + self.assertEqual(unknown, {}) + self.assertEqual(widened, {"Default": ["newly allows dynamodb:DeleteItem on " + "arn:aws:dynamodb:us-east-1:111122223333:table/prod-jobs for WorkerRole"]}) + + def test_a_new_resource_arn_holds(self): + other = "arn:aws:dynamodb:us-east-1:111122223333:table/prod-billing" + new = stack(Default=policy("AWS::IAM::Policy", [statement(TABLE["Action"], [TABLE["Resource"], other]), READ])) + widened, _ = compare(new) + self.assertEqual(widened, {"Default": [f"newly allows dynamodb:GetItem, dynamodb:Query on {other} for WorkerRole"]}) + + def test_a_wildcard_holds(self): + new = stack(Default=policy("AWS::IAM::Policy", [TABLE, statement(READ_LOGS, "*")])) + widened, _ = compare(new) + self.assertIn("newly allows logs:DescribeLogStreams, logs:FilterLogEvents, logs:GetLogEvents on * for WorkerRole", + widened["Default"]) + + def test_a_new_sender_to_a_queue_holds_and_says_which(self): + new = stack(JobQueuePolicy9C8D7E6F=queue_policy("NightlySweepSchedule1A2B3C4D", "MonthTurnScheduleA1B2C3D4")) + widened, _ = compare(new) + self.assertEqual(widened, {"JobQueuePolicy9C8D7E6F": [ + "newly allows sqs:GetQueueAttributes, sqs:GetQueueUrl, sqs:SendMessage on JobQueue for the AWS service " + "events.amazonaws.com when aws:SourceArn is MonthTurnSchedule"]}) + + def test_a_key_policy_opened_to_anyone_holds(self): + def key(principal, action): + return {"Type": "AWS::KMS::Key", "Properties": {"KeyPolicy": {"Statement": [ + {"Effect": "Allow", "Principal": {"AWS": principal}, "Action": action, "Resource": "*"}]}}} + widened, _ = compare(stack(Key=key("*", "kms:Decrypt")), stack(Key=key("arn:aws:iam::111122223333:root", "kms:*"))) + self.assertEqual(widened, {"Key": ["newly allows kms:Decrypt on * for anyone"]}) + # A policy written as text it can't read counts whenever it differs. + widened, _ = compare(stack(Key={"Type": "AWS::KMS::Key", "Properties": {"KeyPolicy": "b"}}), + stack(Key={"Type": "AWS::KMS::Key", "Properties": {"KeyPolicy": "a"}})) + self.assertEqual(list(widened), ["Key"]) + + def test_a_dropped_deny_holds(self): + deny = {"Effect": "Deny", "Action": "dynamodb:DeleteTable", "Resource": "*"} + old = stack(Default=policy("AWS::IAM::Policy", [TABLE, READ, deny])) + widened, _ = compare(stack(), old) + self.assertEqual(widened, {"Default": ["no longer denies dynamodb:DeleteTable on * for WorkerRole"]}) + + def test_a_dropped_boundary_holds(self): + bounded = copy.deepcopy(ROLE) + bounded["Properties"]["PermissionsBoundary"] = "arn:aws:iam::111122223333:policy/example-boundary" + widened, _ = compare(stack(), stack(WorkerRole=bounded)) + self.assertEqual(widened, {"WorkerRole": [ + "drops the permissions boundary arn:aws:iam::111122223333:policy/example-boundary for WorkerRole"]}) + + def test_a_not_action_statement_counts_whenever_it_differs(self): + st = {"Effect": "Allow", "NotAction": "iam:*", "Resource": "*"} + widened, _ = compare(stack(Default=policy("AWS::IAM::Policy", [TABLE, READ, st]))) + self.assertIn("Default", widened) + self.assertIn("NotAction", widened["Default"][0]) + + def test_what_cant_be_resolved_counts(self): + new = stack(Default=policy("AWS::IAM::Policy", [statement(TABLE["Action"], {"Fn::ImportValue": "elsewhere"}), READ])) + widened, unknown = compare(new) + self.assertEqual(widened, {}) + self.assertIn("Default", unknown) + + +class Narrowing(unittest.TestCase): + """Applied by itself: nothing becomes newly allowed.""" + + def assertNothingNew(self, new, old=None): + self.assertEqual(compare(new, old), ({}, {})) + + def test_a_dropped_action_or_resource(self): + self.assertNothingNew(stack(Default=policy("AWS::IAM::Policy", [statement("dynamodb:GetItem", TABLE["Resource"]), READ]))) + self.assertNothingNew(stack(Default=policy("AWS::IAM::Policy", [TABLE]))) + self.assertNothingNew(stack(JobQueuePolicy9C8D7E6F=queue_policy()), + stack(JobQueuePolicy9C8D7E6F=queue_policy("NightlySweepSchedule1A2B3C4D", "MonthTurnScheduleA1B2C3D4"))) + + def test_an_added_condition_or_fewer_condition_values(self): + cond = {"StringEquals": {"aws:RequestedRegion": ["us-east-1", "us-west-2"]}} + narrower = {"StringEquals": {"aws:RequestedRegion": "us-east-1"}, "Bool": {"aws:SecureTransport": "true"}} + old = stack(Default=policy("AWS::IAM::Policy", [dict(TABLE, Condition=cond), READ])) + self.assertNothingNew(stack(Default=policy("AWS::IAM::Policy", [dict(TABLE, Condition=narrower), READ])), old) + self.assertNothingNew(stack(Default=policy("AWS::IAM::Policy", [dict(TABLE, Condition=cond), READ]))) + # The other way round widens: a condition dropped, or a value added. + widened, _ = compare(stack(), old) + self.assertIn("Default", widened) + + def test_a_wildcard_narrowed_to_one_resource(self): + old = stack(Default=policy("AWS::IAM::Policy", [TABLE, statement(READ_LOGS, "*")])) + self.assertNothingNew(stack(), old) + + def test_a_negated_condition_with_more_values(self): + no = {"StringNotEquals": {"aws:PrincipalTag/team": ["a"]}} + more = {"StringNotEquals": {"aws:PrincipalTag/team": ["a", "b"]}} + old = stack(Default=policy("AWS::IAM::Policy", [dict(TABLE, Condition=no), READ])) + self.assertNothingNew(stack(Default=policy("AWS::IAM::Policy", [dict(TABLE, Condition=more), READ])), old) + widened, _ = compare(old, stack(Default=policy("AWS::IAM::Policy", [dict(TABLE, Condition=more), READ]))) + self.assertIn("Default", widened) + + +class Equivalent(unittest.TestCase): + """Applied by itself: the same grants, written another way.""" + + def assertNothingNew(self, new, old=None): + self.assertEqual(compare(new, old), ({}, {})) + + def test_reordered_statements_actions_and_resources(self): + swapped = statement(list(reversed(TABLE["Action"])), [TABLE["Resource"]]) + self.assertNothingNew(stack(Default=policy("AWS::IAM::Policy", [READ, swapped]))) + + def test_a_statement_moved_to_an_overflow_policy_of_the_same_role(self): + # CDK splits a large role policy into managed "overflow" policies and + # may move a statement between them from one release to the next. + old = stack(Default=policy("AWS::IAM::Policy", [TABLE]), + Overflow1=policy("AWS::IAM::ManagedPolicy", [READ], "WorkerRoleOverflowPolicy1")) + new = stack(Default=policy("AWS::IAM::Policy", [TABLE, READ]), + Overflow1=policy("AWS::IAM::ManagedPolicy", [statement("logs:GetLogEvents", READ["Resource"])], "WorkerRoleOverflowPolicy1")) + self.assertNothingNew(new, old) + # The same grants spread over a new overflow policy. + split = stack(Default=policy("AWS::IAM::Policy", [TABLE]), + Overflow2=policy("AWS::IAM::ManagedPolicy", [READ], "WorkerRoleOverflowPolicy2")) + self.assertNothingNew(split) + + def test_moved_to_another_role_is_new_for_that_role(self): + other = dict(ROLE) + moved = policy("AWS::IAM::Policy", [READ], "OtherRolePolicy") + moved["Properties"]["Roles"] = [{"Ref": "OtherRole"}] + widened, _ = compare(stack(Default=policy("AWS::IAM::Policy", [TABLE]), OtherRole=other, Moved=moved)) + self.assertIn("for OtherRole", " ".join(widened["Moved"])) + + def test_a_log_group_written_with_and_without_the_star(self): + # aws-cdk-lib grants a log group's reads on its bare ARN and on its Arn (":*"). + bare = {"Fn::Join": ["", ["arn:", {"Ref": "AWS::Partition"}, {"Fn::Sub": ":logs:${AWS::Region}:"}, {"Ref": "AWS::AccountId"}, + ":log-group:", {"Ref": "BuildLogGroupF00DBA11"}]]} + new = stack(Default=policy("AWS::IAM::Policy", [TABLE, statement(READ_LOGS, [bare, READ["Resource"]])])) + self.assertNothingNew(new) + # The star the other way (a log group's streams) is new. + old = stack(Default=policy("AWS::IAM::Policy", [TABLE, statement(READ_LOGS, bare)])) + widened, _ = compare(stack(), old) + self.assertIn("BuildLogGroup:*", " ".join(widened["Default"])) + + def test_a_role_attaching_its_own_managed_policy_by_arn(self): + mp = policy("AWS::IAM::ManagedPolicy", [READ], "Reads") + mp["Properties"].pop("Roles") + role = copy.deepcopy(ROLE) + role["Properties"]["ManagedPolicyArns"] = [{"Ref": "Reads"}] + old = stack(Default=policy("AWS::IAM::Policy", [TABLE, READ])) + self.assertNothingNew(stack(Default=policy("AWS::IAM::Policy", [TABLE]), Reads=mp, WorkerRole=role), old) + + def test_a_description_or_tag_is_no_permission(self): + role = copy.deepcopy(ROLE) + role["Properties"].update(Description="the worker", Tags=[{"Key": "a", "Value": "b"}]) + self.assertNothingNew(stack(WorkerRole=role)) + + +class InTheUpdate(unittest.TestCase): + """Through permission_changes and the hourly window: a release that + only moves or narrows grants applies; one that widens waits, naming what.""" + + def setUp(self): + self.case = rp.ScheduledUpdates("test_the_same_policies_apply_by_themselves") + self.case.setUp() + self.addCleanup(self.case.tearDown) + + def policy_change(self, new_policy): + return rp.Templates(new_policy=new_policy) + + def test_a_narrowed_policy_applies_by_itself(self): + p = copy.deepcopy(rp.POLICY) + p["Properties"]["PolicyDocument"]["Statement"][0]["Action"] = ["dynamodb:GetItem"] + p["Properties"]["PolicyDocument"]["Statement"][1]["Condition"] = {"Bool": {"aws:SecureTransport": "true"}} + cfn = self.policy_change(p) + self.assertEqual(self.case.run_scheduled(cfn)["native"], "executing") + self.assertEqual(self.case.entry()["permission_changes"], []) + + def test_a_widened_policy_waits_and_the_hold_names_it(self): + p = copy.deepcopy(rp.POLICY) + p["Properties"]["PolicyDocument"]["Statement"].append({"Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::example-reports/*"}) + cfn = self.policy_change(p) + self.assertEqual(self.case.run_scheduled(cfn)["native"], "review") + self.assertEqual(cfn.executed, []) + hold = u.native_hold(self.case.store, self.case.env, self.case.entry()) + self.assertIn("auto-update held: it changes permissions", hold) + self.assertIn("newly allows s3:GetObject on arn:aws:s3:::example-reports/* for WorkerRole", hold) + + +if __name__ == "__main__": + unittest.main() diff --git a/lambda/tests/test_updater_native.py b/lambda/tests/test_updater_native.py index e7c3d2fa3..ed87a2fc3 100644 --- a/lambda/tests/test_updater_native.py +++ b/lambda/tests/test_updater_native.py @@ -1089,12 +1089,23 @@ def test_a_new_update_replaces_the_one_waiting(self): old = self.pending()["id"] self.cfn.nested = {} later = NOW.replace(minute=30) - u.begin(self.store, self.env, later, "v1.1.0", "owner@example.org", "update") + self.store.put("MANIFEST#v1.2.0", {"verified": True, "manifest": None, "template_sha256": SHA}) + u.begin(self.store, self.env, later, "v1.2.0", "owner@example.org", "update") self.assertEqual(self.cfn.deleted, ["arn:cs/1"]) self.assertEqual(self.store.get(old)["status"], "superseded") + self.assertIn("replaced by the update to v1.2.0", self.store.get(old)["reason"]) self.assertIn("nothing was changed", self.store.get(old)["reason"]) self.assertNotIn("review_id", self.store.get("UPDATE_STATE")) + def test_the_same_version_again_continues_the_one_waiting(self): + self.prepare(api=[{"ResourceChange": {"Action": "Add", "ResourceType": "AWS::IAM::Role", "LogicalResourceId": "NewRole"}}]) + old = self.pending()["id"] + again = u.begin(self.store, self.env, NOW.replace(minute=30), "v1.1.0", "owner@example.org", "update") + self.assertEqual((again["id"], again["continued"]), (old, True)) + self.assertEqual((len(self.cfn.created), self.cfn.deleted), (1, [])) + self.assertEqual(self.store.get(old)["status"], "review") + self.assertEqual(self.store.get("UPDATE_STATE")["review_id"], old) + class PermissionChanges(unittest.TestCase): """Auto-update never applies a change to who may do what, in the parent diff --git a/lambda/tests/test_updater_real_permissions.py b/lambda/tests/test_updater_real_permissions.py index c536854ef..d5b9a8281 100644 --- a/lambda/tests/test_updater_real_permissions.py +++ b/lambda/tests/test_updater_real_permissions.py @@ -146,15 +146,15 @@ def test_an_added_action_is_one(self): self.assertIn("Api.WorkerRoleDefaultPolicy", out[0]) self.assertIn("allows dynamodb:PutItem", out[0]) - def test_a_new_resource_or_condition_is_one(self): + def test_a_wider_resource_is_one_and_a_new_condition_is_not(self): p = copy.deepcopy(POLICY) p["Properties"]["PolicyDocument"]["Statement"][1]["Resource"] = "*" - self.assertEqual(len(changes(Templates(new_policy=p))), 1) + (out,) = changes(Templates(new_policy=p)) + self.assertIn("newly allows logs:PutLogEvents on * for WorkerRole", out) + # A condition added to a statement only narrows it: nothing to hold. p = copy.deepcopy(POLICY) p["Properties"]["PolicyDocument"]["Statement"][0]["Condition"] = {"StringEquals": {"aws:RequestedRegion": "us-east-1"}} - out = changes(Templates(new_policy=p)) - self.assertEqual(len(out), 1) - self.assertIn("resources or conditions change", out[0]) + self.assertEqual(changes(Templates(new_policy=p)), []) def test_the_import_counts_when_its_source_changes(self): # The parent feeds the import from another output. diff --git a/lambda/tests/test_updater_same_version.py b/lambda/tests/test_updater_same_version.py new file mode 100644 index 000000000..bd380f1eb --- /dev/null +++ b/lambda/tests/test_updater_same_version.py @@ -0,0 +1,219 @@ +"""An update never replaces an update to the same version. A scheduled update +held for a person (it changes permissions) left no update "running", so the +next hourly check started the same release again: a new change set, and the +one waiting was marked superseded, every hour, and never applied. The next +start for the same version now continues the prepared one. + +The replay: the beta channel at any hour, an hourly check and the 5-minute +poll, against a change set CloudFormation takes hours to make. + +Run: python3 -m unittest discover -s lambda/tests +""" + +import json +import unittest +from datetime import timedelta + +import test_updater_native as base + +u = base.u +ROLE = base.ROLE +BETA = "v1.1.0-beta.20261105" +NEXT = "v1.2.0-beta.20261106" +START = base.NOW.replace(hour=9, minute=26) +# What widens permissions in this replay: a function URL anyone may call. +WIDENS = [{"ResourceChange": {"Action": "Add", "ResourceType": "AWS::Lambda::Permission", "LogicalResourceId": "PublicInvoke"}}] + + +def only_fakes(test, fakes): + """No test here reaches AWS: a client that isn't faked fails the test.""" + saved = u.client + + def client(name, region=None): + if name not in fakes: + raise AssertionError(f"{name} would reach AWS") + return fakes[name] + u.client = client + test.addCleanup(setattr, u, "client", saved) + + +def release(tag, at="2026-10-30T00:00:00Z"): + return {"tag_name": tag, "name": tag, "body": "", "html_url": "", "published_at": at, "prerelease": True} + + +class SlowCfn(base.FakeCfn): + """CloudFormation with a change set per CreateChangeSet: each is made + after `polls` reads, runs once executed, and the stack ends UPDATE_COMPLETE.""" + + def __init__(self, polls): + super().__init__() + self.polls = polls + self.sets = {} + self.nested["nested-api"] = {"Changes": []} + + def create_change_set(self, **kw): + self.created.append(kw) + cs_id = f"arn:cs/{len(self.created)}" + self.sets[cs_id] = {"reads": 0, "executed": False} + return {"Id": cs_id} + + def describe_change_set(self, ChangeSetName, StackName=None, IncludePropertyValues=False, NextToken=None): + if ChangeSetName in self.nested: + return self.nested[ChangeSetName] + s = self.sets[ChangeSetName] + s["reads"] += 1 + if s["executed"]: + self.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "EXECUTE_COMPLETE"} + elif s["reads"] <= self.polls: + self.cs = {"Status": "CREATE_IN_PROGRESS", "ExecutionStatus": "UNAVAILABLE"} + else: + self.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE"} + return super().describe_change_set(ChangeSetName, StackName, IncludePropertyValues, NextToken) + + def execute_change_set(self, ChangeSetName, StackName): + super().execute_change_set(ChangeSetName, StackName) + self.sets[ChangeSetName]["executed"] = True + + +class HourlyChecks(unittest.TestCase): + def setUp(self): + self.store = u.Store(base.FakeDynamo(), "t") + u._clients["lambda"] = base.FakeLambda() + self._saved = (u.fetch_template, u.notify, u.model_check) + u.fetch_template = lambda url, opener=None: base.TEMPLATE + self.sent = [] + u.notify = lambda subject, text, env=None, **kw: self.sent.append((subject, kw.get("what"))) or 1 + u.model_check = lambda store, env, now, version, *a, **k: {"version": version, "results": [], "checked_at": now.isoformat()} + self.env = dict(base.ENV, DEPLOY_ROLE_ARN=ROLE) + self.store.put("AUTO_UPDATE", {"auto": True, "channel": "beta", "day": "any", "gap_hours": 2}) + self.releases = [release(BETA)] + for v in (BETA, NEXT): + self.store.put(f"MANIFEST#{v}", {"verified": True, "manifest": None, "template_sha256": base.SHA}) + + def tearDown(self): + u.fetch_template, u.notify, u.model_check = self._saved + u._clients.pop("cloudformation", None) + u._clients.pop("lambda", None) + + def replay(self, cfn, hours, start=START): + """Every hour the check, and every 5 minutes the poll, as the schedules run them.""" + u._clients["cloudformation"] = cfn + only_fakes(self, {"cloudformation": cfn, "lambda": u._clients["lambda"], "iam": base.FakeIam()}) + out = [] + for h in range(hours): + at = start + timedelta(hours=h) + out.append(u.handle({"action": "tick"}, self.env, self.store, at, fetch=lambda repo: self.releases)) + for m in range(5, 60, 5): + u.handle({"action": "native_poll"}, self.env, self.store, at + timedelta(minutes=m)) + return out + + def history(self): + return self.store.history(50) + + def test_a_slow_change_set_is_applied_once_and_never_replaced(self): + # CloudFormation takes about 4 hours to make the change set (48 polls): + # past the 3 hours an update counts as running, so later checks start it again. + cfn = SlowCfn(polls=48) + self.replay(cfn, hours=7) + self.assertEqual(len(cfn.created), 1, "one change set for one version") + self.assertEqual(cfn.executed, ["arn:cs/1"]) + self.assertEqual(cfn.deleted, []) + rows = self.history() + self.assertEqual([(h["version"], h["status"]) for h in rows], [(BETA, "succeeded")]) + self.assertNotIn("superseded", json.dumps(rows)) + + def test_a_held_update_waits_for_a_person_and_isnt_prepared_again(self): + # Held: it widens permissions. The checks of the next hours change nothing. + cfn = SlowCfn(polls=3) + cfn.nested["nested-api"] = {"Changes": WIDENS} + ticks = self.replay(cfn, hours=6) + self.assertEqual(len(cfn.created), 1) + self.assertEqual((cfn.executed, cfn.deleted), ([], [])) + (row,) = self.history() + self.assertEqual(row["status"], "review") + self.assertIn("auto-update held: it changes permissions", row["reason"]) + for d in ticks[1:]: + self.assertEqual(d["action"], "none", d) + self.assertIn(f"the update to {BETA} is prepared and waits: auto-update held", d["reason"]) + # Told once, with the one thing to do. + self.assertEqual(self.sent, [(f"update to {BETA} needs your OK", "review")]) + # The admin agrees to the permission change: the same change set applies, and the update ends applied. + at = START + timedelta(hours=6) + r = u.handle({"action": "update_now", "version": BETA, "actor": "owner@example.org", "accept_permissions": True}, + self.env, self.store, at, fetch=lambda repo: self.releases) + self.assertEqual((r["id"], r.get("continued")), (row["id"], True)) + u.handle({"action": "native_poll"}, self.env, self.store, at + timedelta(minutes=1)) + u.handle({"action": "native_poll"}, self.env, self.store, at + timedelta(minutes=6)) + self.assertEqual((len(cfn.created), cfn.executed), (1, ["arn:cs/1"])) + rows = self.history() + self.assertEqual([(h["version"], h["status"]) for h in rows], [(BETA, "succeeded")]) + self.assertEqual(rows[0]["confirmed"]["by"], "owner@example.org") + + def test_auto_update_turned_on_again_applies_the_one_waiting(self): + cfn = SlowCfn(polls=2) + u._clients["cloudformation"] = cfn + self.store.put("AUTO_UPDATE", {"auto": True, "channel": "beta", "day": "any", "gap_hours": 2}) + self.replay(cfn, hours=1) + self.assertEqual(cfn.executed, ["arn:cs/1"]) + self.assertEqual([h["status"] for h in self.history()], ["succeeded"]) + + def test_a_newer_release_still_replaces_the_one_waiting(self): + cfn = SlowCfn(polls=1) + cfn.nested["nested-api"] = {"Changes": WIDENS} + self.replay(cfn, hours=2) + self.releases = [release(NEXT, "2026-10-31T11:00:00Z"), release(BETA)] + self.replay(cfn, hours=1, start=START + timedelta(hours=2)) + rows = {h["version"]: h for h in self.history()} + self.assertEqual(rows[BETA]["status"], "superseded") + self.assertIn(f"replaced by the update to {NEXT}", rows[BETA]["reason"]) + self.assertEqual(rows[NEXT]["status"], "review") + self.assertEqual(len(cfn.created), 2) + + +class RefusedStarts(unittest.TestCase): + """An hourly check that can't start its update says so once, and the rest + of the check (reminders, the digest) still runs.""" + + def setUp(self): + self.store = u.Store(base.FakeDynamo(), "t") + self._saved = (u.notify, u.model_check, u.begin) + self.sent = [] + u.notify = lambda subject, text, env=None, **kw: self.sent.append((subject, kw.get("what"), kw.get("facts"))) or 1 + u.model_check = lambda store, env, now, version, *a, **k: {"version": version, "results": []} + self.env = dict(base.ENV, DEPLOY_ROLE_ARN=ROLE) + self.store.put("AUTO_UPDATE", {"auto": True, "channel": "beta", "day": "any"}) + + def tearDown(self): + u.notify, u.model_check, u.begin = self._saved + + def tick(self, at, why="the release's template isn't the verified one"): + def refuse(*a, **k): + raise ValueError(why) + u.begin = refuse + return u.handle({"action": "tick"}, self.env, self.store, at, fetch=lambda repo: [release(BETA)]) + + def test_a_refusal_that_repeats_is_emailed_once(self): + d = self.tick(START) + self.assertEqual(d["action"], "none") + self.assertIn("couldn't start", d["reason"]) + self.assertEqual(self.sent, []) # once can be a passing thing + for h in range(1, 5): + self.tick(START + timedelta(hours=h)) + self.assertEqual(len(self.sent), 1, self.sent) + subject, what, facts = self.sent[0] + self.assertEqual((subject, what), (f"auto-update to {BETA} keeps failing to start", "failed")) + self.assertIn("isn't the verified one", facts["reason"]) + self.assertIn("Update history", facts["action"]) + only_fakes(self, {"cloudformation": base.FakeCfn(), "iam": base.FakeIam()}) + status = u.handle({"action": "status"}, self.env, self.store, START, fetch=lambda repo: []) + self.assertEqual(status["auto_refused"]["count"], 5) + + def test_a_start_clears_the_count(self): + self.tick(START) + u.begin = lambda *a, **k: {"id": "UPDATE#x", "status": "preparing"} + u.handle({"action": "tick"}, self.env, self.store, START + timedelta(hours=1), fetch=lambda repo: [release(BETA)]) + self.assertNotIn("auto_refused", self.store.get("UPDATE_STATE")) + + +if __name__ == "__main__": + unittest.main() diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index bb6462a25..eb3703bd3 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -4145,7 +4145,47 @@ def walk(cid, part, stack_name, physical): walk(cs_id, "parent", stack, stack) out = [] + granted = {} + + def part_grants(part): + """grant_difference for one part, read once; an exception when it can't be.""" + if part not in granted: + try: + old, new = sides.sides(part) + changed = {} + for c in sides.parts.get(part, {}).get("changes") or []: + rc = c.get("ResourceChange") or {} + if rc.get("LogicalResourceId"): + changed[rc["LogicalResourceId"]] = rc.get("Action") + granted[part] = grant_difference(old, new, changed) + except Exception as e: # noqa: BLE001 never quietly fewer changes + if throttled(e): + raise + granted[part] = e + return granted[part] + + told = set() for part, rc, why in found: + lid = rc.get("LogicalResourceId") + if grant_kind(None, rc.get("ResourceType")) or (why.startswith("its ") and not (rc.get("ResourceType") or "").startswith("AWS::IAM::")): + # Read as grants: what the new release allows that the running one doesn't. + found_grants = part_grants(part) + if isinstance(found_grants, Exception): + e = found_grants + what = str(e)[:160] if isinstance(e, Unknown) else f"{type(e).__name__}: {str(e)[:160]}" + out.append(f"{part}.{lid} ({rc.get('ResourceType')} {rc.get('Action')}: {why}: " + f"it couldn't be compared with the running release ({what}))") + continue + widened, unknown = found_grants + told.add((part, lid)) + if lid in unknown: + out.append(f"{part}.{lid} ({rc.get('ResourceType')} {rc.get('Action')}: {why}: " + f"it couldn't be compared with the running release ({unknown[lid]}))") + elif widened.get(lid): + out.append(f"{part}.{lid} ({rc.get('ResourceType')} {rc.get('Action')}: {why}: {'; '.join(widened[lid])})") + else: + logger.info(f"{part}.{lid}: reported as {rc.get('Action')}, but it allows nothing the running release doesn't") + continue if rc.get("Action") in ("Modify", "Dynamic"): try: old, new = sides.sides(part) @@ -4162,6 +4202,16 @@ def walk(cid, part, stack_name, physical): continue why = f"{why}: {differs}" out.append(f"{part}.{rc.get('LogicalResourceId')} ({rc.get('ResourceType')} {rc.get('Action')}: {why})") + for part, found_grants in granted.items(): + # A widening no change above named (a deny policy removed, say). + if isinstance(found_grants, Exception): + continue + for lid, words in sorted(found_grants[0].items()): + if (part, lid) in told or not words: + continue + rc = next(((c.get("ResourceChange") or {}) for c in sides.parts[part]["changes"] + if (c.get("ResourceChange") or {}).get("LogicalResourceId") == lid), {}) + out.append(f"{part}.{lid} ({rc.get('ResourceType') or 'a policy'} {rc.get('Action') or 'Modify'}: {'; '.join(words)})") return out @@ -4241,6 +4291,13 @@ def att(lid, attr): raise Unknown(f"no resource {lid}") if isinstance(attr, str) and attr.startswith("Outputs.") and side.get("outputs"): return side["outputs"](lid, attr[len("Outputs."):]) + if attr == "Arn" and (resources.get(lid) or {}).get("Type") == "AWS::Logs::LogGroup": + # A log group's Arn is its ARN with ":*" after the name: spelled + # out, so the same group written either way compares as the same. + try: + return sub("arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:", {}) + token(lid) + ":*" + except Unknown: + pass return token(lid, attr) def sub(text, vars_): @@ -4422,6 +4479,328 @@ def policy_difference(old_side, new_side, lid): return resource_difference(resource_on(old_side, lid), resource_on(new_side, lid)) +# ── What a release newly allows ─────────────────────────────────────────── +# +# Policies are compared as what they allow, not as text. Each side of a stack +# is a set of grants (who, action, resource, condition), every policy of the +# stack together: a statement CDK moves from a role's default policy to an +# overflow policy, a list in another order, a resource written another way +# (a log group's ARN with or without ":*"), an added condition or a removed +# action allow nothing new, and apply by themselves. An update holds for a +# person only for a grant of the new side that no grant of the running side +# covers, or a deny (or a permissions boundary) the running side had and the +# new one drops. A statement with NotAction, NotResource or NotPrincipal, or a +# property this doesn't know, counts whenever it differs at all. + +# Resources whose permissions are compared as grants. +GRANT_TYPES = ("AWS::IAM::Policy", "AWS::IAM::ManagedPolicy", "AWS::IAM::Role", + "AWS::SQS::QueuePolicy", "AWS::SNS::TopicPolicy", "AWS::S3::BucketPolicy") +# What a resource policy is about, by type (any other resource: itself). +POLICY_SUBJECTS = {"AWS::SQS::QueuePolicy": "Queues", "AWS::SNS::TopicPolicy": "Topics", "AWS::S3::BucketPolicy": "Bucket"} +# Properties of a policy or a role that don't change who may do what. +GRANT_INERT = { + "AWS::IAM::Policy": ("PolicyDocument", "PolicyName", "Roles", "Users", "Groups"), + "AWS::IAM::ManagedPolicy": ("PolicyDocument", "ManagedPolicyName", "Description", "Path", "Roles", "Users", "Groups"), + "AWS::IAM::Role": ("AssumeRolePolicyDocument", "Policies", "ManagedPolicyArns", "PermissionsBoundary", + "Description", "Tags", "MaxSessionDuration", "Path", "RoleName"), +} +# Condition operators whose values a narrower grant has fewer of (a negated one: more of). +_SET_OPS = ("StringEquals", "StringEqualsIgnoreCase", "StringLike", "ArnEquals", "ArnLike", "IpAddress") +_NEGATED_OPS = ("StringNotEquals", "StringNotEqualsIgnoreCase", "StringNotLike", "ArnNotEquals", "ArnNotLike", "NotIpAddress") +_LOG_GROUP_ARN = re.compile(r":log-group:[^:*]+$") +_GLOBS = {} + + +def grant_kind(res, rtype=None): + """Whether a resource's permissions are compared as grants (its policy + documents read as what they allow).""" + t = (res or {}).get("Type") or rtype or "" + if t in GRANT_TYPES: + return True + if t.startswith("AWS::IAM::") or t in POLICY_TYPES: + return False + props = (res or {}).get("Properties") or {} + return isinstance(props, dict) and any(isinstance(props.get(k), (dict, str)) for k in POLICY_PROPERTIES) + + +def _text(v): + return v if isinstance(v, str) else json.dumps(v, sort_keys=True) + + +def _glob(pattern, value, ci): + rx = _GLOBS.get((pattern, ci)) + if rx is None: + rx = re.compile("^" + ".*".join(".".join(re.escape(q) for q in p.split("?")) for p in pattern.split("*")) + "$", + re.I if ci else 0) + _GLOBS[(pattern, ci)] = rx + return rx.match(value) is not None + + +def _condition_key(cond): + """A statement's condition as a sorted tuple of (operator, key, values).""" + if not isinstance(cond, dict): + return () if cond is None else (("?", _text(cond), ()),) + out = [] + for op, kv in cond.items(): + if not isinstance(kv, dict): + out.append((op, _text(kv), ())) + continue + for key, vals in kv.items(): + out.append((op, key, tuple(sorted(_text(x) for x in _as_list(vals))))) + return tuple(sorted(out)) + + +def _principals(p): + if p == "*": + return ["AWS:*"] + if isinstance(p, dict): + return [f"{kind}:{_text(i)}" for kind, ids in sorted(p.items()) for i in _as_list(ids)] + return [f"?:{_text(p)}"] + + +def _statement_grants(st, subject, whos): + """The grants of one statement: (subject, effect, who, action, resource, condition).""" + if not isinstance(st, dict): + return [(subject, "Prop", "?", f"statement {_text(st)}", "", ())] + effect = st.get("Effect") or "Allow" + if any(k in st for k in ("NotAction", "NotResource", "NotPrincipal")): + whole = "statement " + json.dumps({k: v for k, v in st.items() if k != "Sid"}, sort_keys=True) + return [(subject, effect, w, whole, "", ()) for w in (whos or ["?"])] + who = _principals(st["Principal"]) if "Principal" in st else (whos or ["?"]) + cond = _condition_key(st.get("Condition")) + return [(subject, effect, w, _text(a), _text(r), cond) + for w in who for a in _as_list(st.get("Action")) for r in _as_list(st.get("Resource", "*"))] + + +def grants_of(side, lid): + """Every grant resource `lid` makes on this side. A managed policy's own + grants are also kept under "policy:", for a role that attaches it by + ARN. Raises Unknown.""" + r = resource_on(side, lid) + if r["On"] is False: + return [] + t, props = r["Type"], r["Properties"] + + def me(): + return _text(template_resolve({"Ref": lid}, side)) + out = [] + if t in ("AWS::IAM::Policy", "AWS::IAM::ManagedPolicy"): + whos = [f"id:{_text(x)}" for k in ("Roles", "Users", "Groups") for x in _as_list(props.get(k))] + if t == "AWS::IAM::ManagedPolicy": + # Attached by ARN somewhere else (or nowhere yet): its grants count as its own. + whos.append(f"policy:{me()}" + ("" if whos else "!")) + for st in _as_list((props.get("PolicyDocument") or {}).get("Statement")): + out += _statement_grants(st, "", whos) + elif t == "AWS::IAM::Role": + who = f"id:{me()}" + for p in _as_list(props.get("Policies")): + for st in _as_list(((p or {}).get("PolicyDocument") or {}).get("Statement")): + out += _statement_grants(st, "", [who]) + for st in _as_list((props.get("AssumeRolePolicyDocument") or {}).get("Statement")): + out += _statement_grants(st, f"assume:{me()}", []) + out += [("", "Attach", who, _text(arn), "", ()) for arn in _as_list(props.get("ManagedPolicyArns"))] + if props.get("PermissionsBoundary"): + out.append(("", "Boundary", who, _text(props["PermissionsBoundary"]), "", ())) + else: + key = POLICY_SUBJECTS.get(t) + subjects = [_text(x) for x in _as_list(props.get(key))] if key else [me()] + for k, doc in sorted(props.items()): + if k in POLICY_DOCUMENTS and isinstance(doc, dict): + out += [g for s in subjects for st in _as_list(doc.get("Statement")) + for g in _statement_grants(st, f"res:{s}", [])] + elif k in POLICY_DOCUMENTS: + # Not a policy document this can read: it counts whenever it differs. + out.append(("", "Prop", f"res:{lid}", f"its {k} is {_text(doc)[:120]}", "", ())) + inert = GRANT_INERT.get(t) + if inert is not None: + out += [("", "Prop", f"res:{lid}", f"its {k} is {json.dumps(props[k], sort_keys=True)[:120]}", "", ()) + for k in sorted(props) if k not in inert] + return out + + +def _attached(grants): + """A role's managed policy attached by ARN, as that policy's grants (one + of the stack's own), or the attachment itself (any other).""" + by_policy = {} + for g, origins in grants.items(): + if g[2].startswith("policy:"): + by_policy.setdefault(g[2][len("policy:"):].rstrip("!"), []).append((g, origins)) + out = {} + used = {g[3] for g in grants if g[1] == "Attach" and g[3] in by_policy} + for g, origins in grants.items(): + if g[1] == "Attach" and g[3] in by_policy: + for pg, po in by_policy[g[3]]: + out.setdefault((pg[0], pg[1], g[2]) + pg[3:], set()).update(po | origins) + elif g[2].startswith("policy:") and (not g[2].endswith("!") or g[2][len("policy:"):-1] in used): + # Attached here (its own Roles, Users or Groups, or a role's ARN): what + # it grants is compared as those identities' grants. One attached + # nowhere in this stack keeps its grants as its own. + continue + else: + out.setdefault(g, set()).update(origins) + return out + + +def _stricter(new, old): + """Whether condition `new` allows no more than `old`: every test of old is + in new, on the same values or fewer (a negated test: the same or more).""" + have = {(op, key.lower()): vals for op, key, vals in new} + for op, key, vals in old: + got = have.get((op, key.lower())) + if got is None: + return False + base = op.split(":")[-1] + if op.startswith("ForAllValues:"): + ok = got == vals + elif base in _NEGATED_OPS or base.removesuffix("IfExists") in _NEGATED_OPS: + ok = set(got) >= set(vals) + elif base in _SET_OPS or base.removesuffix("IfExists") in _SET_OPS: + ok = set(got) <= set(vals) + else: + ok = got == vals + if not ok: + return False + return True + + +def _covers(o, n): + """Whether grant `o` allows (or, for a deny, refuses) everything grant `n` does.""" + if o == n: + return True + if o[:2] != n[:2] or o[1] not in ("Allow", "Deny") or o[3].startswith("statement ") or n[3].startswith("statement "): + return False + if o[2] != n[2] and o[2] not in ("AWS:*", "*:*"): + return False + if not _glob(o[3], n[3], True): + return False + same = [n[4], n[4] + ":*"] if _LOG_GROUP_ARN.search(n[4]) else [n[4]] + return any(_glob(o[4], r, False) for r in same) and _stricter(n[5], o[5]) + + +def _widening(old, new): + """[(grant, origins, newly)] where `newly` is True for a grant only the new + side allows, False for a deny or boundary only the running side had.""" + def index(grants): + by = {} + for g in grants: + by.setdefault(g[:2], []).append(g) + return by + old_by, new_by = index(old), index(new) + out = [] + for g, origins in sorted(new.items()): + if g[1] in ("Deny", "Boundary") or g in old: + continue + if not any(_covers(o, g) for o in old_by.get(g[:2], [])): + out.append((g, origins, True)) + for g, origins in sorted(old.items()): + if g[1] not in ("Deny", "Boundary") or g in new: + continue + if not any(_covers(n, g) for n in new_by.get(g[:2], [])): + out.append((g, origins, False)) + return out + + +_TOKEN = re.compile(r"\$\{(?:[^}/]*/)?([A-Za-z][A-Za-z0-9]*?)(?:[0-9A-F]{8})?(?:\.[A-Za-z.]+)?\}") + + +def _plain(text): + """A template value in plain words: a resource of the stack by its name.""" + return _TOKEN.sub(lambda m: m.group(1), str(text)) + + +def _who_words(who): + kind, _, rest = who.partition(":") + if who in ("AWS:*", "*:*"): + return "anyone" + if kind == "Service": + return f"the AWS service {rest}" + if kind == "policy": + return f"whoever has {_plain(rest.rstrip('!'))} attached" + return _plain(rest) + + +def _condition_words(cond): + parts = [] + for op, key, vals in cond: + how = "is" if op.removesuffix("IfExists") in ("StringEquals", "ArnEquals", "StringLike", "ArnLike") else op + parts.append(f"{key} {how} {' or '.join(_plain(v) for v in vals)}") + return (" when " + " and ".join(parts)) if parts else "" + + +def grant_words(widened): + """What a list of (grant, newly) means, in plain words.""" + groups = {} + for g, newly in widened: + groups.setdefault((g[1], g[2], g[5], newly), {}).setdefault(g[3], set()).add(g[4]) + lines = [] + for (effect, who, cond, newly), acts in sorted(groups.items()): + to = f" for {_who_words(who)}" + _condition_words(cond) + if effect == "Attach": + lines += [f"attaches the managed policy {_plain(a)}{to}" for a in sorted(acts)] + continue + if effect == "Boundary": + lines += [f"drops the permissions boundary {_plain(a)}{to}" for a in sorted(acts)] + continue + if effect == "Prop": + lines += [_plain(a) if not a.startswith("statement ") else "a statement with NotAction, NotResource or NotPrincipal changes" + for a in sorted(acts)] + continue + by_res = {} + for a, rs in acts.items(): + if a.startswith("statement "): + lines.append(f"{'allows' if newly else 'no longer refuses'} what a NotAction, NotResource or NotPrincipal statement names{to}") + continue + by_res.setdefault(tuple(sorted(rs)), []).append(a) + for rs, names in sorted(by_res.items()): + verb = "newly allows" if newly else "no longer denies" + lines.append(f"{verb} {', '.join(sorted(names))} on {', '.join(_plain(r) for r in rs)}{to}") + return lines + + +def grant_difference(old_side, new_side, changed): + """What the new side of a stack newly allows, every grant-kind resource + together: ({lid: [plain words]}, {lid: why it couldn't be compared}). + `changed`: {lid: the change set's action} for the resources it changes; + every other resource is the same on both sides (read once, from the + running side, and left out of both when it can't be read).""" + old_res = (old_side.get("t") or {}).get("Resources") or {} + new_res = (new_side.get("t") or {}).get("Resources") or {} + old, new, unknown = {}, {}, {} + + def add(into, grants, lid): + for g in grants: + into.setdefault(g, set()).add(lid) + for lid, action in changed.items(): + if lid not in new_res and action != "Remove": + # The change set adds or changes what the new template doesn't have: never read as nothing. + unknown[lid] = f"{lid} isn't in the new release's template" + for lid in sorted(set(old_res) | set(new_res)): + if not (grant_kind(old_res.get(lid)) or grant_kind(new_res.get(lid))): + continue + try: + if lid in changed: + a = grants_of(old_side, lid) if lid in old_res else [] + if lid in new_res: + b = grants_of(new_side, lid) + elif changed[lid] == "Remove": + b = [] + else: + raise Unknown(f"{lid} isn't in the new release's template") + else: + a = b = grants_of(old_side, lid) if lid in old_res else grants_of(new_side, lid) + except Unknown as e: + if lid in changed: + unknown[lid] = str(e)[:160] + continue + add(old, a, lid) + add(new, b, lid) + out = {} + for g, origins, newly in _widening(_attached(old), _attached(new)): + for lid in sorted(origins): + out.setdefault(lid, []).append((g, newly)) + return {lid: grant_words(w) for lid, w in out.items()}, unknown + + class ChangeSides: """Both sides of every stack a change set touches (the parent and each part with a nested change set), each read once and only when asked.""" @@ -5774,6 +6153,62 @@ def check_replaceable(store, env, state, cfn=None): raise ValueError(f"the update to {e.get('version')} is still being prepared; try again in a minute") +def same_version_open(store, env, state, version, mode, cfn=None): + """(id, entry) of the prepared update to this same version that hasn't run + and whose change set can still run here, or None. A second start for the + same version (the next hourly check, an admin's press) continues that one: + an update never replaces an update to the same version. One made without + the deploy role the install has now, or whose change set can no longer + run, isn't continued: a new one is prepared instead.""" + if mode != "update": + return None + role = env.get("DEPLOY_ROLE_ARN") or "" + found = [(hid, e) for hid, e in open_updates(store, state) + if e.get("version") == version and e.get("mode") == mode] + if not found: + return None + cfn = cfn or client("cloudformation") + for hid, e in found: + made = prepared_role(e) + if (role if made is None else made) != role: + continue + try: + status, execution = change_set_state(cfn, env, e["change_set_id"]) + except Exception as ex: # noqa: BLE001 unreadable: never replaced on a guess + if throttled(ex): + raise + logger.warning(f"open update {hid} not read: {ex}") + return hid, e + if status in ("CREATE_PENDING", "CREATE_IN_PROGRESS") or (status == "CREATE_COMPLETE" and execution == "AVAILABLE"): + return hid, e + return None + + +def continue_open(store, state, now, hid, entry, actor, scheduled=False, consent=False, note=None): + """The same-version update already prepared, as this start asks for it: an + admin's press makes it theirs (and, with their OK for permission changes, + lets it apply); the hourly check changes nothing. The next poll reads + the hold again and applies it when nothing holds it any more.""" + if not scheduled: + if entry.get("scheduled"): + entry.pop("scheduled", None) + entry["actor"] = actor + if consent and not consented(entry): + entry["consent"] = {"permissions": True, "by": actor, "at": now.isoformat()} + if note: + entry["note"] = note + store.put(hid, entry) + for k in ("review_id", "running_id", "running_since"): + state.pop(k, None) + if entry.get("status") == "review": + state["review_id"] = hid + else: + state.update({"running_id": hid, "running_since": entry.get("started_at") or now.isoformat()}) + store.put("UPDATE_STATE", state) + logger.info(f"update to {entry.get('version')} continues {hid} ({'the hourly check' if scheduled else actor})") + return dict(entry, id=hid, continued=True) + + def supersede_open(store, env, state, now, by_id, by_version, cfn=None): """Marks every other prepared-but-unapplied update superseded by `by_id` and deletes its change set while it never ran. `state` loses @@ -6028,6 +6463,10 @@ def begin(store, env, now, version, actor, mode, extra=None, note=None, schedule if running(state, now) and not (native and unapplied(live)): raise ValueError("an update is already running") if native: + # Already prepared for this version: continued, never replaced. + same = same_version_open(store, env, state, version, mode) + if same: + return continue_open(store, state, now, *same, actor, scheduled=scheduled, consent=consent, note=note) check_replaceable(store, env, state) current = env.get("CODERHELM_VERSION", "") if parse_version(current): @@ -6088,6 +6527,43 @@ def refused(e): return dict(entry, id=hid) +# An auto-update the hourly check couldn't start this many times in a row +# (the same version, refused before anything changed) is emailed, once. +AUTO_REFUSED_TELL = 2 + + +def auto_started(store): + """The hourly check started (or continued) its update: no refusal streak.""" + state = store.get("UPDATE_STATE", {}) or {} + if state.pop("auto_refused", None) is not None: + store.put("UPDATE_STATE", state) + + +def auto_refused(store, env, now, version, why): + """Counts the hourly check's refusals of `version` in a row; at + AUTO_REFUSED_TELL the admins get one email (the update notice, "failed") + and Settings, System has the rows in Update history. A newer version + starts the count again.""" + state = store.get("UPDATE_STATE", {}) or {} + rec = state.get("auto_refused") or {} + if rec.get("version") != version: + rec = {"version": version, "count": 0, "since": now.isoformat()} + rec.update(count=int(rec.get("count") or 0) + 1, reason=fit(why, 500), at=now.isoformat()) + state["auto_refused"] = rec + store.put("UPDATE_STATE", state) + logger.warning(f"auto-update to {version} couldn't start ({rec['count']} in a row): {why}") + if rec["count"] < AUTO_REFUSED_TELL: + return 0 + action = "Open Settings, System: Update history names what stopped it. Fix that, then press Update now." + return notify_once(store, f"auto_not_started:{version}", now, f"auto-update to {version} keeps failing to start", + f"Auto-update tried {version} {rec['count']} times since {checked_at(when(rec['since']) or now)} and it " + f"couldn't start: {why}. Nothing changed.\n{app_url(env)}/settings/system/", + env, what="failed", version=version, + facts={"current": env.get("CODERHELM_VERSION"), "checked_at": checked_at(now), + "reason": f"Auto-update couldn't start it, {rec['count']} hourly checks in a row: {why}. Nothing changed.", + "action": action}) + + def history_view(entries, state, now): """History as people read it. A row left running or preparing that isn't the update in progress has ended: one that never made a change set or a @@ -6185,6 +6661,8 @@ def releases(max_age, refresh=False): # Releases whose last try failed or rolled back: the dashboard's # update preflight shows them with the reason from history. "failed_versions": sorted(state.get("failed_versions") or []), + # The hourly check couldn't start its update (version, count in a row, reason), or None. + "auto_refused": state.get("auto_refused") or None, "history": history_view(store.history(), state, now), # The model check for the latest release (Settings, System and Setup). "model_check": mc_view, @@ -6499,11 +6977,22 @@ def releases(max_age, refresh=False): "reason": "a model this release calls was refused; checking again daily"} else: try: - begin(store, env, now, d["version"], "auto", "update", scheduled=True) + started = begin(store, env, now, d["version"], "auto", "update", scheduled=True) or {} + auto_started(store) + if started.get("continued"): + # Prepared at an earlier check and still pending: it goes on as it is. + d = dict(d, action="none", reason=f"the update to {d['version']} is prepared" + + (f" and waits: {started['reason']}" if started.get("status") == "review" and started.get("reason") + else "; it goes on by itself")) except AwsBusy as e: # Nothing changed: the next hourly check in the window starts it again. logger.warning(f"AWS is busy, the update starts at the next check: {e.cause}") d = dict(d, action="none", reason="AWS is busy, retrying at the next check") + except ValueError as e: + # Refused before anything changed (history has the row). The + # rest of the check still runs; a refusal that repeats is told once. + d = dict(d, action="none", reason=f"the update couldn't start: {e}") + auto_refused(store, env, now, d["version"], str(e)) remind_waiting(store, env, now, current) send_digest(store, env, now, settings, rel, current) release_report(store, env, now, settings) diff --git a/services/worker/src/passes/incidents/xs_update_continues_its_own_version.rs b/services/worker/src/passes/incidents/xs_update_continues_its_own_version.rs new file mode 100644 index 000000000..abd8d46b1 --- /dev/null +++ b/services/worker/src/passes/incidents/xs_update_continues_its_own_version.rs @@ -0,0 +1,76 @@ +//! xs. A self-hosted install with auto-update on stayed on one release: +//! each beta was held for a person (it changed permissions), a held +//! update isn't "running", so every hourly check prepared the same release +//! again and marked the waiting one superseded by its own version. Half of +//! each hold allowed nothing new: a log-read statement rewritten with the +//! log group's bare ARN beside its `:*` ARN, compared as text. +//! +//! Guarantees: a second start for the same version continues the prepared +//! change set (`same_version_open`, `continue_open`), never replaces it; +//! permission changes are compared as grants across every policy of a part +//! (`grant_difference`) and the hold names what is newly allowed; an hourly +//! check that can't start its update goes on and tells the admins once +//! (`auto_refused`). The Python replays live in +//! `lambda/tests/test_updater_same_version.py` and +//! `lambda/tests/test_updater_grants.py`; this case holds the wiring. + +const UPDATER: &str = include_str!("../../../../../lambda/updater/handler.py"); +const IAM_DIFF: &str = include_str!("../../../../../.github/scripts/iam_diff.py"); + +/// The Python function `name` (up to the next top-level definition). +fn py_fn<'a>(src: &'a str, name: &str) -> &'a str { + let head = format!("\ndef {name}("); + let start = src.find(&head).unwrap_or_else(|| panic!("{name} is gone")); + let rest = &src[start + 1..]; + let end = rest[1..] + .find("\ndef ") + .or_else(|| rest[1..].find("\nclass ")) + .map(|i| i + 1) + .unwrap_or(rest.len()); + &rest[..end] +} + +#[test] +fn a_start_for_the_same_version_continues_the_prepared_one() { + let begin = py_fn(UPDATER, "begin"); + let same = begin + .find("same_version_open(") + .expect("begin looks for the same version first"); + let replace = begin + .find("check_replaceable(") + .expect("begin still refuses to replace what runs"); + let supersede = begin + .find("supersede_open(") + .expect("begin still replaces an older version"); + assert!(same < replace && replace < supersede, "{begin}"); + assert!(begin.contains("return continue_open(")); + let open = py_fn(UPDATER, "same_version_open"); + assert!(open.contains("e.get(\"version\") == version")); + assert!(open.contains("CREATE_IN_PROGRESS")); + let cont = py_fn(UPDATER, "continue_open"); + assert!(cont.contains("\"consent\"")); + assert!(cont.contains("continued=True")); +} + +#[test] +fn the_hourly_check_says_what_waits_and_tells_a_refusal_once() { + let handle = py_fn(UPDATER, "handle"); + assert!(handle.contains("started.get(\"continued\")")); + assert!(handle.contains("auto_refused(store, env, now, d[\"version\"], str(e))")); + let refused = py_fn(UPDATER, "auto_refused"); + assert!(refused.contains("notify_once(")); + assert!(refused.contains("AUTO_REFUSED_TELL")); +} + +#[test] +fn permissions_are_compared_as_what_they_allow() { + let changes = py_fn(UPDATER, "permission_changes"); + assert!(changes.contains("grant_difference(old, new, changed)")); + assert!(changes.contains("couldn't be compared")); + let diff = py_fn(UPDATER, "grant_difference"); + assert!(diff.contains("_widening(_attached(old), _attached(new))")); + // The release notes compare the same way. + assert!(IAM_DIFF.contains("u.grant_difference(sa, sb, changed)")); + // A log group's ARN with or without ":*" is the same group. + assert!(py_fn(UPDATER, "_covers").contains("_LOG_GROUP_ARN")); +} From c2a77f54f241293738d35ed334e23c06613d6542 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Fri, 4 Dec 2026 21:25:53 -0500 Subject: [PATCH 2/2] Count only recorded refusals as failed auto-update starts, and never let ? cover * in a grant - begin's refusals (written to history as not_started) raise StartRefused. The hourly check counts and emails only those; a wait (ReleaseNotReady, another update still being prepared or running) writes nothing, sends nothing, and leaves the count as it is. - Grant coverage compares pattern with pattern (_pattern_covers): a ? in the running grant covers one character or a ?, never a *; only a * covers a * in the new grant. Used for actions and resources, so the release notes (iam_diff.py) follow it too. - Tests: waits never counted or emailed, a wait between refusals, begin marking only its recorded refusals; ?, * and mixed patterns, a running ? against a new *, and the release notes path. --- docs/self-host/updates.md | 2 +- lambda/tests/test_updater_grants.py | 50 +++++++++++++++++++ lambda/tests/test_updater_same_version.py | 45 ++++++++++++++++- lambda/updater/handler.py | 60 ++++++++++++++++++----- 4 files changed, 141 insertions(+), 16 deletions(-) diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index 05d26e713..42c16cb75 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -56,7 +56,7 @@ A new release doesn't email anyone, and neither does an update that finished: ** |---|---| | **update to vX needs your OK** | A prepared update waits for an admin: to confirm the data or permission changes it lists, to press **Apply**, or for someone with administrator rights in the AWS account. Also when [the model check](#the-model-check) refuses a model the release calls. | | **update to vX still needs your OK** | The same update still waits 7 days later. Sent once. | -| **update to vX failed** / **rolled back** | The update stopped, or CloudFormation put the previous release back. The email says where the install is now and what to do. Also when auto-update couldn't start vX at two hourly checks in a row (nothing changed): the email says what stopped it, and **Update history** has a row for each try. | +| **update to vX failed** / **rolled back** | The update stopped, or CloudFormation put the previous release back. The email says where the install is now and what to do. Also when auto-update couldn't start vX at two hourly checks in a row (nothing changed): the email says what stopped it, and **Update history** has a row for each try. A wait (the release still publishing or being verified, another update still being prepared or applied) is never counted. | | **the new address is live** / **the address change failed** / **back on the AWS address** | A [domain](./domains.md) change finished, failed, or was undone. | | **what's new, up to vX** | The digest, below. | diff --git a/lambda/tests/test_updater_grants.py b/lambda/tests/test_updater_grants.py index e07610a09..c7d5bbae1 100644 --- a/lambda/tests/test_updater_grants.py +++ b/lambda/tests/test_updater_grants.py @@ -145,6 +145,56 @@ def test_what_cant_be_resolved_counts(self): self.assertIn("Default", unknown) +class Wildcards(unittest.TestCase): + """A wildcard in the new grant is covered only by a running pattern at + least as broad: a `?` never covers a `*`, and a `*` covers both.""" + + def test_patterns(self): + cases = [ + ("s3:Get?", "s3:Get*", False), ("s3:Get?", "s3:GetX", True), ("s3:Get?", "s3:Get?", True), + ("s3:Get*", "s3:Get?", True), ("s3:*", "s3:Get*", True), ("s3:Get*", "s3:*", False), + ("arn:aws:s3:::b/?", "arn:aws:s3:::b/*", False), ("arn:aws:s3:::b/*", "arn:aws:s3:::b/a/*", True), + ("arn:aws:s3:::b/*/x", "arn:aws:s3:::b/*", False), ("arn:aws:s3:::b/a?*", "arn:aws:s3:::b/a*", False), + ("arn:aws:s3:::b/a*?", "arn:aws:s3:::b/ab?", True), ("arn:aws:s3:::b/??", "arn:aws:s3:::b/?*", False), + ("*", "anything*?", True), + ] + for wide, narrow, want in cases: + self.assertEqual(u._pattern_covers(wide, narrow, False), want, (wide, narrow)) + # Actions compare without case, resources with it. + self.assertTrue(u._pattern_covers("S3:GET*", "s3:getobject", True)) + self.assertFalse(u._pattern_covers("arn:aws:s3:::B/*", "arn:aws:s3:::b/x", False)) + + def test_a_question_mark_running_never_covers_a_new_star(self): + old = stack(Default=policy("AWS::IAM::Policy", [TABLE, statement("logs:Get?", "arn:aws:s3:::reports/?")])) + for action, resource in (("logs:Get*", "arn:aws:s3:::reports/?"), ("logs:Get?", "arn:aws:s3:::reports/*"), + ("logs:Get*", "arn:aws:s3:::reports/*")): + widened, _ = compare(stack(Default=policy("AWS::IAM::Policy", [TABLE, statement(action, resource)])), old) + self.assertIn("Default", widened, (action, resource)) + # The other way round narrows: a star running covers a question mark new. + star = stack(Default=policy("AWS::IAM::Policy", [TABLE, statement("logs:Get*", "arn:aws:s3:::reports/*")])) + self.assertEqual(compare(old, star), ({}, {})) + + def test_the_release_notes_compare_the_same_way(self): + import importlib.util + import pathlib + import tempfile + path = pathlib.Path(__file__).resolve().parents[2] / ".github" / "scripts" / "iam_diff.py" + spec = importlib.util.spec_from_file_location("iam_diff_wildcards", path) + iam_diff = importlib.util.module_from_spec(spec) + spec.loader.exec_module(iam_diff) + root = pathlib.Path(tempfile.mkdtemp()) + for name, t in (("old", stack(Default=policy("AWS::IAM::Policy", [TABLE, statement("logs:Get?", "*")]))), + ("new", stack(Default=policy("AWS::IAM::Policy", [TABLE, statement("logs:Get*", "*")]))), + ("narrow", stack(Default=policy("AWS::IAM::Policy", [TABLE, statement("logs:GetX", "*")])))): + (root / name / "stacks").mkdir(parents=True) + (root / name / "stacks" / "Worker.json").write_text(json.dumps(t)) + (root / name / "coderhelm.json").write_text(json.dumps({"Resources": {}})) + (change,) = iam_diff.diff(root / "old", root / "new") + self.assertEqual(change[1], "Default") + self.assertIn("newly allows logs:Get*", change[3]) + self.assertEqual(iam_diff.diff(root / "old", root / "narrow"), []) + + class Narrowing(unittest.TestCase): """Applied by itself: nothing becomes newly allowed.""" diff --git a/lambda/tests/test_updater_same_version.py b/lambda/tests/test_updater_same_version.py index bd380f1eb..a5448797f 100644 --- a/lambda/tests/test_updater_same_version.py +++ b/lambda/tests/test_updater_same_version.py @@ -186,9 +186,9 @@ def setUp(self): def tearDown(self): u.notify, u.model_check, u.begin = self._saved - def tick(self, at, why="the release's template isn't the verified one"): + def tick(self, at, why="the release's template isn't the verified one", kind=None): def refuse(*a, **k): - raise ValueError(why) + raise (kind or u.StartRefused)(why) u.begin = refuse return u.handle({"action": "tick"}, self.env, self.store, at, fetch=lambda repo: [release(BETA)]) @@ -208,6 +208,47 @@ def test_a_refusal_that_repeats_is_emailed_once(self): status = u.handle({"action": "status"}, self.env, self.store, START, fetch=lambda repo: []) self.assertEqual(status["auto_refused"]["count"], 5) + def test_waits_are_never_counted_or_emailed(self): + # The release still publishing, its template not verified yet, another + # update being prepared or running: each passes by itself. + waits = [(u.ReleaseNotReady, "the release is still being published"), + (u.ReleaseNotReady, "its template isn't verified yet"), + (ValueError, "the update to v1.0.5 is still being prepared; try again in a minute"), + (ValueError, "an update is already running")] + for h, (kind, why) in enumerate(waits * 2): + d = self.tick(START + timedelta(hours=h), why, kind) + self.assertEqual(d["action"], "none") + self.assertIn("waiting", d["reason"]) + self.assertEqual(self.sent, []) + self.assertNotIn("auto_refused", self.store.get("UPDATE_STATE") or {}) + self.assertEqual(self.store.history(), []) + + def test_a_wait_between_refusals_neither_counts_nor_clears(self): + self.tick(START) + self.tick(START + timedelta(hours=1), "an update is already running", ValueError) + self.assertEqual(self.store.get("UPDATE_STATE")["auto_refused"]["count"], 1) + self.assertEqual(self.sent, []) + self.tick(START + timedelta(hours=2)) + self.assertEqual(len(self.sent), 1) + + def test_begin_marks_only_its_recorded_refusals(self): + # A refusal begin writes as not_started is a StartRefused; a wait is not. + store = u.Store(base.FakeDynamo(), "t") + cfn = base.FakeCfn() + only_fakes(self, {"cloudformation": cfn, "lambda": base.FakeLambda(), "iam": base.FakeIam()}) + u.begin = self._saved[2] + saved = u.native_propose + self.addCleanup(setattr, u, "native_propose", saved) + u.native_propose = lambda *a, **k: (_ for _ in ()).throw(ValueError("the release's template isn't the verified one")) + with self.assertRaises(u.StartRefused): + u.begin(store, self.env, START, BETA, "auto", "update", scheduled=True) + self.assertEqual([h["status"] for h in store.history()], ["not_started"]) + u.native_propose = lambda *a, **k: (_ for _ in ()).throw(u.ReleaseNotReady("still publishing")) + with self.assertRaises(u.ReleaseNotReady) as cm: + u.begin(store, self.env, START + timedelta(minutes=1), BETA, "auto", "update", scheduled=True) + self.assertNotIsInstance(cm.exception, u.StartRefused) + self.assertEqual(len(store.history()), 1) + def test_a_start_clears_the_count(self): self.tick(START) u.begin = lambda *a, **k: {"id": "UPDATE#x", "status": "preparing"} diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index eb3703bd3..0f68e2ff5 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -1663,6 +1663,13 @@ class ReleaseNotReady(ValueError): check hasn't verified it): a wait. Nothing is recorded in history.""" +class StartRefused(ValueError): + """An update refused before anything changed, recorded in history as + not_started (begin's `refused`). Unlike a wait (the release still + publishing, an update still being prepared or running), it doesn't pass + by itself: the hourly check counts these, and only these, as refusals.""" + + class AwsBusy(ReleaseNotReady): """AWS throttled a step before anything changed: a wait like the one above, retried by itself (`cause`: what AWS said).""" @@ -4527,13 +4534,36 @@ def _text(v): return v if isinstance(v, str) else json.dumps(v, sort_keys=True) -def _glob(pattern, value, ci): - rx = _GLOBS.get((pattern, ci)) - if rx is None: - rx = re.compile("^" + ".*".join(".".join(re.escape(q) for q in p.split("?")) for p in pattern.split("*")) + "$", - re.I if ci else 0) - _GLOBS[(pattern, ci)] = rx - return rx.match(value) is not None +def _pattern_covers(wide, narrow, ci): + """Whether IAM pattern `wide` matches everything pattern `narrow` can + (each may hold * and ?). A literal in `narrow` is matched by the same + literal, `?` or `*` in `wide`; a `?` in `narrow` only by `?` or `*`; a + `*` in `narrow` only by a `*` in `wide`. So `s3:Get?` never covers + `s3:Get*`, and `s3:*` covers both. Sound: when it says covered, every + value `narrow` allows is one `wide` allows.""" + key = (wide, narrow, ci) + if key in _GLOBS: + return _GLOBS[key] + if ci: + wide, narrow = wide.lower(), narrow.lower() + w, n = len(wide), len(narrow) + # ok[i][j]: wide[i:] covers narrow[j:]. + ok = [[False] * (n + 1) for _ in range(w + 1)] + ok[w][n] = True + for i in range(w - 1, -1, -1): + for j in range(n, -1, -1): + c = wide[i] + if c == "*": + # The star covers nothing more (i+1), or one more token of narrow, whatever it is. + ok[i][j] = ok[i + 1][j] or (j < n and ok[i][j + 1]) + elif j < n: + t = narrow[j] + if c == "?": + ok[i][j] = t != "*" and ok[i + 1][j + 1] + else: + ok[i][j] = t == c and ok[i + 1][j + 1] + _GLOBS[key] = ok[0][0] + return ok[0][0] def _condition_key(cond): @@ -4671,10 +4701,10 @@ def _covers(o, n): return False if o[2] != n[2] and o[2] not in ("AWS:*", "*:*"): return False - if not _glob(o[3], n[3], True): + if not _pattern_covers(o[3], n[3], True): return False same = [n[4], n[4] + ":*"] if _LOG_GROUP_ARN.search(n[4]) else [n[4]] - return any(_glob(o[4], r, False) for r in same) and _stricter(n[5], o[5]) + return any(_pattern_covers(o[4], r, False) for r in same) and _stricter(n[5], o[5]) def _widening(old, new): @@ -6492,9 +6522,7 @@ def refused(e): entry.update({"status": "not_started", "reason": not_started_reason(e), "finished_at": now.isoformat()}) entry.update(not_started_details(e, version, current)) store.put(hid, entry) - if isinstance(e, ValueError): - raise e - raise ValueError(entry["reason"]) from e + raise StartRefused(str(e) if isinstance(e, ValueError) else entry["reason"]) from e if is_native(env): try: @@ -6988,11 +7016,17 @@ def releases(max_age, refresh=False): # Nothing changed: the next hourly check in the window starts it again. logger.warning(f"AWS is busy, the update starts at the next check: {e.cause}") d = dict(d, action="none", reason="AWS is busy, retrying at the next check") - except ValueError as e: + except StartRefused as e: # Refused before anything changed (history has the row). The # rest of the check still runs; a refusal that repeats is told once. d = dict(d, action="none", reason=f"the update couldn't start: {e}") auto_refused(store, env, now, d["version"], str(e)) + except ValueError as e: + # A wait, never a refusal: the release still publishing or not + # verified yet (ReleaseNotReady), or another update still being + # prepared or running. Nothing is written, nobody is emailed, + # and the next check tries again. + d = dict(d, action="none", reason=f"waiting: {e}") remind_waiting(store, env, now, current) send_digest(store, env, now, settings, rel, current) release_report(store, env, now, settings)