diff --git a/docs/self-host/troubleshooting.md b/docs/self-host/troubleshooting.md index f20cdf022..bc2f7e132 100644 --- a/docs/self-host/troubleshooting.md +++ b/docs/self-host/troubleshooting.md @@ -87,7 +87,7 @@ Each step checks what you did before it moves on. When a check fails, fix it and **The update says it can't install yet.** **Install health** on **Settings, then System** lists the check that stops it (marked **Stops updates**), with its fix. Press **Re-run checks** after fixing it. **Update to vX needs your action** is the model check instead: fix the model access, then **Re-run the model check**. -**The update waits: "needs your OK", "ready to apply" or "needs an AWS admin".** It is prepared and waits for a person. **Review and apply** lists the data or permission changes to confirm; **Apply vX** applies it; **needs an AWS admin** means it changes the deploy role or a permissions boundary, so someone with administrator rights executes it in the AWS console. Admins get one email when it starts waiting, and one reminder after 7 days. See [The page, state by state](./updates.md#the-page-state-by-state). +**The update waits: "would replace or remove data", "ready to apply" or "needs an AWS admin".** It is prepared and waits for a person. **Replace the data and apply** applies an update after the card has listed the data it replaces or removes; **Apply update** applies one the maintenance window held; **needs an AWS admin** means it changes the deploy role or a permissions boundary, so someone with administrator rights executes it in the AWS console. Admins get one email when it starts waiting, and one reminder after 7 days. See [The page, state by state](./updates.md#the-page-state-by-state). **"This update was prepared without the deploy role".** The install runs v0.8.28 to v0.8.38, whose apply check was wrong. Execute that one change set in the CloudFormation console; from v0.8.39 on, updates apply from the page. See [Installs on v0.8.28 to v0.8.38](./updates.md#installs-on-v0828-to-v0838). diff --git a/docs/self-host/updates.md b/docs/self-host/updates.md index 75dae3cb0..a48a18520 100644 --- a/docs/self-host/updates.md +++ b/docs/self-host/updates.md @@ -106,11 +106,12 @@ The **Version** section of **Settings, then System** shows one state at a time, | **You're up to date** | No newer release on your channel. With automatic updates on, it says when the next one would install. | Nothing. **Check for updates** reads GitHub now. | | **Updated to vX** | An update finished in the last day. | Nothing. | | **vX is available** | A newer release is out; its notes are below. **Major release** means its notes ask you to do something first; **Beta** means a nightly build on the Beta channel. | **Update to vX**. | -| **Checking vX before it can be applied** | The release check runs: the signature, the checksums, then a test call to each model the release calls. It usually takes about 5 minutes. | Nothing. The page moves on by itself. | +| **Checking vX before it can be applied** | The release check runs: the signature, the checksums, then a test call to each model the release calls. It usually takes about 5 minutes. If you pressed **Update**, the card says who pressed it and when: the update starts by itself once the check passes, exactly as if you pressed again. | Nothing. The page moves on by itself. | | **Checking vX didn't finish** | The release check stopped without an answer, or has had none for 30 minutes. It says why. Nothing changed. | **Check again**. | | **Update to vX needs your action** | A model the release calls doesn't answer here yet ([the model check](#the-model-check)). | Fix it in the AWS console, then **Re-run the model check**. | | **Preparing the update to vX…** | AWS prepares the change to your stack, which takes a minute or two. | Nothing. If it would change data or permissions, it asks you first. | -| **vX needs your OK** | The prepared update would replace or remove data or change permissions, and waits for you ([Update now](#update-now)). | **Review and apply**: check the listed changes, then confirm. | +| **vX would replace or remove data** | The prepared update would replace or remove data, and waits for you ([Update now](#update-now)). | **Replace the data and apply**, once you've read what it lists. | +| **vX is ready to apply** | Prepared and waiting: the maintenance window held it because it changes what CoderHelm's own roles may do, or auto-update was turned off before it ran. | **Apply update**. | | **vX is ready to apply** | The prepared update waits for an admin, for example because automatic updates were turned off before it ran. | **Apply vX**. | | **vX needs an AWS admin** | The update changes the deploy role or a permissions boundary, which CoderHelm can't apply for itself ([why](#what-an-update-does)). | **Open it in the AWS console**: someone with administrator rights reviews it and chooses **Execute**. | | **Applying vX…** / **Updating to vX…** | The update runs (10 to 20 minutes), with who started it and when. When someone executed it in the AWS console, it says so. Coderhelm keeps running your current version until it finishes. | Nothing. The page follows it. | @@ -147,7 +148,7 @@ Some releases need you to say yes first. When the prepared update would replace ### Installs on v0.8.28 to v0.8.38 -On these releases, **Review and apply** and **Apply vX** refuse every prepared update with "this update was prepared without the deploy role", even though the change set was made with it: the check read a field AWS never returns. v0.8.39 fixed it. To get onto v0.8.39 or newer once, when the page refuses: +On these releases, applying from the page (then called **Review and apply** and **Apply vX**) refused every prepared update with "this update was prepared without the deploy role", even though the change set was made with it: the check read a field AWS never returns. v0.8.39 fixed it. To get onto v0.8.39 or newer once, when the page refuses: 1. Open the link next to the update (**See the change in the AWS console**), or the stack `coderhelm-` in the [CloudFormation console](https://console.aws.amazon.com/cloudformation/home), then **Change sets**, then the newest one. 2. Check what it changes, and choose **Execute change set**. It runs through the deploy role it was made with. @@ -162,13 +163,15 @@ On an install made with Launch Stack, an update is a stack update of `coderhelm- 2. **Checks the models** the release calls ([the model check](#the-model-check)). 3. **Prepares the change set.** The updater downloads `coderhelm.json` from `https://coderhelm-public.s3.amazonaws.com/launch//`, where release files are written once and never replaced, and proposes it only if its sha256 matches the signed one. First the install helper copies the release's part templates into the install's own release bucket, each checked against the sha256 that verified `coderhelm.json` lists, so CloudFormation can read them while it prepares the parts' own change sets. Every parameter keeps its current value. After CloudFormation reads the template, the updater compares what it read with the verified one, and runs nothing if they differ. 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. When it would replace or remove data or change permissions, it waits for you to confirm exactly those changes on the page, then applies. + - **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**. - **It changes the deploy role or a permissions boundary:** the deploy role can't change those (that is what keeps it from giving itself more), so CoderHelm can't apply it for you. The page says so and links to the change set: someone with administrator rights in the AWS account reviews it and chooses **Execute**. Releases do this rarely, and their notes say so. 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. +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. + +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. ### The first update onto a release with the deploy role on every install diff --git a/lambda/tests/test_updater.py b/lambda/tests/test_updater.py index 158002e6f..0a84933ca 100644 --- a/lambda/tests/test_updater.py +++ b/lambda/tests/test_updater.py @@ -406,8 +406,10 @@ def test_tick_with_auto_update_on_starts_the_build_without_an_email(self): def test_update_now_and_finished_failure_marks_the_version(self): e = u.handle({"action": "update_now", "actor": "owner@example.org"}, self.env, self.store, SUNDAY_3AM, self.fetch) self.assertEqual((e["version"], e["actor"], e["status"]), ("v2.0.0", "owner@example.org", "running")) - with self.assertRaises(ValueError): - u.handle({"action": "update_now"}, self.env, self.store, SUNDAY_3AM, self.fetch) + # Pressed again while it runs: the same update, never a second one or an error. + again = u.handle({"action": "update_now"}, self.env, self.store, SUNDAY_3AM, self.fetch) + self.assertEqual((again["id"], again["state"]), (e["id"], "started")) + self.assertEqual(len(self.builds), 1) r = u.handle({"action": "finished", "status": "rolled_back", "reason": "health check failed after deploy", "history_id": e["id"]}, self.env, self.store, SUNDAY_3AM, self.fetch) self.assertEqual(r["status"], "rolled_back") @@ -845,9 +847,10 @@ def test_the_manifest_is_read_only_after_the_signature_check(self): self.assertEqual(d["action"], "notify") self.assertEqual(self.worker.payloads, []) self.assertTrue(self.store.get("MODEL_CHECK")["pending"]) - with self.assertRaises(u.ModelsBlocked) as e: - u.handle({"action": "update_now", "actor": "a"}, self.env, self.store, SUNDAY_3AM, self.releases, self.worker) - self.assertIn("signature", str(e.exception)) + # Update pressed while it runs: recorded, not refused. + r = u.handle({"action": "update_now", "actor": "a"}, self.env, self.store, SUNDAY_3AM, self.releases, self.worker) + self.assertEqual((r["state"], r["version"]), ("checking", "v1.1.0")) + self.assertTrue(r["model_check"]["pending"]) # Not started again within 30 minutes. self.assertEqual(self.builds, [("v1.1.0", "check", "release-check")]) # A report that isn't from the build the updater started is refused. @@ -946,6 +949,167 @@ def test_one_reminder_after_a_week_of_waiting_and_no_more(self): self.assertEqual(self.notices, ["update to v1.1.0 needs your OK", "update to v1.1.0 still needs your OK"]) +class PressDuringCheck(unittest.TestCase): + """Update pressed while the release check runs: recorded, then carried on by itself.""" + + def setUp(self): + self.db = FakeDynamo() + self.store = u.Store(self.db, "t") + self.builds, self.notices = [], [] + real_build, real_notify, real_check = u.start_build, u.notify, u.start_check + u.start_build = lambda env, version, actor, mode, hid, extra=None: self.builds.append((version, actor, mode)) or "b-1" + u.notify = lambda subject, text, env=None, **kw: self.notices.append(subject) or 1 + u.start_check = lambda env, version: self.checks.append(version) or f"c-{version}" + self.addCleanup(setattr, u, "start_build", real_build) + self.addCleanup(setattr, u, "notify", real_notify) + self.addCleanup(setattr, u, "start_check", real_check) + self.checks = [] + self.cb = FakeCodeBuild() + u._clients["codebuild"] = self.cb + self.addCleanup(u._clients.pop, "codebuild", None) + self.env = {"CODERHELM_VERSION": "v1.0.0", "APP_URL": "https://helm.example.org", "UPDATE_PROJECT_NAME": "p", + "RELEASE_CHECK_PROJECT_NAME": "coderhelm-prod-release-check", "WORKER_FUNCTION_NAME": "w", + "CONFIGURED_MODELS": "claude-opus-5-5,claude-sonnet-5-5"} + self.worker = FakeWorker(refuse=()) + self.tags = ["v1.1.0"] + + def releases(self, _repo): + return [rel(t) for t in self.tags] + + def h(self, event, at=SUNDAY_3AM): + return u.handle(event, self.env, self.store, at, self.releases, self.worker) + + def press(self, at=SUNDAY_3AM, **kw): + return self.h(dict({"action": "update_now", "actor": "admin@example.org"}, **kw), at) + + def verify(self, version="v1.1.0", at=SUNDAY_3AM, manifest=MANIFEST): + """The release check build reports, then CodeBuild says it succeeded.""" + text = json.dumps(dict(manifest, version=version)) + self.h({"action": "models_verified", "version": version, "build": f"c-{version}", "status": "verified", "manifest_text": text}, at) + self.cb.finish(f"c-{version}", version=version, models=hashlib.sha256(text.encode()).hexdigest()) + + def updates(self): + return [b for b in self.builds if b[2] == "update"] + + def test_a_press_while_checking_is_recorded_not_refused(self): + r = self.press() + self.assertEqual((r["state"], r["version"]), ("checking", "v1.1.0")) + self.assertTrue(r["model_check"]["pending"]) + self.assertEqual(r["request"]["actor"], "admin@example.org") + self.assertEqual(r["request"]["status"], "waiting") + self.assertEqual(self.updates(), []) + req = self.store.get("UPDATE_REQUEST") + self.assertEqual((req["version"], req["actor"], req["requested_at"]), ("v1.1.0", "admin@example.org", SUNDAY_3AM.isoformat())) + s = self.h({"action": "status"}) + self.assertEqual(s["update_request"]["status"], "waiting") + self.assertTrue(s["model_check"]["pending"]) + # The handler answers ok: the gateway never turns it into an error. + self.assertNotIn("error", r) + + def test_the_update_starts_by_itself_once_the_check_passes(self): + self.press() + self.verify() + self.assertEqual(self.updates(), []) # CodeBuild hasn't said yet + d = self.h({"action": "tick"}, SUNDAY_3AM + timedelta(minutes=5)) + self.assertEqual(self.updates(), [("v1.1.0", "admin@example.org", "update")]) + req = self.store.get("UPDATE_REQUEST") + self.assertEqual(req["status"], "started") + self.assertEqual(req["id"], self.store.get("UPDATE_STATE")["running_id"]) + self.assertEqual(d["reason"], "an update is running") + # Pressing again now is the same update, not a second one or an error. + again = self.press(SUNDAY_3AM + timedelta(minutes=6)) + self.assertEqual((again["state"], again["id"]), ("started", req["id"])) + self.assertEqual(len(self.updates()), 1) + + def test_status_carries_it_on_without_a_tick(self): + self.press() + self.verify() + s = self.h({"action": "status"}, SUNDAY_3AM + timedelta(minutes=3)) + self.assertEqual(self.updates(), [("v1.1.0", "admin@example.org", "update")]) + self.assertTrue(s["running"]) + self.assertEqual(s["update_request"]["status"], "started") + + def test_a_refused_model_ends_the_request_with_the_reason(self): + self.worker.refuse = {"claude-sonnet-5-5"} + self.press() + self.verify() + s = self.h({"action": "status"}, SUNDAY_3AM + timedelta(minutes=3)) + self.assertEqual(self.updates(), []) + self.assertEqual(s["update_request"]["status"], "ended") + self.assertTrue(s["update_request"]["reason"].startswith("Update to v1.1.0 needs your action")) + self.assertFalse(s["running"]) + + def test_a_failed_signature_check_ends_the_request_with_its_reason(self): + self.press() + self.h({"action": "models_verified", "version": "v1.1.0", "build": "c-v1.1.0", "status": "failed", "reason": "bad signature"}) + req = self.store.get("UPDATE_REQUEST") + self.assertEqual(req["status"], "ended") + self.assertIn("couldn't verify v1.1.0: bad signature", req["reason"]) + self.assertEqual(self.updates(), []) + + def test_a_check_that_never_ends_drops_the_request(self): + self.press() + later = SUNDAY_3AM + u.REQUEST_LIMIT + timedelta(minutes=1) + self.cb.builds["c-v1.1.0"] = {"buildStatus": "IN_PROGRESS"} + self.h({"action": "tick"}, later) + req = self.store.get("UPDATE_REQUEST") + self.assertEqual(req["status"], "ended") + self.assertIn("didn't finish", req["reason"]) + + def test_a_newer_press_replaces_the_waiting_one(self): + self.press() + self.tags = ["v1.1.0", "v1.2.0"] + r = self.press(SUNDAY_3AM + timedelta(minutes=1), version="v1.2.0") + self.assertEqual(r["state"], "checking") + req = self.store.get("UPDATE_REQUEST") + self.assertEqual((req["version"], req["replaces"]), ("v1.2.0", "v1.1.0")) + # The check now runs for v1.2.0, and that is what starts. + self.assertEqual(self.store.get("UPDATE_STATE")["verifying"]["version"], "v1.2.0") + self.verify("v1.2.0", SUNDAY_3AM + timedelta(minutes=2)) + self.h({"action": "status"}, SUNDAY_3AM + timedelta(minutes=3)) + self.assertEqual(self.updates(), [("v1.2.0", "admin@example.org", "update")]) + + def test_a_newer_release_replaces_the_waiting_request(self): + self.press() + self.tags = ["v1.1.0", "v1.2.0"] + s = self.h({"action": "status", "refresh": True}, SUNDAY_3AM + timedelta(minutes=1)) + self.assertEqual(s["latest"]["version"], "v1.2.0") + self.assertEqual(s["update_request"]["version"], "v1.2.0") + self.assertEqual(s["update_request"]["replaces"], "v1.1.0") + self.assertEqual(s["model_check"]["version"], "v1.2.0") + self.assertTrue(s["model_check"]["pending"]) + self.verify("v1.2.0", SUNDAY_3AM + timedelta(minutes=2)) + self.h({"action": "status"}, SUNDAY_3AM + timedelta(minutes=3)) + self.assertEqual(self.updates(), [("v1.2.0", "admin@example.org", "update")]) + + def test_a_press_after_the_check_passed_starts_at_once(self): + self.store.put("MANIFEST#v1.1.0", {"verified": True, "manifest": MANIFEST}) + r = self.press() + self.assertEqual(r["state"], "started") + self.assertEqual(self.updates(), [("v1.1.0", "admin@example.org", "update")]) + + def test_the_scheduled_window_is_unchanged_and_starts_once(self): + self.h({"action": "settings", "settings": {"auto": True, "day": "daily"}}) + # No press: the window waits for the check, then applies by itself. + d = self.h({"action": "tick"}) + self.assertEqual(d["action"], "notify") + self.assertEqual(self.updates(), []) + self.verify() + d = self.h({"action": "tick"}, SUNDAY_3AM + timedelta(minutes=5)) + self.assertEqual(d["action"], "update") + self.assertEqual(self.updates(), [("v1.1.0", "auto", "update")]) + self.assertIsNone(self.store.get("UPDATE_REQUEST")) + + def test_a_press_and_the_window_start_one_update(self): + self.h({"action": "settings", "settings": {"auto": True, "day": "daily"}}) + self.press() + self.verify() + self.h({"action": "tick"}, SUNDAY_3AM + timedelta(minutes=5)) + self.h({"action": "tick"}, SUNDAY_3AM + timedelta(minutes=6)) + self.assertEqual(len(self.updates()), 1) + self.assertEqual(self.updates()[0][1], "admin@example.org") + + class NeverAcceptsTerms(unittest.TestCase): """The updater only checks: no subscription, agreement or form is ever sent.""" diff --git a/lambda/tests/test_updater_native.py b/lambda/tests/test_updater_native.py index 359db948c..ae28d2907 100644 --- a/lambda/tests/test_updater_native.py +++ b/lambda/tests/test_updater_native.py @@ -758,10 +758,10 @@ def tearDown(self): u._clients.pop("cloudformation", None) u._clients.pop("lambda", None) - def prepare(self, actor="owner@example.org", scheduled=False, api=None, parent=None): + def prepare(self, actor="owner@example.org", scheduled=False, api=None, parent=None, consent=False): if api is not None: self.cfn.nested["nested-api"] = {"Changes": api} - u.begin(self.store, self.env, NOW, "v1.1.0", actor, "update", scheduled=scheduled) + u.begin(self.store, self.env, NOW, "v1.1.0", actor, "update", scheduled=scheduled, consent=consent) self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE"} if parent is not None: self.cfn.cs["Changes"] = parent @@ -875,6 +875,57 @@ def test_permission_changes_need_the_confirmation_too(self): self.apply() self.assertEqual(self.apply(confirm=p["confirm"])["status"], "running") + def test_an_update_press_that_agreed_to_permission_changes_applies_them_in_one_go(self): + role = [{"ResourceChange": {"Action": "Modify", "ResourceType": "AWS::IAM::Policy", "LogicalResourceId": "ServiceRoleDefaultPolicy"}}] + r = self.prepare(api=role, consent=True) + self.assertEqual(r["native"], "executing") + self.assertEqual(self.cfn.executed, ["arn:cs/1"]) + e = self.store.get(self.store.get("UPDATE_STATE")["running_id"]) + self.assertEqual(e["confirmed"]["by"], "owner@example.org") + self.assertEqual(e["confirmed"]["on"], "update") + self.assertIn("Api.ServiceRoleDefaultPolicy", e["confirmed"]["permission_changes"][0]) + + def test_the_press_never_agrees_to_data_changes(self): + data = [{"ResourceChange": {"Action": "Modify", "ResourceType": "AWS::DynamoDB::GlobalTable", "Replacement": "True", "LogicalResourceId": "Table"}}, + {"ResourceChange": {"Action": "Add", "ResourceType": "AWS::IAM::Role", "LogicalResourceId": "NewRole"}}] + r = self.prepare(api=data, consent=True) + self.assertEqual(r["native"], "review") + self.assertEqual(self.cfn.executed, []) + p = self.pending() + self.assertIn("would replace or remove", p["hold"]) + with self.assertRaisesRegex(ValueError, "confirm the changes"): + self.apply() + self.assertEqual(self.apply(confirm=p["confirm"])["status"], "running") + + def test_the_press_never_agrees_to_a_role_or_boundary_change(self): + r = self.prepare(parent=[{"ResourceChange": {"Action": "Modify", "LogicalResourceId": "DeployBoundary", "ResourceType": "AWS::IAM::ManagedPolicy"}}], consent=True) + self.assertEqual(r["native"], "review") + self.assertEqual(self.cfn.executed, []) + self.assertFalse(self.pending()["can_apply"]) + + def test_the_window_never_carries_a_press_consent(self): + self.store.put("AUTO_UPDATE", {"auto": True}) + r = self.prepare(actor="auto", scheduled=True, consent=True, + api=[{"ResourceChange": {"Action": "Add", "ResourceType": "AWS::IAM::Role", "LogicalResourceId": "NewRole"}}]) + self.assertEqual(r["native"], "review") + self.assertEqual(self.cfn.executed, []) + self.assertIn("auto-update held: it changes permissions", self.pending()["hold"]) + + def test_update_now_passes_the_press_consent_on(self): + calls = [] + orig = u.begin + u.begin = lambda *a, **k: calls.append(k) or {"id": "UPDATE#x", "version": "v1.1.0"} + orig_mc = u.model_check + u.model_check = lambda *a, **k: {"version": "v1.1.0", "ok": True, "results": []} + try: + u.handle({"action": "update_now", "version": "v1.1.0", "actor": "owner@example.org", "accept_permissions": True}, + self.env, self.store, NOW, fetch=lambda repo: []) + u.handle({"action": "update_now", "version": "v1.1.0", "actor": "owner@example.org"}, + self.env, self.store, NOW, fetch=lambda repo: []) + finally: + u.begin, u.model_check = orig, orig_mc + self.assertEqual([c.get("consent") for c in calls], [True, False]) + def test_a_confirmation_for_another_prepared_update_is_refused(self): self.prepare(api=[{"ResourceChange": {"Action": "Add", "ResourceType": "AWS::IAM::Role", "LogicalResourceId": "NewRole"}}]) p = self.pending() diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index 996ce5888..78bddb63d 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -19,7 +19,10 @@ - update_now starts the update build for a version (default: the latest, read from GitHub at that moment). Only a version newer than the one running: going back is a - rollback. + rollback. Pressed while the release check runs, the press is + recorded and the update starts by itself once the check passes + (follow_request); pressed again for the update in progress, it + answers with that update. - rollback starts the build for the version before the last update, or an admin's pick, which must be a version this install ran before. - apply_update a native install: an admin applies the prepared update that @@ -1587,6 +1590,8 @@ def confirm_check(store, env, now, probe=None, cb=None): "build": v["build"], "at": now.isoformat()}) mc = model_check(store, env, now, version, env.get("RELEASE_REPO", RELEASE_REPO), probe or invoke_worker) notify_blocked(store, env, mc) + # An admin pressed Update while this ran: it carries on now. + follow_request(store, env, now, probe, record=mc) return "verified" @@ -1791,6 +1796,116 @@ def blocked_message(record): return f"Update to {record['version']} needs your action: {f.get('detail', 'a model was refused.')} {f.get('fix', '')}".strip() +# ── Update pressed while the release check runs ────────────────────────── +# +# Pressing Update while the release's signature and models are still being +# checked is never a refusal: the press is recorded (UPDATE_REQUEST: who, +# which version, when) and the updater carries on by itself once the check +# ends, exactly as if the admin pressed again: it prepares the update (begin) +# and the update then applies or waits for their OK as usual. A check that +# fails ends the request with the check's own reason, which the card shows. +# Another press, or a newer release, replaces the request. A request that +# never sees its check end is dropped after REQUEST_LIMIT. +# +# status: waiting (the check runs, or the release is still publishing), +# started (begin ran: `id` is the update), ended (`reason` says why), or done +# (the install already runs that version). + +REQUEST_LIMIT = timedelta(hours=2) + + +def record_request(store, now, version, actor, skip_check=False, waiting_for="the release check", consent=False): + """Records an admin's Update press that waits for the release check.""" + old = store.get("UPDATE_REQUEST") or {} + req = {"version": version, "actor": actor, "requested_at": now.isoformat(), "status": "waiting", "waiting_for": waiting_for} + if skip_check: + req["skip_check"] = True + if consent: + req["accept_permissions"] = True + if old.get("status") == "waiting" and old.get("version") != version: + req["replaces"] = old.get("version") + store.put("UPDATE_REQUEST", req) + return req + + +def settle_request(store, req, now, status, reason="", **extra): + req = dict(req, status=status, reason=reason, ended_at=now.isoformat(), **extra) + store.put("UPDATE_REQUEST", req) + return req + + +def follow_request(store, env, now, probe=None, latest=None, record=None): + """Carries a waiting Update press on: once its release check passed, the + update starts as if the admin pressed again; a check that failed ends it + with the check's reason. `latest` (the newest release offered) replaces + the request's version when it is newer. `record` is the model check as + the version route sees it (a stalled view). Returns the request, or None.""" + req = store.get("UPDATE_REQUEST") + if not req or req.get("status") != "waiting": + return req or None + version = req.get("version") or "" + current = env.get("CODERHELM_VERSION", "") + if not parse_version(version): + return settle_request(store, req, now, "ended", "the requested version isn't a release") + if parse_version(current) and compare(version, current) <= 0: + return settle_request(store, req, now, "done", f"this install already runs {current}") + if latest and parse_version(latest) and compare(latest, version) > 0: + # A newer release came out while this one was checked: Update means the newest. + req = record_request(store, now, latest, req.get("actor") or DIRECT_ACTOR, req.get("skip_check", False), + consent=req.get("accept_permissions", False)) + version = latest + record = model_check(store, env, now, version, env.get("RELEASE_REPO", RELEASE_REPO), probe or invoke_worker) + state = store.get("UPDATE_STATE", {}) or {} + if running(state, now): + live = (store.get(state["running_id"], {}) or {}) if state.get("running_id") else {} + if live.get("version") == version: + # The window (or another press) started this very update. + return settle_request(store, req, now, "started", id=state.get("running_id")) + if not (is_native(env) and unapplied(live)): + return req # another update runs: this one waits for it + mc = record if record and record.get("version") == version else (store.get("MODEL_CHECK") or {}) + if mc.get("version") != version or mc.get("pending"): + try: + old = now - datetime.fromisoformat(req.get("requested_at") or "") > REQUEST_LIMIT + except ValueError: + old = True + if old: + return settle_request(store, req, now, "ended", f"checking {version} didn't finish; press Update to start it over") + return req + if mc.get("stalled"): + return settle_request(store, req, now, "ended", mc.get("note") or f"checking {version} didn't finish") + if failures(mc, required=True): + return settle_request(store, req, now, "ended", blocked_message(mc)) + note = None + if failures(mc): + if not req.get("skip_check"): + return settle_request(store, req, now, "ended", blocked_message(mc) + " This release doesn't call it, so you can skip this check.") + note = "model check skipped for " + ", ".join(f.get("model", "?") for f in failures(mc)) + try: + started = begin(store, env, now, version, req.get("actor") or DIRECT_ACTOR, "update", note=note, + consent=req.get("accept_permissions", False)) + except ReleaseNotReady as e: + req = dict(req, waiting_for=str(e)) + store.put("UPDATE_REQUEST", req) + return req + except ValueError as e: + return settle_request(store, req, now, "ended", str(e)[:500]) + return settle_request(store, req, now, "started", id=started.get("id")) + + +def request_view(req, now): + """The Update press for the version route: while it waits, and for a day after it ended.""" + if not req or req.get("status") in ("done", None): + return None + if req.get("status") != "waiting": + try: + if now - datetime.fromisoformat(req.get("ended_at") or "") > timedelta(days=1): + return None + except ValueError: + return None + return {k: req.get(k) for k in ("version", "actor", "requested_at", "status", "waiting_for", "reason", "ended_at", "id", "replaces") if req.get(k) is not None} + + # ── The deploy window (hardened installs) ──────────────────────────────── WINDOW_POLICY_NAME = "deploy-window" @@ -2431,6 +2546,11 @@ def keep(e): return {"native": "moved on"} cfn.execute_change_set(ChangeSetName=cs_id, StackName=env["NATIVE_STACK"]) entry.update({"executed_at": now.isoformat(), "status": "running"}) + if entry.get("permission_changes") and consented(entry): + # What the press agreed to, as it turned out: kept with the update. + c = entry["consent"] + entry["confirmed"] = {"by": c.get("by"), "at": c.get("at"), "data_changes": [], + "permission_changes": entry["permission_changes"], "on": "update"} store.put(hid, entry) return {"native": "executing"} if entry.get("status") != "review": @@ -2511,7 +2631,7 @@ def native_hold(store, env, entry): if entry.get("data_changes"): # Never without a person: data would be replaced or removed. return f"{who}: it would replace or remove " + "; ".join(entry["data_changes"])[:400] - if entry.get("permission_changes"): + if entry.get("permission_changes") and not consented(entry): # Never without a person: it changes who may do what. return f"{who}: it changes permissions (" + "; ".join(entry["permission_changes"])[:400] + ")" if entry.get("scheduled") and not auto_on(store, env): @@ -2519,6 +2639,14 @@ def native_hold(store, env, entry): return "" +def consented(entry): + """An admin's Update press (never the window) agreed to permission changes + of CoderHelm's own roles. They stay inside the permissions boundary; the + deploy role and the boundary themselves are admin_changes, never applied here.""" + c = entry.get("consent") or {} + return bool(c.get("permissions")) and not entry.get("scheduled") + + def prepared_role(entry): """The deploy role this update's change set was made with ("" when none). DescribeChangeSet doesn't return it, so prepare records it on the entry. @@ -2805,7 +2933,7 @@ def not_started_details(e, version, from_version): return {k: d[k][:1000] for k in ("summary", "fix", "technical")} -def begin(store, env, now, version, actor, mode, extra=None, note=None, scheduled=False): +def begin(store, env, now, version, actor, mode, extra=None, note=None, scheduled=False, consent=False): """Starts the update and records it in history. History holds updates that started: the row is written once the change @@ -2831,6 +2959,11 @@ def begin(store, env, now, version, actor, mode, extra=None, note=None, schedule if scheduled: # The maintenance window started it: it applies only while auto-update is on. entry["scheduled"] = True + elif consent: + # The admin pressed Update next to "it may change what CoderHelm's own + # roles may do, inside the install's permissions boundary": that press + # is their OK for permission changes (see native_hold). Never for data. + entry["consent"] = {"permissions": True, "by": actor, "at": now.isoformat()} def refused(e): entry.update({"status": "not_started", "reason": not_started_reason(e), "finished_at": now.isoformat()}) @@ -2934,6 +3067,11 @@ def releases(max_age, refresh=False): # Opening Settings, System reads the list again when it is a couple # of minutes old; Check for updates (refresh) reads it now. _, latest, behind = releases(0, refresh=True) if event.get("refresh") else releases(FRESH_SECONDS) + mc_view = model_check_view(store, env, now, latest["version"], probe) if latest else None + # An Update press that waited for the check carries on (or ends) here too. + follow_request(store, env, now, probe, latest=latest["version"] if latest else None, record=mc_view) + if (store.get("UPDATE_REQUEST") or {}).get("version") != (mc_view or {}).get("version") and latest: + mc_view = model_check_view(store, env, now, latest["version"], probe) if is_native(env): # The pending update as CloudFormation has it now, not as last stored. reconcile(store, env, now) @@ -2955,7 +3093,9 @@ def releases(max_age, refresh=False): "failed_versions": sorted(state.get("failed_versions") or []), "history": history_view(store.history(), state, now), # The model check for the latest release (Settings, System and Setup). - "model_check": model_check_view(store, env, now, latest["version"], probe) if latest else None, + "model_check": mc_view, + # An admin's Update press waiting for the release check (or how it ended). + "update_request": request_view(store.get("UPDATE_REQUEST"), now), # Which install this is, for Settings, System, Uninstall's link to the uninstall page. "install": install_identity(env), # A native install: the stack, and the change set an admin reviews. @@ -2987,11 +3127,21 @@ def releases(max_age, refresh=False): # Forward only: an older (or the same) release is a rollback. if parse_version(current) and compare(version, current) <= 0: raise ValueError(f"{version} is not newer than {current}; use Roll back to go to an earlier release") + actor = event.get("actor") or DIRECT_ACTOR if running(state, now): - raise ValueError("an update is already running") + live = (store.get(state["running_id"], {}) or {}) if state.get("running_id") else {} + if live.get("version") == version and live.get("status") in ("running", "preparing", "review"): + # Pressed again (a second click, or a waiting press already + # started it): the update in progress is the answer. + return dict(live, id=state["running_id"], state="started") + if not (is_native(env) and unapplied(live)): + raise ValueError(f"the update to {live.get('version') or 'another version'} is still running; this one can start once it finishes") mc = model_check(store, env, now, version, repo, probe) if mc.get("pending"): - raise ModelsBlocked(f"Checking {version}'s signature and the models it calls first; try Update now again in a few minutes.", mc) + # Not a refusal: the press is kept, and the update starts by + # itself once the check passes (follow_request). + req = record_request(store, now, version, actor, bool(event.get("skip_check")), consent=bool(event.get("accept_permissions"))) + return {"state": "checking", "version": version, "request": request_view(req, now), "model_check": mc} if failures(mc, required=True): # No override: the release would call a model this install can't. raise ModelsBlocked(blocked_message(mc), mc) @@ -3001,12 +3151,22 @@ def releases(max_age, refresh=False): raise ModelsBlocked(blocked_message(mc) + " This release doesn't call it, so you can skip this check.", dict(mc, skippable=True)) note = "model check skipped for " + ", ".join(f.get("model", "?") for f in failures(mc)) - started = begin(store, env, now, version, event.get("actor") or DIRECT_ACTOR, "update", note=note) + try: + started = begin(store, env, now, version, actor, "update", note=note, consent=bool(event.get("accept_permissions"))) + except ReleaseNotReady as e: + # Still publishing, or its template not verified yet: a wait, kept like a check. + req = record_request(store, now, version, actor, bool(event.get("skip_check")), waiting_for=str(e), + consent=bool(event.get("accept_permissions"))) + return {"state": "checking", "version": version, "request": request_view(req, now), "model_check": mc} + req = store.get("UPDATE_REQUEST") or {} + if req.get("status") == "waiting": + # This press replaces the one that waited. + settle_request(store, req, now, "started", id=started.get("id")) stored = store.get("MODEL_CHECK") or {} if stored.get("version") == version and (stored.get("pending") or stored.get("stalled")): # Written meanwhile by an older check: the one that just passed stands. store.put("MODEL_CHECK", mc) - return started + return dict(started, state="started") if action == "models_verified": # From the release check build, after the signature check. Only a @@ -3028,6 +3188,7 @@ def releases(max_age, refresh=False): mc.update(pending=False, stalled=True, ok=False, checked_at=now.isoformat(), note=f"The release check couldn't verify {version}: {why}. Check again to start it over.") store.put("MODEL_CHECK", mc) + follow_request(store, env, now, probe, record=mc) return {"verified": False} sha = event.get("template_sha256") if sha is not None and not (isinstance(sha, str) and re.fullmatch(r"[0-9a-f]{64}", sha)): @@ -3057,7 +3218,9 @@ def releases(max_age, refresh=False): if not latest: return {"model_check": None} version = latest["version"] - return {"model_check": model_check(store, env, now, version, repo, probe)} + mc = model_check(store, env, now, version, repo, probe) + follow_request(store, env, now, probe, record=mc) + return {"model_check": mc, "request": request_view(store.get("UPDATE_REQUEST"), now)} if action == "rollback": target = event.get("version") @@ -3155,6 +3318,11 @@ def releases(max_age, refresh=False): if latest and not running(state, now) and needs_check(mc, latest["version"], now): mc = model_check(store, env, now, latest["version"], repo, probe) notify_blocked(store, env, mc) + if not behind: + # An Update press that waited for the check carries on. + follow_request(store, env, now, probe, latest=latest["version"] if latest else None) + state = store.get("UPDATE_STATE", {}) + mc = store.get("MODEL_CHECK") if behind: # Never an older release while a newer one is out. d = {"action": "none", "version": behind["version"], "reason": behind["reason"]} diff --git a/selfhost/versions.json b/selfhost/versions.json index db73b6e84..ca599b32d 100644 --- a/selfhost/versions.json +++ b/selfhost/versions.json @@ -1,4 +1,4 @@ { "about": "The dashboard commit each platform release ships: a full 40-character commit SHA of CoderHelm/coderhelm, never a branch or tag (scripts/check-dashboard-ref.mjs fails CI and the release otherwise). The release workflow builds exactly this commit (dashboard/) into dashboard.tar.gz. Move it with scripts/bump-dashboard.sh in a reviewed PR, in the same PR as any API change the dashboard needs.", - "dashboardRef": "8434a36b91d88b770f7757bee913f683e08b93f2" + "dashboardRef": "3f185a6a374c7b4b7f303549c3f6db37533b6674" } diff --git a/services/gateway/src/routes/setup_checks.rs b/services/gateway/src/routes/setup_checks.rs index 5a23f715b..7d53bb36f 100644 --- a/services/gateway/src/routes/setup_checks.rs +++ b/services/gateway/src/routes/setup_checks.rs @@ -1397,33 +1397,13 @@ pub fn update_models(status: Option<&Value>) -> Option { .map(|r| r.iter().filter(|x| x["status"] == "fail").collect()) .unwrap_or_default(); let label = "The next release's models answer"; - if mc["pending"].as_bool() == Some(true) { - return Some(Check::not_ok( - Status::Warn, - "update_models", - M, - label, - format!("Checking {version}'s signature before reading the models it calls."), - "The update waits until every model it calls answers.", - Fix::text("Wait a few minutes, then check again.").href("/settings/system#readiness"), - )); - } - if mc["stalled"].as_bool() == Some(true) { - // The release check stopped reporting (or couldn't verify the - // release): it holds the update, and says so, never "Checking". - return Some(Check::not_ok( - Status::Warn, - "update_models", - M, - label, - mc["note"] - .as_str() - .map(str::to_string) - .unwrap_or_else(|| format!("Checking {version} didn't finish.")), - "The update waits until the release is verified and every model it calls answers.", - Fix::text("Check again to start the release check over.") - .href("/settings/system#version"), - )); + // A release check that runs, or that stopped without an answer, is the + // update's own state (the Version card: "Checking vX before it can be + // applied", or "didn't finish" with Check again), not a problem with the + // install: no check here, never a warning. The preflight still holds the + // update for it. + if mc["pending"].as_bool() == Some(true) || mc["stalled"].as_bool() == Some(true) { + return None; } if mc["ok"].as_bool() == Some(true) || failing.is_empty() { return Some(Check::pass( @@ -3044,9 +3024,10 @@ mod tests { let ok = json!({"model_check": {"version": "v1.3.0", "ok": true, "results": []}}); assert_eq!(update_models(Some(&ok)).unwrap().status, Status::Pass); assert!(update_models(Some(&json!({}))).is_none()); - // Before the release's signature is checked: held, not refused. + // Before the release's signature is checked: held, not refused, and + // the update card's state only: no install check, never a warning. let pending = json!({"model_check": {"version": "v1.3.0", "ok": false, "pending": true, "results": []}}); - assert_eq!(update_models(Some(&pending)).unwrap().status, Status::Warn); + assert!(update_models(Some(&pending)).is_none()); let b = preflight(&[], Some(&pending)); assert_eq!( (b[0].key.as_str(), b[0].severity), @@ -3056,10 +3037,7 @@ mod tests { // A release check that stopped reporting: held, with its reason, never "Checking". let stalled = json!({"model_check": {"version": "v1.3.0", "ok": false, "pending": false, "stalled": true, "results": [], "note": "Checking v1.3.0 didn't finish: the release check build ended FAILED without reporting back. Check again to start it over."}}); - let c = update_models(Some(&stalled)).unwrap(); - assert_eq!(c.status, Status::Warn); - assert!(c.detail.contains("ended FAILED")); - assert!(!c.detail.contains("signature")); + assert!(update_models(Some(&stalled)).is_none()); let b = preflight(&[], Some(&stalled)); assert_eq!(b.len(), 1); assert_eq!( diff --git a/services/gateway/src/routes/system.rs b/services/gateway/src/routes/system.rs index 80506d185..fa541a3c9 100644 --- a/services/gateway/src/routes/system.rs +++ b/services/gateway/src/routes/system.rs @@ -77,16 +77,27 @@ pub(crate) async fn call(state: &AppState, payload: Value) -> Result Result, (StatusCode, Json)> { if body.get("ok").and_then(Value::as_bool) == Some(false) { let msg = body.get("error").cloned().unwrap_or(json!("refused")); let mut out = json!({ "error": msg }); + let mut code = StatusCode::BAD_REQUEST; if let Some(m) = body.get("model_check").filter(|m| !m.is_null()) { out["model_check"] = m.clone(); + code = StatusCode::CONFLICT; } - return Err((StatusCode::BAD_REQUEST, Json(out))); + if body.get("waiting").and_then(Value::as_bool) == Some(true) { + out["waiting"] = json!(true); + code = StatusCode::CONFLICT; + } + return Err((code, Json(out))); } Ok(Json(body)) } @@ -198,9 +209,11 @@ pub async fn set_uninstall_mode( } /// POST /api/system/update: update to `version` (default: the latest). -/// The updater checks every model the release calls first and refuses -/// while one is refused; `skip_check` passes only a failure on a model the -/// release doesn't call. +/// The updater checks every model the release calls first. Pressed while +/// that check runs, the press is recorded (`state: "checking"`) and the +/// update starts by itself once the check passes; a model the release calls +/// that is refused answers 409 with the check. `skip_check` passes only a +/// failure on a model the release doesn't call. pub async fn update_now( State(state): State>, Extension(claims): Extension, @@ -213,9 +226,13 @@ pub async fn update_now( .and_then(Value::as_str) .map(str::to_string); let skip = body.get("skip_check").and_then(Value::as_bool) == Some(true); + // The admin pressed Update next to "it may change what Coderhelm's own + // roles may do": their OK for permission changes inside the boundary, + // never for data (lambda/updater, consented). + let accept = body.get("accept_permissions").and_then(Value::as_bool) == Some(true); let body = call( &state, - json!({ "action": "update_now", "version": version, "actor": claims.email, "skip_check": skip }), + json!({ "action": "update_now", "version": version, "actor": claims.email, "skip_check": skip, "accept_permissions": accept }), ) .await .map_err(status_only)?; @@ -554,11 +571,31 @@ mod tests { let r = answer( json!({"ok": false, "error": "Update to v1.3.0 needs your action", "model_check": {"version": "v1.3.0", "ok": false}}), ); - let (_, body) = r.unwrap_err(); + let (code, body) = r.unwrap_err(); + assert_eq!(code, StatusCode::CONFLICT); assert_eq!(body.0["model_check"]["version"], "v1.3.0"); assert!(answer(json!({"ok": true, "version": "v1.2.0"})).is_ok()); } + #[test] + fn update_pressed_while_the_check_runs_is_a_200_with_its_state() { + let r = answer(json!({ + "ok": true, "state": "checking", "version": "v1.3.0", + "request": {"version": "v1.3.0", "actor": "admin@acme.example", "status": "waiting"}, + "model_check": {"version": "v1.3.0", "pending": true, "ok": false, "results": []} + })) + .expect("a recorded press is not an error"); + assert_eq!(r.0["state"], "checking"); + assert_eq!(r.0["request"]["status"], "waiting"); + // A release still publishing: the state, as a 409 the card shows. + let (code, body) = answer( + json!({"ok": false, "error": "v1.3.0 is still publishing; try again in a minute", "waiting": true}), + ) + .unwrap_err(); + assert_eq!(code, StatusCode::CONFLICT); + assert_eq!(body.0["waiting"], true); + } + fn claims(role: &str) -> Claims { Claims { sub: "USER#acme-admin".into(),