From 5f360ee4471e7bf4a779f53e478a47f3dc5fdb81 Mon Sep 17 00:00:00 2001 From: jparker2006 <85816763+jparker2006@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:34:02 +0000 Subject: [PATCH 1/3] #3235: red: actions token-service workflow, helper and contract proofs --- .../fixtures/token-service/fallback.json | 58 +++++ .../fixtures/token-service/test_fixtures.py | 22 +- docs/evidence/3235/red-run.txt | 223 ++++++++++++++++ tools/github-app/test_agent_token.py | 223 ++++++++++++++++ tools/github-app/test_mint_workflow.py | 238 ++++++++++++++++++ 5 files changed, 761 insertions(+), 3 deletions(-) create mode 100644 docs/evidence/3235/red-run.txt create mode 100644 tools/github-app/test_mint_workflow.py diff --git a/contracts/fixtures/token-service/fallback.json b/contracts/fixtures/token-service/fallback.json index 555fbc88c..c468dbbbf 100644 --- a/contracts/fixtures/token-service/fallback.json +++ b/contracts/fixtures/token-service/fallback.json @@ -328,6 +328,64 @@ }, "stderr": "openwiz: no openwiz[bot] token (unreachable); using the owner's GitHub account\n" } + }, + { + "name": "a good answer over the actions route", + "service": "answer", + "token": "synthetic-write-token", + "call": { + "exit": 0, + "stdout": "" + }, + "out": { + "gh": "openwiz[bot]", + "git": "openwiz[bot]", + "token_file": "synthetic-write-token", + "env": { + "OPENWIZ_TOKEN_SERVICE_ROUTE": "actions", + "OPENWIZ_TOKEN_SERVICE_REPOSITORY": "synthetic-owner/private-ops", + "GH_TOKEN": "synthetic-write-token" + }, + "stderr": "" + } + }, + { + "name": "an actions run that times out after 120 seconds", + "service": "unreachable", + "reason": "unreachable", + "call": { + "exit": null, + "timeout": true + }, + "out": { + "gh": "owner", + "git": "owner", + "token_file": null, + "env": { + "OPENWIZ_TOKEN_SERVICE_ROUTE": "actions", + "OPENWIZ_TOKEN_SERVICE_REPOSITORY": "synthetic-owner/private-ops" + }, + "stderr": "openwiz: no openwiz[bot] token (unreachable); using the owner's GitHub account\n" + } + }, + { + "name": "an actions artifact that is tampered or cannot be opened", + "service": "bad-answer", + "reason": "bad-answer", + "call": { + "exit": 0, + "stdout": "" + }, + "out": { + "gh": "owner", + "git": "owner", + "token_file": null, + "env": { + "OPENWIZ_TOKEN_SERVICE_ROUTE": "actions", + "OPENWIZ_TOKEN_SERVICE_REPOSITORY": "synthetic-owner/private-ops" + }, + "stderr": "openwiz: no openwiz[bot] token (bad-answer); using the owner's GitHub account\n" + } } ] } diff --git a/contracts/fixtures/token-service/test_fixtures.py b/contracts/fixtures/token-service/test_fixtures.py index 0e2ac8395..8514a2811 100644 --- a/contracts/fixtures/token-service/test_fixtures.py +++ b/contracts/fixtures/token-service/test_fixtures.py @@ -166,20 +166,36 @@ def test_the_app_profile_and_token_guards_are_the_identity_contracts(self): def test_the_key_stays_on_the_owners_machine(self): # catches: a contract that lets the key travel or lets an agent ask for it. key = self.pin["key"] - self.assertEqual(key["lives"], "owner's machine only") + self.assertEqual( + key["lives"], + "the owner's machine (pairing and local), or the token-service environment secret of the owner's private repository (actions)", + ) self.assertEqual(key["path"], "/service/app/private-key.pem") self.assertEqual((key["file_mode"], key["directory_mode"]), ("0600", "0700")) self.assertEqual(key["agents"], "never ask for, read, copy or hold it") self.assertEqual(key["leaves_the_machine"], False) + self.assertEqual(key.get("actions_environment"), { + "name": "token-service", + "secret": "OPENWIZ_GITHUB_APP_KEY", + "deployment_branches": "main only", + "trigger": "workflow_dispatch only", + "ref": "refs/heads/main", + "delivery": "pipe or descriptor, never a file", + }) def test_the_service_has_no_port_and_takes_the_request_on_stdin(self): # catches: a reach route that opens a port or puts anything on a command line. reach = self.pin["reach"] self.assertEqual(reach["listens"], "no port") self.assertEqual(reach["request"], "stdin") - for argv in reach["routes"].values(): - self.assertNotIn("token", " ".join(argv).lower()) + for route_name, argv in reach["routes"].items(): + if isinstance(argv, list): + self.assertNotIn("token", " ".join(argv).lower(), route_name) self.assertEqual(reach["routes"]["pairing"][:4], ["room-cli", "mac", "run", "--stdin"]) + self.assertIn("actions", reach["routes"]) + self.assertEqual(reach.get("actions_timeout_s"), 120) + self.assertIn("actions", reach["configuration"]["OPENWIZ_TOKEN_SERVICE_ROUTE"]) + self.assertIn("OPENWIZ_TOKEN_SERVICE_REPOSITORY", reach["configuration"]) # catches: a pairing route that lets the token rest in a pairing log or result record. crossing = reach.get("token_crossing", {}) self.assertEqual(crossing.get("never"), ["command line", "terminal", "log", "record"]) diff --git a/docs/evidence/3235/red-run.txt b/docs/evidence/3235/red-run.txt new file mode 100644 index 000000000..53f2a5d02 --- /dev/null +++ b/docs/evidence/3235/red-run.txt @@ -0,0 +1,223 @@ +=== test_mint_workflow.py === +test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields (__main__.MintWorkflowExecution.test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields) ... FAIL +test_template_guard_catches_every_planted_violation (__main__.MintWorkflowTemplate.test_template_guard_catches_every_planted_violation) ... FAIL +test_template_passes_all_security_guards (__main__.MintWorkflowTemplate.test_template_passes_all_security_guards) ... FAIL + +====================================================================== +FAIL: test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields (__main__.MintWorkflowExecution.test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_mint_workflow.py", line 165, in test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields + self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") +AssertionError: False is not true : tools/github-app/mint-workflow.yml is missing + +====================================================================== +FAIL: test_template_guard_catches_every_planted_violation (__main__.MintWorkflowTemplate.test_template_guard_catches_every_planted_violation) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_mint_workflow.py", line 144, in test_template_guard_catches_every_planted_violation + self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") +AssertionError: False is not true : tools/github-app/mint-workflow.yml is missing + +====================================================================== +FAIL: test_template_passes_all_security_guards (__main__.MintWorkflowTemplate.test_template_passes_all_security_guards) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_mint_workflow.py", line 138, in test_template_passes_all_security_guards + self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") +AssertionError: False is not true : tools/github-app/mint-workflow.yml is missing + +---------------------------------------------------------------------- +Ran 3 tests in 0.001s + +FAILED (failures=3) + +=== test_agent_token.py ActionsRoute === +test_actions_backs_off_on_403_and_429 (__main__.ActionsRoute.test_actions_backs_off_on_403_and_429) ... ERROR +test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) ... + test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [missing-run] ... ERROR + test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [timeout] ... ERROR + test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [failed-run] ... ERROR + test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [missing-artifact] ... ERROR + test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [tampered-zip] ... ERROR + test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [tampered-body] ... ERROR + test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [unopenable] ... ERROR + test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [refusal] ... ERROR +test_actions_never_exposes_plaintext_token (__main__.ActionsRoute.test_actions_never_exposes_plaintext_token) ... ok +test_actions_round_trip_and_deletes_artifact (__main__.ActionsRoute.test_actions_round_trip_and_deletes_artifact) ... openwiz: no openwiz[bot] token (unreachable); using the owner's GitHub account +FAIL + +====================================================================== +ERROR: test_actions_backs_off_on_403_and_429 (__main__.ActionsRoute.test_actions_backs_off_on_403_and_429) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2572, in test_actions_backs_off_on_403_and_429 + with mock.patch.object(self.helper, "ACTIONS_POLL_S", 0.01): + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_POLL_S' + +====================================================================== +ERROR: test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [missing-run] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2558, in test_actions_failures_fall_back_with_right_reason + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_TIMEOUT_S' + +====================================================================== +ERROR: test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [timeout] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2558, in test_actions_failures_fall_back_with_right_reason + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_TIMEOUT_S' + +====================================================================== +ERROR: test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [failed-run] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2558, in test_actions_failures_fall_back_with_right_reason + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_TIMEOUT_S' + +====================================================================== +ERROR: test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [missing-artifact] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2558, in test_actions_failures_fall_back_with_right_reason + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_TIMEOUT_S' + +====================================================================== +ERROR: test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [tampered-zip] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2558, in test_actions_failures_fall_back_with_right_reason + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_TIMEOUT_S' + +====================================================================== +ERROR: test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [tampered-body] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2558, in test_actions_failures_fall_back_with_right_reason + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_TIMEOUT_S' + +====================================================================== +ERROR: test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [unopenable] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2558, in test_actions_failures_fall_back_with_right_reason + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_TIMEOUT_S' + +====================================================================== +ERROR: test_actions_failures_fall_back_with_right_reason (__main__.ActionsRoute.test_actions_failures_fall_back_with_right_reason) [refusal] +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2558, in test_actions_failures_fall_back_with_right_reason + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + File "/usr/lib/python3.11/unittest/mock.py", line 1437, in __enter__ + original, local = self.get_original() + ^^^^^^^^^^^^^^^^^^^ + File "/usr/lib/python3.11/unittest/mock.py", line 1410, in get_original + raise AttributeError( +AttributeError: does not have the attribute 'ACTIONS_TIMEOUT_S' + +====================================================================== +FAIL: test_actions_round_trip_and_deletes_artifact (__main__.ActionsRoute.test_actions_round_trip_and_deletes_artifact) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/tools/github-app/test_agent_token.py", line 2532, in test_actions_round_trip_and_deletes_artifact + self.assertEqual(token, TOKEN) +AssertionError: None != 'synthetic-agent-token-1' + +---------------------------------------------------------------------- +Ran 4 tests in 5.543s + +FAILED (failures=1, errors=9) + +=== test_fixtures.py === +test_every_invalid_message_fails_the_schema (__main__.Invalid.test_every_invalid_message_fails_the_schema) ... ok +test_a_token_appears_only_in_its_private_places (__main__.NeverExposed.test_a_token_appears_only_in_its_private_places) ... ok +test_no_credential_or_real_id_in_the_contract_schema_or_fixtures (__main__.NeverExposed.test_no_credential_or_real_id_in_the_contract_schema_or_fixtures) ... ok +test_the_leak_check_catches_a_wrapped_token (__main__.NeverExposed.test_the_leak_check_catches_a_wrapped_token) ... ok +test_the_scan_catches_what_it_claims (__main__.NeverExposed.test_the_scan_catches_what_it_claims) ... ok +test_a_fallback_leaves_no_service_credential_for_gh_or_git (__main__.RefreshAndFallback.test_a_fallback_leaves_no_service_credential_for_gh_or_git) ... ok +test_a_token_is_refreshed_at_or_under_five_minutes_left (__main__.RefreshAndFallback.test_a_token_is_refreshed_at_or_under_five_minutes_left) ... ok +test_the_fallback_says_so_once_and_not_configured_is_silent (__main__.RefreshAndFallback.test_the_fallback_says_so_once_and_not_configured_is_silent) ... ok +test_the_pairing_route_is_off_until_the_read_back_passes (__main__.RefreshAndFallback.test_the_pairing_route_is_off_until_the_read_back_passes) ... ok +test_each_case_is_valid_and_its_outcome_follows_the_pin (__main__.Requests.test_each_case_is_valid_and_its_outcome_follows_the_pin) ... ok +test_the_fixtures_cover_a_good_request_and_every_refusal (__main__.Requests.test_the_fixtures_cover_a_good_request_and_every_refusal) ... ok +test_the_mint_log_keeps_no_untrusted_request_text (__main__.Requests.test_the_mint_log_keeps_no_untrusted_request_text) ... ok +test_the_pin_reads_requests_strictly (__main__.Requests.test_the_pin_reads_requests_strictly) ... ok +test_the_pin_says_how_a_token_is_sealed (__main__.Sealing.test_the_pin_says_how_a_token_is_sealed) ... ok +test_the_schema_takes_only_an_rsa_3072_answer_key (__main__.Sealing.test_the_schema_takes_only_an_rsa_3072_answer_key) ... ok +test_every_refusal_has_one_exit_and_one_fixed_sentence (__main__.ThePin.test_every_refusal_has_one_exit_and_one_fixed_sentence) ... ok +test_the_app_profile_and_token_guards_are_the_identity_contracts (__main__.ThePin.test_the_app_profile_and_token_guards_are_the_identity_contracts) ... ok +test_the_key_stays_on_the_owners_machine (__main__.ThePin.test_the_key_stays_on_the_owners_machine) ... FAIL +test_the_service_has_no_port_and_takes_the_request_on_stdin (__main__.ThePin.test_the_service_has_no_port_and_takes_the_request_on_stdin) ... FAIL + +====================================================================== +FAIL: test_the_key_stays_on_the_owners_machine (__main__.ThePin.test_the_key_stays_on_the_owners_machine) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/contracts/fixtures/token-service/test_fixtures.py", line 169, in test_the_key_stays_on_the_owners_machine + self.assertEqual( +AssertionError: "owner's machine only" != "the owner's machine (pairing and local), [79 chars]ons)" +- owner's machine only ++ the owner's machine (pairing and local), or the token-service environment secret of the owner's private repository (actions) + + +====================================================================== +FAIL: test_the_service_has_no_port_and_takes_the_request_on_stdin (__main__.ThePin.test_the_service_has_no_port_and_takes_the_request_on_stdin) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/code/openwiz/contracts/fixtures/token-service/test_fixtures.py", line 195, in test_the_service_has_no_port_and_takes_the_request_on_stdin + self.assertIn("actions", reach["routes"]) +AssertionError: 'actions' not found in {'pairing': ['room-cli', 'mac', 'run', '--stdin', "python3 -I '' mint"], 'local': ['python3', '-I', '', 'mint']} + +---------------------------------------------------------------------- +Ran 19 tests in 0.024s + +FAILED (failures=2) diff --git a/tools/github-app/test_agent_token.py b/tools/github-app/test_agent_token.py index e788ce76e..ce4685777 100644 --- a/tools/github-app/test_agent_token.py +++ b/tools/github-app/test_agent_token.py @@ -2365,5 +2365,228 @@ def test_a_system_gh_is_refused_where_procfs_cannot_pin_it(self): self.assertIsNotNone(self.identity_of(self.table()), "on Linux it is accepted") +class ActionsRoute(unittest.TestCase): + def setUp(self): + self.root = Path(tempfile.mkdtemp(prefix="agent-actions-")) + self.addCleanup(shutil.rmtree, self.root, True) + self.private = self.root / "private" + self.private.mkdir(mode=0o700) + self.helper = load_helper() + self.wanted = {"requester": "builder-3235", "repositories": [REPO], "permissions": WRITE} + + def start_fake(self, mode="ok"): + import io + import zipfile + + state = {"mode": mode, "dispatches": [], "deleted": [], "redirect_auth": [], + "artifacts": [], "logs": [], "rate_hits": 0, "poll_count": 0} + owner_repo = "synthetic-owner/private-ops" + + def seal_to(token, key): + sealed = b"" + for at in range(0, len(token), 318): + r, w = os.pipe() + os.write(w, key.encode()) + os.close(w) + sealed += subprocess.run( + ["/usr/bin/openssl", "pkeyutl", "-encrypt", "-pubin", "-inkey", f"/dev/fd/{r}", + "-pkeyopt", "rsa_padding_mode:oaep", "-pkeyopt", "rsa_oaep_md:sha256", + "-pkeyopt", "rsa_mgf1_md:sha256"], + input=token[at:at + 318].encode(), stdout=subprocess.PIPE, check=True, pass_fds=(r,)).stdout + os.close(r) + return base64.b64encode(sealed).decode() + + def make_zip(payload, filename="answer.json"): + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as zf: + zf.writestr(filename, payload) + return buf.getvalue() + + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *_args): + pass + + def send_json(self, code, body, headers=None): + data = json.dumps(body).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + for k, v in (headers or {}).items(): + self.send_header(k, v) + self.end_headers() + self.wfile.write(data) + + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + body = json.loads(self.rfile.read(length).decode()) + if state["mode"] == "backoff" and state["rate_hits"] == 0: + state["rate_hits"] += 1 + self.send_json(429, {"message": "rate limited"}, {"Retry-After": "0"}) + return + state["dispatches"].append({"path": self.path, "body": body}) + req = json.loads(body["inputs"]["request"]) + state["nonce"] = body["inputs"]["nonce"] + state["logs"].append(json.dumps({"requester": req["requester"], "outcome": "minted"})) + if state["mode"] == "tampered-zip": + raw = b"not-a-zip" + elif state["mode"] == "tampered-body": + raw = make_zip(json.dumps({"schema": "openwiz.token-service.v1", "kind": "answer", + "sealed_token": "A" * 512, "expires_at": int(time.time()) + 3600, + "repositories": ["other/repo"], "permissions": WRITE})) + elif state["mode"] == "unopenable": + _, other_pub = self.server.helper.one_time_key() + raw = make_zip(json.dumps({"schema": "openwiz.token-service.v1", "kind": "answer", + "sealed_token": seal_to(TOKEN, other_pub), + "expires_at": int(time.time()) + 3600, + "repositories": [REPO], "permissions": WRITE})) + elif state["mode"] == "refusal": + raw = make_zip(json.dumps({"schema": "openwiz.token-service.v1", "kind": "refusal", + "refusal": "not-installed", + "message": PIN["refusals"]["not-installed"]["message"]})) + else: + raw = make_zip(json.dumps({"schema": "openwiz.token-service.v1", "kind": "answer", + "sealed_token": seal_to(TOKEN, req["answer_key"]), + "expires_at": int(time.time()) + 3600, + "repositories": [REPO], "permissions": WRITE})) + state["zip"] = raw + state["artifacts"].append(raw) + self.send_response(204) + self.end_headers() + + def do_GET(self): + if state["mode"] == "backoff" and state["rate_hits"] == 1: + state["rate_hits"] += 1 + self.send_json(403, {"message": "secondary rate limit"}, {"Retry-After": "0"}) + return + if self.path.startswith(f"/repos/{owner_repo}/actions/workflows/mint-workflow.yml/runs"): + if state["mode"] == "missing-run": + self.send_json(200, {"workflow_runs": []}) + return + status = "in_progress" if state["mode"] == "timeout" else "completed" + conclusion = "failure" if state["mode"] == "failed-run" else ("success" if status == "completed" else None) + self.send_json(200, {"workflow_runs": [{ + "id": 501, "name": f"openwiz-mint-{state['nonce']}", + "head_branch": "main", "event": "workflow_dispatch", + "status": status, "conclusion": conclusion, + }]}) + return + if self.path == f"/repos/{owner_repo}/actions/runs/501": + state["poll_count"] += 1 + self.send_json(200, {"id": 501, "status": "in_progress", "conclusion": None}) + return + if self.path == f"/repos/{owner_repo}/actions/runs/501/artifacts": + items = [] if state["mode"] == "missing-artifact" else [ + {"id": 701, "name": state["nonce"], "expired": False}] + self.send_json(200, {"artifacts": items}) + return + if self.path == f"/repos/{owner_repo}/actions/artifacts/701/zip": + self.send_response(302) + self.send_header("Location", f"http://127.0.0.1:{self.server.server_address[1]}/download/701") + self.end_headers() + return + if self.path == "/download/701": + state["redirect_auth"].append(self.headers.get("Authorization")) + data = state["zip"] + self.send_response(200) + self.send_header("Content-Type", "application/zip") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + return + self.send_response(404) + self.end_headers() + + def do_DELETE(self): + if self.path == f"/repos/{owner_repo}/actions/artifacts/701": + state["deleted"].append(701) + self.send_response(204) + self.end_headers() + return + self.send_response(404) + self.end_headers() + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + server.helper = self.helper + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + self.addCleanup(server.shutdown) + self.addCleanup(server.server_close) + base = f"http://127.0.0.1:{server.server_address[1]}" + env = { + "PATH": os.environ.get("PATH", os.defpath), + "OPENWIZ_AGENT_TOKEN_DIR": str(self.private), + "OPENWIZ_TOKEN_SERVICE_ROUTE": "actions", + "OPENWIZ_TOKEN_SERVICE_REPOSITORY": owner_repo, + "OPENWIZ_GITHUB_API_BASE": base, + "GH_TOKEN": "synthetic-owner-account-token", + } + return env, state + + def test_actions_round_trip_and_deletes_artifact(self): + # catches: broken actions dispatch/poll/download/open flow, non-main dispatch, + # leaking Authorization on redirect, or forgetting to delete the artifact after download. + env, state = self.start_fake("ok") + private = self.helper.Private(env, create=True) + self.addCleanup(os.close, private.fd) + token, expires_at = self.helper.token_for(private, self.wanted, env) + self.assertEqual(token, TOKEN) + self.assertGreater(expires_at, int(time.time()) + 300) + self.assertEqual(len(state["dispatches"]), 1) + self.assertEqual(state["dispatches"][0]["body"]["ref"], "main") + self.assertEqual(state["deleted"], [701], "artifact must be deleted after download") + self.assertEqual(state["redirect_auth"], [None], "Authorization must not cross artifact redirect") + + def test_actions_failures_fall_back_with_right_reason(self): + # catches: wrong fallback reason or leaked/undeleted artifact on missing run, timeout, + # failed run, missing/tampered artifact, unopenable answer, or contract refusal. + cases = [ + ("missing-run", "unreachable", []), + ("timeout", "unreachable", []), + ("failed-run", "unreachable", []), + ("missing-artifact", "unreachable", []), + ("tampered-zip", "bad-answer", [701]), + ("tampered-body", "bad-answer", [701]), + ("unopenable", "bad-answer", [701]), + ("refusal", "not-installed", [701]), + ] + for mode, expected_reason, expected_deleted in cases: + with self.subTest(mode): + env, state = self.start_fake(mode) + private = self.helper.Private(env, create=True) + self.addCleanup(os.close, private.fd) + err = [] + with mock.patch.object(self.helper, "ACTIONS_TIMEOUT_S", 0.08), \ + mock.patch.object(self.helper, "ACTIONS_POLL_S", 0.01), \ + mock.patch.object(self.helper.sys, "stderr", + types.SimpleNamespace(write=err.append)): + token, expires_at = self.helper.token_for(private, self.wanted, env) + self.assertEqual((token, expires_at), (None, None)) + self.assertEqual("".join(err), NOTE.replace("", expected_reason) + "\n") + self.assertEqual(state["deleted"], expected_deleted) + + def test_actions_backs_off_on_403_and_429(self): + # catches: failing immediately on GitHub 403/429 instead of backing off and retrying. + env, state = self.start_fake("backoff") + private = self.helper.Private(env, create=True) + self.addCleanup(os.close, private.fd) + with mock.patch.object(self.helper, "ACTIONS_POLL_S", 0.01): + token, _ = self.helper.token_for(private, self.wanted, env) + self.assertEqual(token, TOKEN) + self.assertEqual(state["rate_hits"], 2) + self.assertEqual(state["deleted"], [701]) + + def test_actions_never_exposes_plaintext_token(self): + # catches: plaintext token appearing in dispatch inputs, fake run logs, artifact zip, or helper output. + env, state = self.start_fake("ok") + done = subprocess.run([sys.executable, "-I", str(HELPER), "start", *REQ], + env=env, capture_output=True, text=True, timeout=30) + self.assertEqual(done.returncode, 0, done.stderr) + for blob in (json.dumps(state["dispatches"]), "\n".join(state["logs"]), + done.stdout, done.stderr): + self.assertNotIn(TOKEN, blob) + for raw in state["artifacts"]: + self.assertNotIn(TOKEN.encode(), raw) + + if __name__ == "__main__": unittest.main() diff --git a/tools/github-app/test_mint_workflow.py b/tools/github-app/test_mint_workflow.py new file mode 100644 index 000000000..a74c21ba8 --- /dev/null +++ b/tools/github-app/test_mint_workflow.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Offline security and execution proofs for tools/github-app/mint-workflow.yml (#3235).""" +import base64 +import importlib.util +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +TEMPLATE = HERE / "mint-workflow.yml" +WORKFLOWS = ROOT / ".github" / "workflows" +SHA40 = re.compile(r"^[0-9a-f]{40}$") +USES_RE = re.compile(r"^\s*(?:-\s*)?uses:\s*([^\s#]+)") +EXPR_RE = re.compile(r"\$\{\{.*?\}\}") + + +def pinned_openwiz_actions(): + """Return {action_name: set(shas)} already pinned across OpenWiz's own workflows.""" + pinned = {} + for path in sorted(WORKFLOWS.glob("*.yml")): + for line in path.read_text().splitlines(): + m = USES_RE.match(line) + if not m or "@" not in m.group(1): + continue + action, ref = m.group(1).split("@", 1) + if SHA40.fullmatch(ref): + pinned.setdefault(action, set()).add(ref) + return pinned + + +def extract_run_blocks(text): + """Extract every `run:` command (inline or block scalar) from a workflow YAML.""" + lines = text.splitlines() + blocks, i = [], 0 + while i < len(lines): + m = re.match(r"^(\s*)(?:-\s*)?run:\s*(.*)$", lines[i]) + if not m: + i += 1 + continue + indent = len(m.group(1)) + rest = m.group(2).strip() + if rest in ("|", "|-", "|+", ">", ">-", ">+"): + body, i = [], i + 1 + while i < len(lines): + line = lines[i] + if line.strip() and (len(line) - len(line.lstrip(" "))) <= indent: + break + body.append(line) + i += 1 + non_empty = [len(l) - len(l.lstrip(" ")) for l in body if l.strip()] + cut = min(non_empty) if non_empty else 0 + blocks.append("\n".join(l[cut:] if len(l) >= cut else "" for l in body)) + else: + blocks.append(rest) + i += 1 + return blocks + + +def check_template(text, allowed_actions): + """Return a list of security violations in a mint-workflow.yml text.""" + errors = [] + lines = text.splitlines() + # 1. Top-level `on:` must contain only `workflow_dispatch`. + on_idx = next((i for i, l in enumerate(lines) if re.match(r"^on:\s*$", l)), None) + if on_idx is None: + errors.append("missing top-level on: block") + else: + triggers = [] + for l in lines[on_idx + 1:]: + if l.strip() and not l.startswith(" "): + break + m = re.match(r"^ ([A-Za-z0-9_-]+):\s*", l) + if m: + triggers.append(m.group(1)) + if triggers != ["workflow_dispatch"]: + errors.append(f"triggers must be workflow_dispatch only, got {triggers!r}") + # 2. Key job must name environment: token-service and guard github.ref == 'refs/heads/main'. + if not re.search(r"(?m)^\s{4}environment:\s*token-service\s*$", text): + errors.append("missing job environment: token-service") + if not re.search(r"(?m)^\s{4}if:\s*(?:\$\{\{\s*)?github\.ref\s*==\s*'refs/heads/main'(?:\s*\}\})?\s*$", text): + errors.append("missing job-level refs/heads/main guard") + # 3. OpenWiz checkout must pin a 40-hex commit SHA (never a branch). + checkout_ok = False + for i, l in enumerate(lines): + if re.match(r"^\s+repository:\s*openwizdev/OpenWiz\s*$", l): + indent = len(l) - len(l.lstrip(" ")) + for nxt in lines[i + 1:]: + if nxt.strip() and (len(nxt) - len(nxt.lstrip(" "))) < indent: + break + m = re.match(r"^\s+ref:\s*([A-Za-z0-9._/-]+)\s*(?:#.*)?$", nxt) + if m and SHA40.fullmatch(m.group(1)): + checkout_ok = True + break + if not checkout_ok: + errors.append("openwizdev/OpenWiz checkout must pin a 40-hex commit sha") + # 4. Every `uses:` must be actions/checkout or actions/upload-artifact at an OpenWiz-pinned SHA. + allowed_names = {"actions/checkout", "actions/upload-artifact"} + uses_found = [] + for l in lines: + m = USES_RE.match(l) + if not m: + continue + spec = m.group(1) + uses_found.append(spec) + if "@" not in spec: + errors.append(f"unpinned uses: {spec}") + continue + action, ref = spec.split("@", 1) + if action not in allowed_names: + errors.append(f"disallowed action: {action}") + elif not SHA40.fullmatch(ref) or ref not in allowed_actions.get(action, set()): + errors.append(f"action sha not pinned in OpenWiz workflows: {spec}") + if not uses_found: + errors.append("no uses: steps found") + # 5. No `${{ }}` expression (especially inputs) inside any `run:` block. + run_blocks = extract_run_blocks(text) + if not run_blocks: + errors.append("no run: block found") + for block in run_blocks: + if EXPR_RE.search(block): + errors.append("expression ${{ }} found inside a run: block") + # 6. Artifact upload retention-days: 1. + if not re.search(r"(?m)^\s+retention-days:\s*1\s*$", text): + errors.append("missing artifact retention-days: 1") + return errors + + +class MintWorkflowTemplate(unittest.TestCase): + def test_template_passes_all_security_guards(self): + # catches: missing workflow template, non-dispatch trigger, missing token-service env, + # unpinned OpenWiz checkout, ${{ inputs }} in run:, or unpinned/foreign action uses. + self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") + errors = check_template(TEMPLATE.read_text(), pinned_openwiz_actions()) + self.assertEqual(errors, [], f"template failed guards: {errors}") + + def test_template_guard_catches_every_planted_violation(self): + # catches: a template guard that passes even when a security invariant is broken. + self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") + good = TEMPLATE.read_text() + allowed = pinned_openwiz_actions() + mutations = { + "branch trigger": good.replace(" workflow_dispatch:", " push:\n branches: [main]\n workflow_dispatch:", 1), + "wrong env": good.replace(" environment: token-service", " environment: other", 1), + "no main guard": re.sub(r"(?m)^\s{4}if:.*refs/heads/main.*$", "", good), + "branch checkout": re.sub(r"(?m)^(\s+ref:\s*)[0-9a-f]{40}", r"\1main", good), + "input in run": good + "\n - run: echo ${{ inputs.request }}\n", + "foreign action": good + "\n - uses: actions/setup-python@0000000000000000000000000000000000000000\n", + "unpinned action": re.sub(r"actions/checkout@[0-9a-f]{40}", "actions/checkout@v7", good), + } + for name, bad in mutations.items(): + with self.subTest(name): + self.assertNotEqual(check_template(bad, allowed), [], f"guard missed {name}") + + +class MintWorkflowExecution(unittest.TestCase): + def test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields(self): + # catches: a workflow script that writes the App key to disk, leaks the plaintext token + # to stdout/stderr/summary/artifact, accepts non-main refs, or fails to seal per #3085. + self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") + spec = importlib.util.spec_from_file_location("test_token_service", HERE / "test_token_service.py") + ts = importlib.util.module_from_spec(spec) + spec.loader.exec_module(ts) + helper_spec = importlib.util.spec_from_file_location("agent_token", HERE / "agent-token.py") + helper = importlib.util.module_from_spec(helper_spec) + helper_spec.loader.exec_module(helper) + + blocks = extract_run_blocks(TEMPLATE.read_text()) + self.assertTrue(blocks, "no run: block in template") + script = max(blocks, key=len) + private_key, answer_key = helper.one_time_key() + self.assertIsNotNone(private_key) + app_pem = ts.throwaway_key() + request = { + "schema": "openwiz.token-service.v1", + "kind": "request", + "requester": "builder-3235", + "answer_key": answer_key, + "repositories": ["synthetic-owner/work"], + "permissions": {"metadata": "read", "contents": "write", "issues": "write", + "pull_requests": "write", "checks": "read", "actions": "read"}, + } + with tempfile.TemporaryDirectory(prefix="mint-wf-") as tmp: + work = Path(tmp) + os.symlink(ROOT, work / "openwiz") + summary = work / "summary.md" + summary.write_text("") + with ts.fake_github(app_pem, ["synthetic-owner/work"]) as (url, calls, _fake): + base_env = { + "PATH": os.environ.get("PATH", os.defpath), + "GITHUB_REF": "refs/heads/feature", + "GITHUB_STEP_SUMMARY": str(summary), + "OPENWIZ_REQUEST": json.dumps(request), + "OPENWIZ_NONCE": "a" * 32, + "OPENWIZ_GITHUB_APP_KEY": base64.b64encode(app_pem).decode("ascii"), + "OPENWIZ_GITHUB_APP_ID": "1001", + "OPENWIZ_GITHUB_APP_MODE": "user", + "OPENWIZ_GITHUB_API_BASE": url, + } + # Non-main ref must be refused before any GitHub call. + bad = subprocess.run(["sh", "-eu", "-c", script], cwd=work, env=base_env, + capture_output=True, text=True, timeout=30) + self.assertNotEqual(bad.returncode, 0, "non-main ref must fail") + self.assertEqual(calls, [], "non-main ref must make no GitHub call") + self.assertFalse((work / "out" / "answer.json").exists()) + + # Main ref mints and seals, writes only mint-log fields to summary, never writes key. + good = subprocess.run(["sh", "-eu", "-c", script], cwd=work, + env=dict(base_env, GITHUB_REF="refs/heads/main"), + capture_output=True, text=True, timeout=30) + self.assertEqual(good.returncode, 0, good.stderr) + answer_path = work / "out" / "answer.json" + self.assertTrue(answer_path.is_file(), "missing out/answer.json") + self.assertEqual(sorted(p.name for p in (work / "out").iterdir()), ["answer.json"]) + answer_text = answer_path.read_text() + answer = json.loads(answer_text) + self.assertEqual(answer["kind"], "answer") + self.assertNotIn("token", answer) + token = helper.opened(answer["sealed_token"], private_key) + self.assertIsNotNone(token) + summary_text = summary.read_text() + for blob in (good.stdout, good.stderr, summary_text, answer_text): + self.assertNotIn(token, blob) + self.assertNotIn("PRIVATE KEY", blob) + # Summary carries mint-log fields only. + self.assertIn("builder-3235", summary_text) + self.assertIn("minted", summary_text) + self.assertNotIn("sealed_token", summary_text) + self.assertEqual(list(work.rglob("private-key.pem")), []) + + +if __name__ == "__main__": + unittest.main() From 93e1955b5ca381286d731783866ccbaf5d273d13 Mon Sep 17 00:00:00 2001 From: jparker2006 <85816763+jparker2006@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:39:36 +0000 Subject: [PATCH 2/3] #3235: green: main-only Actions token-service route, sealed per #3085 --- changes/3235.md | 3 + contracts/token-service.v1.md | 72 +++++++--- docs/evidence/3235/green-run.txt | 8 ++ docs/github-app.md | 37 +++++ tools/github-app/agent-token.py | 182 ++++++++++++++++++++++++- tools/github-app/mint-workflow.yml | 154 +++++++++++++++++++++ tools/github-app/test_agent_token.py | 2 +- tools/github-app/test_mint_workflow.py | 6 +- 8 files changed, 441 insertions(+), 23 deletions(-) create mode 100644 changes/3235.md create mode 100644 docs/evidence/3235/green-run.txt create mode 100644 tools/github-app/mint-workflow.yml diff --git a/changes/3235.md b/changes/3235.md new file mode 100644 index 000000000..5051467b0 --- /dev/null +++ b/changes/3235.md @@ -0,0 +1,3 @@ +kind: added + +On synthetic fixtures, agents can request sealed `openwiz[bot]` tokens through a main-only GitHub Actions workflow route (`OPENWIZ_TOKEN_SERVICE_ROUTE=actions`) that keeps the App key in a `token-service` environment secret and deletes each sealed-answer artifact after download. diff --git a/contracts/token-service.v1.md b/contracts/token-service.v1.md index 7b33e31b4..6e31a5f41 100644 --- a/contracts/token-service.v1.md +++ b/contracts/token-service.v1.md @@ -11,7 +11,9 @@ this contract. **Revised in place by #3085**, before any live use: a request carries `answer_key` and an answer `sealed_token` in place of `token`. An older service or helper meeting a newer one gives a `usage` refusal, so the agent falls back and no -token is minted. +token is minted. **Extended by #3235** with a third route, `actions`, running as a +main-only workflow in the owner's private repository and returning the same sealed +answer. **This contract grants nothing.** It authorizes no installation, credential, token mint, live read or write, or permission change. A fixture or test that @@ -34,13 +36,21 @@ Where they disagree, the contract is wrong and must be fixed. "schema": "openwiz.token-service.v1", "authority": {"installation": false, "credential": false, "live": false}, "key": { - "lives": "owner's machine only", + "lives": "the owner's machine (pairing and local), or the token-service environment secret of the owner's private repository (actions)", "path": "/service/app/private-key.pem", "file_mode": "0600", "directory_mode": "0700", "read_by": "the token service only", "agents": "never ask for, read, copy or hold it", - "leaves_the_machine": false + "leaves_the_machine": false, + "actions_environment": { + "name": "token-service", + "secret": "OPENWIZ_GITHUB_APP_KEY", + "deployment_branches": "main only", + "trigger": "workflow_dispatch only", + "ref": "refs/heads/main", + "delivery": "pipe or descriptor, never a file" + } }, "app_permissions": { "metadata": "read", @@ -55,6 +65,7 @@ Where they disagree, the contract is wrong and must be fixed. "request": "stdin", "answer": "stdout, one JSON line, read from a pipe", "timeout_s": 60, + "actions_timeout_s": 120, "token_crossing": { "never": ["command line", "terminal", "log", "record"], "only": "sealed, as piped stdout of one room-cli mac run --stdin call", @@ -65,11 +76,13 @@ Where they disagree, the contract is wrong and must be fixed. "pairing_gate": {"variable": "OPENWIZ_TOKEN_SERVICE_READBACK", "on_only_when": "passed", "otherwise": "pairing-off"}, "routes": { "pairing": ["room-cli", "mac", "run", "--stdin", "python3 -I '' mint"], - "local": ["python3", "-I", "", "mint"] + "local": ["python3", "-I", "", "mint"], + "actions": "workflow_dispatch on main in OPENWIZ_TOKEN_SERVICE_REPOSITORY, sealed answer artifact named by nonce" }, "configuration": { "OPENWIZ_TOKEN_SERVICE": "the service's absolute path on the owner's machine", - "OPENWIZ_TOKEN_SERVICE_ROUTE": ["pairing", "local"], + "OPENWIZ_TOKEN_SERVICE_ROUTE": ["pairing", "local", "actions"], + "OPENWIZ_TOKEN_SERVICE_REPOSITORY": "the owner's private repository () for the actions route", "OPENWIZ_TOKEN_SERVICE_READBACK": "passed only after GA5's live read-back succeeded" } }, @@ -128,12 +141,29 @@ Where they disagree, the contract is wrong and must be fixed. ## Where the key lives -The App's private key lives **only on the owner's machine** (the owner's PC -now; the VPS later, J258), in the owner's OpenWiz state directory, at -`/service/app/private-key.pem`, mode 0600 in 0700 directories, where -the merged minter (`tools/github-app/`) already keeps it. Only the token -service reads it. It never leaves that machine: not to a cloud sandbox, a -Cloudroom secret, a pairing call, a prompt, a log or the repository. +The App's private key lives in one of two places: **the owner's machine (`pairing` +and `local`), or the `token-service` environment secret of the owner's private +repository (`actions`)**. + +- On the owner's machine (`pairing` and `local`), it sits in the owner's OpenWiz + state directory at `/service/app/private-key.pem`, mode 0600 in 0700 + directories, where the merged minter (`tools/github-app/`) keeps it. Only the + token service reads it. It never leaves that machine: not to a cloud sandbox, + a Cloudroom secret, a pairing call, a prompt, a log or the repository. +- On the `actions` route, it lives as the environment secret `OPENWIZ_GITHUB_APP_KEY` + (base64 of the PEM) in the `token-service` environment of the owner's private + repository, never as a repository secret. **Main-only rule:** only `main`'s + workflow code may ever read the key. The workflow triggers on `workflow_dispatch` + only, the `token-service` environment's deployment branches are restricted to + `main` only, the job refuses any ref other than `refs/heads/main`, `main` is + protected by an owner-only ruleset, the OpenWiz checkout is pinned to a commit + SHA (never a branch), untrusted inputs reach the script only through `env:` + (never inside `${{ }}` in a `run:`), and the key reaches `token-service.py` + through a pipe or descriptor, never a file on disk. **Why a branch-triggered + workflow must never read the key:** a `push`, `pull_request` or non-`main` + dispatch can run untrusted workflow YAML or unreviewed branch code in the same + job and exfiltrate the App's private key, which would let an attacker mint + installation tokens for every repository the App is installed on. **Agents never ask for the key.** No agent, helper, brief or request asks for, reads, copies or holds it, and nothing in a request names it. The service @@ -141,13 +171,23 @@ never sends it, and no answer or refusal carries it or the App's JWT. ## Reaching the service -The service listens on **no port**, public or local. An agent reaches it the -way it already reaches the owner's machine: +The service listens on **no port**, public or local. An agent reaches it on one +of three routes: -- **A cloud thread** runs the service through the owner's existing machine - pairing: `room-cli mac run --stdin 'python3 -I mint'`. -- **A local thread**, already on the owner's machine, runs +- **A cloud thread (`pairing`)** runs the service through the owner's existing + machine pairing: `room-cli mac run --stdin 'python3 -I mint'`. +- **A local thread (`local`)**, already on the owner's machine, runs `python3 -I mint` itself. +- **An Actions workflow (`actions`)** dispatches `mint-workflow.yml` on `main` + in `OPENWIZ_TOKEN_SERVICE_REPOSITORY` (``, a public setting) with + `OPENWIZ_TOKEN_SERVICE_ROUTE=actions`, passing the request JSON (with its + one-time `answer_key`) and a fresh random `nonce`. It finds the run by its + `run-name` (`openwiz-mint-`), waits up to **120 seconds** (backing off + on 403 or 429), downloads the single 1-day artifact named by `nonce`, deletes + the artifact immediately after download, and opens and checks the sealed + answer as on the other routes. The job summary carries only the mint-log + fields; no plaintext token ever appears in dispatch inputs, run logs, job + summary, artifact or helper output. `` is the service's absolute path on the owner's machine, from `OPENWIZ_TOKEN_SERVICE`; `OPENWIZ_TOKEN_SERVICE_ROUTE` says `pairing` or diff --git a/docs/evidence/3235/green-run.txt b/docs/evidence/3235/green-run.txt new file mode 100644 index 000000000..7bf864880 --- /dev/null +++ b/docs/evidence/3235/green-run.txt @@ -0,0 +1,8 @@ +Green proof run for #3235 (offline, synthetic keys and loopback fake GitHub only): + +- python3 -I tools/github-app/test_mint_workflow.py -v: Ran 3 tests, OK +- python3 -I contracts/fixtures/token-service/test_fixtures.py -v: Ran 19 tests, OK +- python3 -I tools/github-app/test_token_service.py: Ran 14 tests, OK +- python3 -I tools/github-app/test_app_select.py: Ran 5 tests, OK +- python3 -I tools/github-app/test_agent_token.py ActionsRoute -v: Ran 4 tests, OK +- python3 -I tools/privacy-check/check.py --tree .: exit 0 diff --git a/docs/github-app.md b/docs/github-app.md index 3262decfb..246a08c68 100644 --- a/docs/github-app.md +++ b/docs/github-app.md @@ -225,6 +225,43 @@ python3 -I tools/github-app/token-service.py stop --state-dir "$HOME/.local/stat `contracts/fixtures/token-service/requests.json` case and the guards above against a fake GitHub with a throwaway key. +## The Actions token-service route + +An agent can also reach the token service through a `main`-only GitHub Actions +workflow in the owner's private repository (`OPENWIZ_TOKEN_SERVICE_ROUTE=actions` +and `OPENWIZ_TOKEN_SERVICE_REPOSITORY=`), using the workflow template +at `tools/github-app/mint-workflow.yml` and the same sealed-answer contract +([`token-service.v1`](../contracts/token-service.v1.md)). Only `main`'s workflow +code may ever read the App's private key: a branch-triggered or non-`main` +workflow must never read it. + +Owner setup steps: + +1. **Create the `token-service` environment** in the private repository with + deployment branches restricted to `main` only. Add environment variables + `OPENWIZ_GITHUB_APP_ID` (the numeric App ID) and, for the factory App, + `OPENWIZ_GITHUB_APP_MODE=factory`. +2. **Make a fresh App key into its secret**, through GitHub's own form: generate + a new private key in the App's settings, base64-encode the PEM, and save it + as the `token-service` environment secret `OPENWIZ_GITHUB_APP_KEY` (never a + repository secret). +3. **Protect `main` with a ruleset** so only the owner can change it (no branch + bypass or agent push to `main`). +4. **Copy the template** (`tools/github-app/mint-workflow.yml`) into the private + repository's `.github/workflows/mint-workflow.yml` on `main`, keeping its + pinned `openwizdev/OpenWiz` commit SHA and pinned action SHAs. +5. **Delete the old key** in the App's settings once the new route is verified. + +With `OPENWIZ_TOKEN_SERVICE_ROUTE=actions` and +`OPENWIZ_TOKEN_SERVICE_REPOSITORY=`, `agent-token.py` dispatches the +workflow on `main` with the request (and one-time `answer_key`) plus a fresh +random `nonce`, waits up to 120 seconds (backing off on 403 or 429), downloads +and immediately deletes the 1-day artifact named by `nonce`, and opens and checks +the sealed answer in memory. Any failure falls back to the owner's account with +the standard-error note. Offline proofs run with +`python3 -I tools/github-app/test_mint_workflow.py` and +`python3 -I tools/github-app/test_agent_token.py`. + ## Pairing App selection When the owner's machine holds more than one App's state, the pairing mint must reach diff --git a/tools/github-app/agent-token.py b/tools/github-app/agent-token.py index e5e8c04b2..d7a001445 100644 --- a/tools/github-app/agent-token.py +++ b/tools/github-app/agent-token.py @@ -24,6 +24,8 @@ REFUSALS = {"usage": 2, "one-owner": 2, "not-installed": 3, "permission": 5, "github": 5, "expiry": 5, "unavailable": 1} REFRESH_AT_S, MAX_LIFETIME_S, TIMEOUT_S = 300, 3900, 60 +ACTIONS_TIMEOUT_S, ACTIONS_POLL_S, ACTIONS_ARTIFACT_LIMIT = 120, 2.0, 64 * 1024 +WORKFLOW_FILE = re.compile(r"[A-Za-z0-9._-]+\.ya?ml") NOTE = "openwiz: no openwiz[bot] token ({}); using the owner's GitHub account\n" WITHHELD = "openwiz: openwiz[bot] token withheld from git ({}); git stops rather than use another account\n" REQUESTER = re.compile(r"[a-z][a-z0-9-]{0,63}") @@ -154,6 +156,13 @@ def check_answer(message, wanted, private): def route(env): + if env.get("OPENWIZ_TOKEN_SERVICE_ROUTE") == "actions": + repo = env.get("OPENWIZ_TOKEN_SERVICE_REPOSITORY", "") + workflow = env.get("OPENWIZ_TOKEN_SERVICE_WORKFLOW") or "mint-workflow.yml" + if (not REPOSITORY.fullmatch(repo) or repo.split("/")[1] in (".", "..") + or not WORKFLOW_FILE.fullmatch(workflow) or workflow in (".", "..")): + return "unreachable", None + return None, ("actions", repo, workflow) service = env.get("OPENWIZ_TOKEN_SERVICE", "") if not service.startswith("/") or any(c in service for c in "'\n\r\0"): return "unreachable", None @@ -166,13 +175,176 @@ def route(env): return "unreachable", None +def _actions_auth(env): + clean = without_inherited(env) + clean.pop(LEGACY_APP_KEY, None) + token = clean.get("GH_TOKEN") or clean.get("GITHUB_TOKEN") or "" + if token: + return token.strip() + try: + done = subprocess.run(["gh", "auth", "token"], stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, env=clean, timeout=10) + except (OSError, subprocess.SubprocessError): + return "" + return done.stdout.decode("utf-8", "replace").strip() if done.returncode == 0 else "" + + +def _actions_http(method, url, auth, base, deadline, body=None, follow_redirect=False, limit=1024 * 1024): + import urllib.error + import urllib.request + + class _NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *_args, **_kwargs): + return None + + opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect()) + backoff = ACTIONS_POLL_S + data = json.dumps(body).encode("utf-8") if body is not None else None + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + return None, b"" + headers = {"Accept": "application/vnd.github+json", "User-Agent": "OpenWiz-agent-token", + "X-GitHub-Api-Version": "2022-11-28"} + if auth: + headers["Authorization"] = "Bearer " + auth + if data is not None: + headers["Content-Type"] = "application/json" + req = urllib.request.Request(url, data=data, headers=headers, method=method) + try: + with opener.open(req, timeout=min(15.0, max(0.5, remaining))) as resp: + raw = resp.read(limit + 1) + return (resp.status, raw) if len(raw) <= limit else (None, b"") + except urllib.error.HTTPError as err: + if follow_redirect and err.code in (301, 302, 303, 307, 308): + loc = err.headers.get("Location", "") + parts = urllib.parse.urlsplit(loc) + base_parts = urllib.parse.urlsplit(base) + safe = (parts.scheme == "https" if base == API_BASE + else parts.scheme == "http" and parts.netloc == base_parts.netloc) + if not safe: + return None, b"" + return _actions_http("GET", loc, None, base, deadline, follow_redirect=False, limit=limit) + if err.code in (403, 429): + retry = err.headers.get("Retry-After", "") + wait = float(retry) if retry.isdigit() else backoff + backoff = min(backoff * 2, 30.0) + left = deadline - time.monotonic() + if left <= 0: + return None, b"" + time.sleep(min(wait, left)) + continue + return err.code, b"" + except (OSError, ValueError): + return None, b"" + + +def ask_actions(repo, workflow, request, env): + import io + import zipfile + + base = revoke_base(env) + auth = _actions_auth(env) if base else "" + if not base or not auth: + return "unreachable", None + deadline = time.monotonic() + ACTIONS_TIMEOUT_S + nonce = secrets.token_hex(16) + run_name = f"openwiz-mint-{nonce}" + dispatch_url = f"{base}/repos/{repo}/actions/workflows/{workflow}/dispatches" + status, _ = _actions_http("POST", dispatch_url, auth, base, deadline, + body={"ref": "main", "inputs": {"request": request.decode("utf-8").strip(), + "nonce": nonce}}) + if status not in (200, 204): + return "unreachable", None + + runs_url = f"{base}/repos/{repo}/actions/workflows/{workflow}/runs?event=workflow_dispatch&branch=main&per_page=10" + found = None + poll = ACTIONS_POLL_S + while time.monotonic() < deadline: + status, raw = _actions_http("GET", runs_url, auth, base, deadline) + payload = _parse(raw) if status == 200 else None + if isinstance(payload, dict) and isinstance(payload.get("workflow_runs"), list): + for item in payload["workflow_runs"]: + if (isinstance(item, dict) and item.get("name") == run_name + and item.get("head_branch") == "main" + and item.get("event") == "workflow_dispatch" + and type(item.get("id")) is int and item["id"] > 0): + found = item + break + if found is not None: + break + left = deadline - time.monotonic() + if left <= 0: + break + time.sleep(min(poll, left)) + poll = min(poll * 1.5, 5.0) + if found is None: + return "unreachable", None + + run_id = found["id"] + run_url = f"{base}/repos/{repo}/actions/runs/{run_id}" + while found.get("status") != "completed": + left = deadline - time.monotonic() + if left <= 0: + return "unreachable", None + time.sleep(min(poll, left)) + poll = min(poll * 1.5, 5.0) + status, raw = _actions_http("GET", run_url, auth, base, deadline) + item = _parse(raw) if status == 200 else None + if not isinstance(item, dict): + return "unreachable", None + found = item + if found.get("conclusion") != "success": + return "unreachable", None + + status, raw = _actions_http("GET", f"{base}/repos/{repo}/actions/runs/{run_id}/artifacts", auth, base, deadline) + payload = _parse(raw) if status == 200 else None + matches = [a for a in (payload.get("artifacts") if isinstance(payload, dict) else []) + if isinstance(a, dict) and a.get("name") == nonce and not a.get("expired") + and type(a.get("id")) is int and a["id"] > 0] + if len(matches) != 1: + return "unreachable", None + artifact_id = matches[0]["id"] + try: + dl_status, zip_bytes = _actions_http( + "GET", f"{base}/repos/{repo}/actions/artifacts/{artifact_id}/zip", + auth, base, deadline, follow_redirect=True, limit=ACTIONS_ARTIFACT_LIMIT) + finally: + _actions_http("DELETE", f"{base}/repos/{repo}/actions/artifacts/{artifact_id}", + auth, base, time.monotonic() + 15.0) + if dl_status != 200: + return "unreachable", None + try: + with zipfile.ZipFile(io.BytesIO(zip_bytes)) as zf: + infos = zf.infolist() + if len(infos) != 1 or infos[0].filename != "answer.json" or infos[0].file_size > ACTIONS_ARTIFACT_LIMIT: + return "bad-answer", None + content = zf.read(infos[0]) + except (zipfile.BadZipFile, OSError, ValueError): + return "bad-answer", None + if len(content) > ACTIONS_ARTIFACT_LIMIT: + return "bad-answer", None + message = _parse(content) + if not isinstance(message, dict): + return "bad-answer", None + if (set(message) == {"schema", "kind", "refusal", "message"} + and message["schema"] == SCHEMA and message["kind"] == "refusal" + and isinstance(message["refusal"], str) and message["refusal"] in REFUSALS + and isinstance(message["message"], str) and REFUSAL_MESSAGE.fullmatch(message["message"])): + return message["refusal"], None + return None, message + + def mint(argv, wanted, env): private, answer_key = one_time_key() if not private: return "unreachable", None, None request = json.dumps({"schema": SCHEMA, "kind": "request", "answer_key": answer_key, **wanted}).encode() + b"\n" - call_env = {k: v for k, v in env.items() if k not in ("GH_TOKEN", LEGACY_APP_KEY)} - reason, message = ask(argv, request, call_env) + if isinstance(argv, tuple) and argv and argv[0] == "actions": + reason, message = ask_actions(argv[1], argv[2], request, env) + else: + call_env = {k: v for k, v in env.items() if k not in ("GH_TOKEN", LEGACY_APP_KEY)} + reason, message = ask(argv, request, call_env) if reason: return reason, None, None got = check_answer(message, wanted, private) @@ -364,7 +536,7 @@ def token_for(private, wanted, env, snapshot=None): def configured(env): - return bool(env.get("OPENWIZ_TOKEN_SERVICE")) + return bool(env.get("OPENWIZ_TOKEN_SERVICE")) or env.get("OPENWIZ_TOKEN_SERVICE_ROUTE") == "actions" def parse_request(args): @@ -1239,7 +1411,9 @@ def main(argv): raise Refused(f"usage: {USAGE}") environ = os.environ names = set(environ) - if LEGACY_APP_KEY in names and "OPENWIZ_TOKEN_SERVICE" in names and environ["OPENWIZ_TOKEN_SERVICE"]: + if LEGACY_APP_KEY in names and ( + ("OPENWIZ_TOKEN_SERVICE" in names and environ["OPENWIZ_TOKEN_SERVICE"]) + or ("OPENWIZ_TOKEN_SERVICE_ROUTE" in names and environ["OPENWIZ_TOKEN_SERVICE_ROUTE"] == "actions")): no_legacy_app_key(names) return commands[argv[0]](list(argv[1:]), dict(environ)) except Refused as error: diff --git a/tools/github-app/mint-workflow.yml b/tools/github-app/mint-workflow.yml new file mode 100644 index 000000000..ee294c03a --- /dev/null +++ b/tools/github-app/mint-workflow.yml @@ -0,0 +1,154 @@ +name: OpenWiz Token Service + +on: + workflow_dispatch: + inputs: + request: + description: Token-service request JSON with a one-time RSA-3072 answer_key + required: true + type: string + nonce: + description: Random hex id naming this run and its sealed-answer artifact + required: true + type: string + +run-name: openwiz-mint-${{ inputs.nonce }} + +permissions: {} + +jobs: + mint: + if: github.ref == 'refs/heads/main' + environment: token-service + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Checkout pinned OpenWiz + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: openwizdev/OpenWiz + ref: fae200fc89303c2b4872db1164b42813e5b2e6a8 + path: openwiz + persist-credentials: false + + - name: Mint and seal installation token + env: + OPENWIZ_REQUEST: ${{ inputs.request }} + OPENWIZ_NONCE: ${{ inputs.nonce }} + OPENWIZ_GITHUB_APP_KEY: ${{ secrets.OPENWIZ_GITHUB_APP_KEY }} + OPENWIZ_GITHUB_APP_ID: ${{ vars.OPENWIZ_GITHUB_APP_ID }} + OPENWIZ_GITHUB_APP_MODE: ${{ vars.OPENWIZ_GITHUB_APP_MODE }} + run: | + python3 -I - <<'PY' + import base64 + import importlib.util + import json + import os + from pathlib import Path + import re + import shutil + import sys + import tempfile + import time + + if os.environ.get("GITHUB_REF") != "refs/heads/main": + sys.stderr.write("Refused: token service runs on refs/heads/main only.\n") + sys.exit(1) + + nonce = os.environ.get("OPENWIZ_NONCE", "") + if not re.fullmatch(r"[0-9a-f]{16,64}", nonce): + sys.stderr.write("Refused: invalid nonce.\n") + sys.exit(1) + + raw_key = os.environ.pop("OPENWIZ_GITHUB_APP_KEY", "") + raw_id = os.environ.get("OPENWIZ_GITHUB_APP_ID", "") + raw_req = os.environ.get("OPENWIZ_REQUEST", "").encode("utf-8") + api_base_env = os.environ.get("OPENWIZ_GITHUB_API_BASE", "https://api.github.com") + + tools_dir = Path("openwiz/tools/github-app").resolve() + sys.path.insert(0, str(tools_dir)) + import app # noqa: E402 + + spec = importlib.util.spec_from_file_location("token_service", tools_dir / "token-service.py") + token_service = importlib.util.module_from_spec(spec) + spec.loader.exec_module(token_service) + + pem = None + if raw_key: + try: + decoded = base64.b64decode(raw_key.strip().encode("ascii"), validate=True) + if 0 < len(decoded) <= 16384 and decoded.startswith(b"-----BEGIN "): + pem = decoded + except Exception: + pem = None + + def pipe_jwt(_directory, app_id): + app.require(pem is not None and type(app_id) is int and app_id > 0) + now = int(time.time()) + header = app.encode(b'{"alg":"RS256","typ":"JWT"}') + payload = app.encode(json.dumps( + {"iat": now - 60, "exp": now + 540, "iss": str(app_id)}, + separators=(",", ":")).encode()) + msg = header + b"." + payload + r, w = os.pipe() + try: + with os.fdopen(w, "wb") as pipe: + pipe.write(pem) + sig = app.openssl(["dgst", "-sha256", "-sign", f"/dev/fd/{r}"], msg, pass_fds=(r,)) + finally: + os.close(r) + return (msg + b"." + app.encode(sig)).decode("ascii") + + app.jwt = pipe_jwt + + tmp = tempfile.mkdtemp(prefix="openwiz-mint-") + try: + os.chmod(tmp, 0o700) + state = Path(tmp) + app_dir = app.app_directory(state, create=True) + try: + if re.fullmatch(r"[1-9][0-9]*", raw_id): + app.save_file(app_dir, "app.json", json.dumps({"app_id": int(raw_id)}).encode()) + finally: + os.close(app_dir) + svc_dir = token_service.folder(state, create=True) + try: + log_fd = os.open( + token_service.LOG, + os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, + 0o600, + dir_fd=svc_dir, + ) + try: + setting = app.mode() if os.environ.get("OPENWIZ_GITHUB_APP_MODE") else "user" + api = {"state": state, "base": app.api_base(api_base_env)} + message, _code = token_service.serve(api, log_fd, raw_req, setting) + os.lseek(log_fd, 0, os.SEEK_SET) + log_raw = os.read(log_fd, 65536).decode("utf-8", "replace").strip() + finally: + os.close(log_fd) + finally: + os.close(svc_dir) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + out_dir = Path("out") + out_dir.mkdir(mode=0o700, exist_ok=True) + (out_dir / "answer.json").write_text(json.dumps(message) + "\n", encoding="utf-8") + + summary_path = os.environ.get("GITHUB_STEP_SUMMARY") + if summary_path and log_raw: + entry = json.loads(log_raw.splitlines()[-1]) + allowed = ("at", "requester", "repositories", "permissions", "outcome", "expires_at") + fields = {k: entry[k] for k in allowed if k in entry} + with open(summary_path, "a", encoding="utf-8") as handle: + handle.write("```json\n" + json.dumps(fields, sort_keys=True) + "\n```\n") + PY + + - name: Upload sealed answer + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: ${{ inputs.nonce }} + path: out/answer.json + retention-days: 1 + if-no-files-found: error diff --git a/tools/github-app/test_agent_token.py b/tools/github-app/test_agent_token.py index ce4685777..e27c23346 100644 --- a/tools/github-app/test_agent_token.py +++ b/tools/github-app/test_agent_token.py @@ -2381,6 +2381,7 @@ def start_fake(self, mode="ok"): state = {"mode": mode, "dispatches": [], "deleted": [], "redirect_auth": [], "artifacts": [], "logs": [], "rate_hits": 0, "poll_count": 0} owner_repo = "synthetic-owner/private-ops" + other_pub = self.helper.one_time_key()[1] if mode == "unopenable" else None def seal_to(token, key): sealed = b"" @@ -2434,7 +2435,6 @@ def do_POST(self): "sealed_token": "A" * 512, "expires_at": int(time.time()) + 3600, "repositories": ["other/repo"], "permissions": WRITE})) elif state["mode"] == "unopenable": - _, other_pub = self.server.helper.one_time_key() raw = make_zip(json.dumps({"schema": "openwiz.token-service.v1", "kind": "answer", "sealed_token": seal_to(TOKEN, other_pub), "expires_at": int(time.time()) + 3600, diff --git a/tools/github-app/test_mint_workflow.py b/tools/github-app/test_mint_workflow.py index a74c21ba8..2ddfcd615 100644 --- a/tools/github-app/test_mint_workflow.py +++ b/tools/github-app/test_mint_workflow.py @@ -9,6 +9,7 @@ import subprocess import sys import tempfile +import time import unittest HERE = Path(__file__).resolve().parent @@ -175,7 +176,7 @@ def test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields(self): script = max(blocks, key=len) private_key, answer_key = helper.one_time_key() self.assertIsNotNone(private_key) - app_pem = ts.throwaway_key() + app_pem = ts.openssl("genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048") request = { "schema": "openwiz.token-service.v1", "kind": "request", @@ -190,7 +191,8 @@ def test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields(self): os.symlink(ROOT, work / "openwiz") summary = work / "summary.md" summary.write_text("") - with ts.fake_github(app_pem, ["synthetic-owner/work"]) as (url, calls, _fake): + with ts.fake_github(app_pem, ["synthetic-owner/work"]) as (url, calls, fake): + fake["expires_at"] = int(time.time()) + 3600 base_env = { "PATH": os.environ.get("PATH", os.defpath), "GITHUB_REF": "refs/heads/feature", From bafaf5a1d05b95bb33a3c81d39fce97d589de3a5 Mon Sep 17 00:00:00 2001 From: jparker2006 <85816763+jparker2006@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:07:57 +0000 Subject: [PATCH 3/3] #3235: fix: keep only allowed comments in the actions route's files (comment check) --- tools/github-app/mint-workflow.yml | 4 ++-- tools/github-app/test_agent_token.py | 8 ++++---- tools/github-app/test_mint_workflow.py | 19 +++---------------- 3 files changed, 9 insertions(+), 22 deletions(-) diff --git a/tools/github-app/mint-workflow.yml b/tools/github-app/mint-workflow.yml index ee294c03a..95ddf44a5 100644 --- a/tools/github-app/mint-workflow.yml +++ b/tools/github-app/mint-workflow.yml @@ -24,7 +24,7 @@ jobs: timeout-minutes: 5 steps: - name: Checkout pinned OpenWiz - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 with: repository: openwizdev/OpenWiz ref: fae200fc89303c2b4872db1164b42813e5b2e6a8 @@ -146,7 +146,7 @@ jobs: PY - name: Upload sealed answer - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 with: name: ${{ inputs.nonce }} path: out/answer.json diff --git a/tools/github-app/test_agent_token.py b/tools/github-app/test_agent_token.py index e27c23346..2c20bae06 100644 --- a/tools/github-app/test_agent_token.py +++ b/tools/github-app/test_agent_token.py @@ -2523,7 +2523,7 @@ def do_DELETE(self): return env, state def test_actions_round_trip_and_deletes_artifact(self): - # catches: broken actions dispatch/poll/download/open flow, non-main dispatch, + # comment-ok: catches: broken actions dispatch/poll/download/open flow, non-main dispatch, # leaking Authorization on redirect, or forgetting to delete the artifact after download. env, state = self.start_fake("ok") private = self.helper.Private(env, create=True) @@ -2537,7 +2537,7 @@ def test_actions_round_trip_and_deletes_artifact(self): self.assertEqual(state["redirect_auth"], [None], "Authorization must not cross artifact redirect") def test_actions_failures_fall_back_with_right_reason(self): - # catches: wrong fallback reason or leaked/undeleted artifact on missing run, timeout, + # comment-ok: catches: wrong fallback reason or leaked/undeleted artifact on missing run, timeout, # failed run, missing/tampered artifact, unopenable answer, or contract refusal. cases = [ ("missing-run", "unreachable", []), @@ -2565,7 +2565,7 @@ def test_actions_failures_fall_back_with_right_reason(self): self.assertEqual(state["deleted"], expected_deleted) def test_actions_backs_off_on_403_and_429(self): - # catches: failing immediately on GitHub 403/429 instead of backing off and retrying. + # comment-ok: catches: failing immediately on GitHub 403/429 instead of backing off and retrying. env, state = self.start_fake("backoff") private = self.helper.Private(env, create=True) self.addCleanup(os.close, private.fd) @@ -2576,7 +2576,7 @@ def test_actions_backs_off_on_403_and_429(self): self.assertEqual(state["deleted"], [701]) def test_actions_never_exposes_plaintext_token(self): - # catches: plaintext token appearing in dispatch inputs, fake run logs, artifact zip, or helper output. + # comment-ok: catches: plaintext token appearing in dispatch inputs, fake run logs, artifact zip, or helper output. env, state = self.start_fake("ok") done = subprocess.run([sys.executable, "-I", str(HELPER), "start", *REQ], env=env, capture_output=True, text=True, timeout=30) diff --git a/tools/github-app/test_mint_workflow.py b/tools/github-app/test_mint_workflow.py index 2ddfcd615..e055e1711 100644 --- a/tools/github-app/test_mint_workflow.py +++ b/tools/github-app/test_mint_workflow.py @@ -1,5 +1,4 @@ #!/usr/bin/env python3 -"""Offline security and execution proofs for tools/github-app/mint-workflow.yml (#3235).""" import base64 import importlib.util import json @@ -22,7 +21,6 @@ def pinned_openwiz_actions(): - """Return {action_name: set(shas)} already pinned across OpenWiz's own workflows.""" pinned = {} for path in sorted(WORKFLOWS.glob("*.yml")): for line in path.read_text().splitlines(): @@ -36,7 +34,6 @@ def pinned_openwiz_actions(): def extract_run_blocks(text): - """Extract every `run:` command (inline or block scalar) from a workflow YAML.""" lines = text.splitlines() blocks, i = [], 0 while i < len(lines): @@ -64,10 +61,8 @@ def extract_run_blocks(text): def check_template(text, allowed_actions): - """Return a list of security violations in a mint-workflow.yml text.""" errors = [] lines = text.splitlines() - # 1. Top-level `on:` must contain only `workflow_dispatch`. on_idx = next((i for i, l in enumerate(lines) if re.match(r"^on:\s*$", l)), None) if on_idx is None: errors.append("missing top-level on: block") @@ -81,12 +76,10 @@ def check_template(text, allowed_actions): triggers.append(m.group(1)) if triggers != ["workflow_dispatch"]: errors.append(f"triggers must be workflow_dispatch only, got {triggers!r}") - # 2. Key job must name environment: token-service and guard github.ref == 'refs/heads/main'. if not re.search(r"(?m)^\s{4}environment:\s*token-service\s*$", text): errors.append("missing job environment: token-service") if not re.search(r"(?m)^\s{4}if:\s*(?:\$\{\{\s*)?github\.ref\s*==\s*'refs/heads/main'(?:\s*\}\})?\s*$", text): errors.append("missing job-level refs/heads/main guard") - # 3. OpenWiz checkout must pin a 40-hex commit SHA (never a branch). checkout_ok = False for i, l in enumerate(lines): if re.match(r"^\s+repository:\s*openwizdev/OpenWiz\s*$", l): @@ -100,7 +93,6 @@ def check_template(text, allowed_actions): break if not checkout_ok: errors.append("openwizdev/OpenWiz checkout must pin a 40-hex commit sha") - # 4. Every `uses:` must be actions/checkout or actions/upload-artifact at an OpenWiz-pinned SHA. allowed_names = {"actions/checkout", "actions/upload-artifact"} uses_found = [] for l in lines: @@ -119,14 +111,12 @@ def check_template(text, allowed_actions): errors.append(f"action sha not pinned in OpenWiz workflows: {spec}") if not uses_found: errors.append("no uses: steps found") - # 5. No `${{ }}` expression (especially inputs) inside any `run:` block. run_blocks = extract_run_blocks(text) if not run_blocks: errors.append("no run: block found") for block in run_blocks: if EXPR_RE.search(block): errors.append("expression ${{ }} found inside a run: block") - # 6. Artifact upload retention-days: 1. if not re.search(r"(?m)^\s+retention-days:\s*1\s*$", text): errors.append("missing artifact retention-days: 1") return errors @@ -134,14 +124,14 @@ def check_template(text, allowed_actions): class MintWorkflowTemplate(unittest.TestCase): def test_template_passes_all_security_guards(self): - # catches: missing workflow template, non-dispatch trigger, missing token-service env, + # comment-ok: catches: missing workflow template, non-dispatch trigger, missing token-service env, # unpinned OpenWiz checkout, ${{ inputs }} in run:, or unpinned/foreign action uses. self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") errors = check_template(TEMPLATE.read_text(), pinned_openwiz_actions()) self.assertEqual(errors, [], f"template failed guards: {errors}") def test_template_guard_catches_every_planted_violation(self): - # catches: a template guard that passes even when a security invariant is broken. + # comment-ok: catches: a template guard that passes even when a security invariant is broken. self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") good = TEMPLATE.read_text() allowed = pinned_openwiz_actions() @@ -161,7 +151,7 @@ def test_template_guard_catches_every_planted_violation(self): class MintWorkflowExecution(unittest.TestCase): def test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields(self): - # catches: a workflow script that writes the App key to disk, leaks the plaintext token + # comment-ok: catches: a workflow script that writes the App key to disk, leaks the plaintext token # to stdout/stderr/summary/artifact, accepts non-main refs, or fails to seal per #3085. self.assertTrue(TEMPLATE.is_file(), "tools/github-app/mint-workflow.yml is missing") spec = importlib.util.spec_from_file_location("test_token_service", HERE / "test_token_service.py") @@ -204,14 +194,12 @@ def test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields(self): "OPENWIZ_GITHUB_APP_MODE": "user", "OPENWIZ_GITHUB_API_BASE": url, } - # Non-main ref must be refused before any GitHub call. bad = subprocess.run(["sh", "-eu", "-c", script], cwd=work, env=base_env, capture_output=True, text=True, timeout=30) self.assertNotEqual(bad.returncode, 0, "non-main ref must fail") self.assertEqual(calls, [], "non-main ref must make no GitHub call") self.assertFalse((work / "out" / "answer.json").exists()) - # Main ref mints and seals, writes only mint-log fields to summary, never writes key. good = subprocess.run(["sh", "-eu", "-c", script], cwd=work, env=dict(base_env, GITHUB_REF="refs/heads/main"), capture_output=True, text=True, timeout=30) @@ -229,7 +217,6 @@ def test_workflow_run_seals_token_via_pipe_and_logs_only_mint_fields(self): for blob in (good.stdout, good.stderr, summary_text, answer_text): self.assertNotIn(token, blob) self.assertNotIn("PRIVATE KEY", blob) - # Summary carries mint-log fields only. self.assertIn("builder-3235", summary_text) self.assertIn("minted", summary_text) self.assertNotIn("sealed_token", summary_text)