From 5fa76a07900e564c930968cee4cd8dcaafc36007 Mon Sep 17 00:00:00 2001 From: Andrew Wilkinson Date: Mon, 9 Nov 2026 17:04:28 +0000 Subject: [PATCH] feat: add inactive conditional Sekko release publisher --- actions/sekko-release-notice/notice.py | 41 ++- actions/sekko-release-notice/publisher.py | 292 ++++++++++++++++++ docs/sekko-release-notices.md | 127 ++++++++ scripts/test-sekko-release-notice.py | 354 ++++++++++++++++++++++ 4 files changed, 806 insertions(+), 8 deletions(-) create mode 100644 actions/sekko-release-notice/publisher.py diff --git a/actions/sekko-release-notice/notice.py b/actions/sekko-release-notice/notice.py index bc671ca..3e27061 100644 --- a/actions/sekko-release-notice/notice.py +++ b/actions/sekko-release-notice/notice.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Send one bounded notice. No private imports, subprocesses, proxies, or redirects.""" +"""Sign one bounded notice; HTTPS by default, trusted publisher injection only.""" from __future__ import annotations @@ -72,11 +72,15 @@ def endpoint(value): return value -def configuration(raw, encoded_key): +def configuration(raw, encoded_key, *, require_inbox=True): config = document(raw.encode("utf-8")) - if set(config) != {"inbox_url", "scope_id", "target_id", "surface", "origin", "description"}: + fields = {"scope_id", "target_id", "surface", "origin", "description"} + if require_inbox: + fields.add("inbox_url") + if set(config) != fields: raise NoticeError("invalid_config") - endpoint(config["inbox_url"]) + if require_inbox: + endpoint(config["inbox_url"]) if config["origin"] != STAGING_ORIGIN: raise NoticeError("invalid_config") if any(not isinstance(config[name], str) or not IDENTIFIER.fullmatch(config[name]) @@ -129,13 +133,15 @@ def eligible(env): }.items()) -def execute(env, *, persist_payload, transport=request, now=time.time, sleep=time.sleep): +def execute(env, *, persist_payload, transport=request, now=time.time, sleep=time.sleep, + publisher=None): report = {"status": "skipped", "reason": "not_eligible", "attempts": 0} if not eligible(env): return report report.update(status="failed", reason="invalid_config", deployment_outcome="success") try: - config, key = configuration(env.get("SEKKO_NOTICE_CONFIG", ""), env.get("SEKKO_RELEASE_KEY", "")) + config, key = configuration(env.get("SEKKO_NOTICE_CONFIG", ""), env.get("SEKKO_RELEASE_KEY", ""), + require_inbox=publisher is None) sha = env.get("NOTICE_SOURCE_SHA", "") run = env.get("NOTICE_RUN_ID", "") attempt = env.get("NOTICE_RUN_ATTEMPT", "") @@ -169,6 +175,23 @@ def execute(env, *, persist_payload, transport=request, now=time.time, sleep=tim body = canonical({"key_id": "release-ci", "purpose": "release-v1", "payload": payload, "signature": signature}) # Freeze these bytes once: retries must not change timestamp, ID or signature. + if len(body) > MAX_BYTES: + raise NoticeError("invalid_document") + if publisher is not None: + report["attempts"] = 1 + try: + receipt = publisher(event, body) + if (type(receipt) is not dict or set(receipt) != {"status", "version_id", "body_sha256"} + or receipt["status"] != "published" + or receipt["body_sha256"] != hashlib.sha256(body).hexdigest() + or type(receipt["version_id"]) is not str or receipt["version_id"] == "null" + or not re.fullmatch(r"[A-Za-z0-9._~+/=-]{1,1024}", receipt["version_id"])): + raise ValueError() + except Exception: + raise NoticeError("publication_unknown") from None + report.update(status="published", reason="controller_intake_unconfirmed", + body_sha256=receipt["body_sha256"], version_id=receipt["version_id"]) + return report for number in range(1, ATTEMPTS + 1): report["attempts"] = number try: @@ -203,7 +226,7 @@ def write_pending(path, raw): os.fsync(output.fileno()) -def main(*, transport=request, now=time.time, sleep=time.sleep): +def main(*, transport=request, now=time.time, sleep=time.sleep, publisher=None): pending = Path(os.environ["RUNNER_TEMP"]) / "sekko-release-notice-pending.json" # Remove this task's exact stale filename even when the new config is invalid. pending.unlink(missing_ok=True) @@ -213,7 +236,7 @@ def main(*, transport=request, now=time.time, sleep=time.sleep): path.write_bytes(canonical({"status": "failed", "reason": "interrupted", "attempts": 0}) + b"\n") path.chmod(0o600) report = execute(os.environ, persist_payload=lambda raw: write_pending(pending, raw), - transport=transport, now=now, sleep=sleep) + transport=transport, now=now, sleep=sleep, publisher=publisher) path.write_bytes(canonical(report) + b"\n") with open(os.environ["GITHUB_OUTPUT"], "a") as output: output.write("status=" + report["status"] + "\n") @@ -222,6 +245,8 @@ def main(*, transport=request, now=time.time, sleep=time.sleep): summary.write("Sekko release-notice delivery gap: **" + report["reason"] + "**. Deployment outcome is separate; do not redeploy to resend. " "See the safe report and unsigned pending payload artifacts if present.\n") + elif report["status"] == "published": + summary.write("Sekko release notice: published to object storage; controller intake unconfirmed.\n") else: summary.write("Sekko release notice: " + report["status"] + ".\n") if report["status"] == "failed": diff --git a/actions/sekko-release-notice/publisher.py b/actions/sekko-release-notice/publisher.py new file mode 100644 index 0000000..bcd7b86 --- /dev/null +++ b/actions/sekko-release-notice/publisher.py @@ -0,0 +1,292 @@ +"""Inactive trusted CI publisher. Object storage is not a controller queue ACK. + +No operation, credential discovery or CLI execution occurs on construction. +Only trusted code may supply activation, qualification and the dedicated OIDC +identity; the notice, action inputs and ambient environment cannot select them. +""" + +from __future__ import annotations + +import base64 +from dataclasses import dataclass, field +import hashlib +import json +import os +from pathlib import Path +import re +import selectors +import signal +import stat +import subprocess +import tempfile +import threading +import time + +BUCKET = "zkp2p-sekko-releases-411399509833-us-east-1" +PREFIX = "notices/v1/pay-api/staging/" +REGION = "us-east-1" +OWNER = "411399509833" +PUBLICATION_ROLE = "arn:aws:iam::411399509833:role/sekko-release-publisher" +MAX_BODY = 65_536 +MAX_OUTPUT = 131_072 # Combined stdout/stderr, never raw logged. +MAX_TOKEN = 16_384 +MAX_SCRATCH = 262_144 +MAX_FILES = 64 +COMMAND_SECONDS = 5 +_EVENT = re.compile(r"pay:staging:[1-9][0-9]{0,19}:[1-9][0-9]{0,19}:[a-f0-9]{40}\Z") +_VERSION = re.compile(r"[A-Za-z0-9._~+/=-]{1,1024}\Z") + + +class PublicationError(ValueError): + """Fixed reason only; never external output or credential text.""" + + +class PublicationInactive(PublicationError): + pass + + +class PublicationUnknown(PublicationError): + """No success proof; this may include a successfully stored object.""" + + +@dataclass(frozen=True) +class OidcPublicationIdentity: + role_arn: str + token: bytes = field(repr=False) + + def __post_init__(self): + if (type(self.role_arn) is not str or self.role_arn != PUBLICATION_ROLE + or type(self.token) is not bytes or not 1 <= len(self.token) <= MAX_TOKEN + or not re.fullmatch(rb"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", self.token)): + raise PublicationError("invalid_publication_identity") + + +@dataclass(frozen=True) +class CommandResult: + returncode: int + stdout: bytes = field(repr=False) + + +def object_key(event_id): + if type(event_id) is not str or not _EVENT.fullmatch(event_id): + raise PublicationError("invalid_publication_event") + return PREFIX + hashlib.sha256(event_id.encode("ascii")).hexdigest() + ".json" + + +def _document(raw): + def pairs(items): + result = {} + for key, value in items: + if key in result: + raise ValueError() + result[key] = value + return result + + return json.loads(raw, object_pairs_hook=pairs, + parse_constant=lambda _: (_ for _ in ()).throw(ValueError())) + + +def _stop_group(process): + # The owned group may outlive its leader. Never use leader exit as proof + # that descendants stopped, or wait for the leader instead of the group. + def signal_group(sig): + try: + os.killpg(process.pid, sig) + except ProcessLookupError: + return False + except PermissionError: + if sig == signal.SIGKILL: + raise PublicationUnknown("publication_unknown") from None + return True + + def wait_for_group_exit(seconds): + deadline = time.monotonic() + seconds + while True: + process.poll() + if not signal_group(0): + return True + if time.monotonic() >= deadline: + return False + time.sleep(0.01) + + def kill_and_confirm(): + if signal_group(signal.SIGKILL) and not wait_for_group_exit(1): + raise PublicationUnknown("publication_unknown") + + try: + if signal_group(signal.SIGTERM) and not wait_for_group_exit(0.2): + kill_and_confirm() + finally: + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + kill_and_confirm() + try: + process.wait(timeout=1) + except subprocess.TimeoutExpired: + raise PublicationUnknown("publication_unknown") from None + + +def _check_scratch(root): + total, entries, pending = 0, 0, [root] + while pending: + with os.scandir(pending.pop()) as children: + for child in children: + entries += 1 + info = child.stat(follow_symlinks=False) + if entries > MAX_FILES: + raise PublicationUnknown("publication_unknown") + if stat.S_ISDIR(info.st_mode): + pending.append(child.path) + elif stat.S_ISREG(info.st_mode): + total += info.st_size + if total > MAX_SCRATCH: + raise PublicationUnknown("publication_unknown") + else: + raise PublicationUnknown("publication_unknown") + + +class BoundedCliRunner: + """Pipes provide backpressure; output never grows an unbounded scratch file.""" + + def __call__(self, argv, *, cwd, env): + process = subprocess.Popen(argv, cwd=cwd, env=env, stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + start_new_session=True, close_fds=True) + try: + deadline, count, chunks = time.monotonic() + COMMAND_SECONDS, 0, [] + with selectors.DefaultSelector() as selector: + for stream in (process.stdout, process.stderr): + os.set_blocking(stream.fileno(), False) + selector.register(stream, selectors.EVENT_READ) + while selector.get_map(): + _check_scratch(cwd) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise PublicationUnknown("publication_unknown") + for key, _ in selector.select(min(remaining, 0.05)): + raw = os.read(key.fd, min(8192, MAX_OUTPUT + 1 - count)) + count += len(raw) + if count > MAX_OUTPUT: + raise PublicationUnknown("publication_unknown") + if not raw: + selector.unregister(key.fileobj) + elif key.fileobj is process.stdout: + chunks.append(raw) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise PublicationUnknown("publication_unknown") + process.wait(timeout=remaining) + _check_scratch(cwd) + return CommandResult(process.returncode, b"".join(chunks)) + finally: + try: + _stop_group(process) + finally: + process.stdout.close() + process.stderr.close() + + +def _private_file(path, raw): + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(descriptor, "wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + + +class AwsCliPublisher: + """One conditional PUT per call; no reads, discovery, retries or fallback. + + Qualification is an external deployment decision, not inferred from a CLI + version or a caller-provided identity. The role must be a separately reviewed + dedicated publication role; this module cannot establish its IAM policy. + """ + + def __init__(self, cli_path, *, expected_version, identity=None, activated=False, + qualified=False, runner=None): + if (not isinstance(cli_path, (str, Path)) or not Path(cli_path).is_absolute() + or type(expected_version) is not str + or not re.fullmatch(r"2\.[0-9]+\.[0-9]+", expected_version) + or type(activated) is not bool or type(qualified) is not bool + or identity is not None and type(identity) is not OidcPublicationIdentity): + raise PublicationError("invalid_publication_configuration") + self.cli_path, self.expected_version = Path(cli_path), expected_version + self.identity, self.activated, self.qualified = identity, activated, qualified + self.runner = BoundedCliRunner() if runner is None else runner + if not callable(self.runner): + raise PublicationError("invalid_publication_configuration") + self._lock = threading.Lock() + + def _environment(self, root): + home = root / "home" + home.mkdir(mode=0o700) + config, credentials, token = root / "config", root / "credentials", root / "oidc" + for path, raw in ((config, b""), (credentials, b""), (token, self.identity.token)): + _private_file(path, raw) + return {"PATH": "/usr/bin:/bin", "HOME": str(home), "LANG": "C", "LC_ALL": "C", "NO_PROXY": "*", + "AWS_CONFIG_FILE": str(config), "AWS_SHARED_CREDENTIALS_FILE": str(credentials), + "BOTO_CONFIG": str(credentials), "AWS_ROLE_ARN": self.identity.role_arn, + "AWS_WEB_IDENTITY_TOKEN_FILE": str(token), "AWS_ROLE_SESSION_NAME": "sekko-release-publisher", + "AWS_REGION": REGION, "AWS_DEFAULT_REGION": REGION, "AWS_PAGER": "", + "AWS_CLI_AUTO_PROMPT": "off", "AWS_MAX_ATTEMPTS": "1", "AWS_RETRY_MODE": "standard", + "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS": "true", "AWS_EC2_METADATA_DISABLED": "true", + "AWS_STS_REGIONAL_ENDPOINTS": "regional"} + + def __call__(self, event_id, body): + if self.activated is not True or self.qualified is not True or self.identity is None: + raise PublicationInactive("publication_inactive") + key = object_key(event_id) + if type(body) is not bytes or not 1 <= len(body) <= MAX_BODY: + raise PublicationError("invalid_publication_body") + try: + envelope = _document(body) + if (type(envelope) is not dict or set(envelope) != {"key_id", "purpose", "payload", "signature"} + or envelope["key_id"] != "release-ci" or envelope["purpose"] != "release-v1" + or type(envelope["payload"]) is not dict or envelope["payload"].get("event_id") != event_id + or type(envelope["signature"]) is not str + or not re.fullmatch(r"[a-f0-9]{64}", envelope["signature"])): + raise ValueError() + except (ValueError, UnicodeError, RecursionError): + raise PublicationError("invalid_publication_body") from None + digest = hashlib.sha256(body).digest() + checksum = base64.b64encode(digest).decode("ascii") + try: + # Private, bounded scratch disappears on every normal/error path. + # Serialized calls do not share body/token/config files. + with self._lock, tempfile.TemporaryDirectory(prefix="sekko-release-publish-") as directory: + root = Path(directory) + env = self._environment(root) + _private_file(root / "body", body) + result = self.runner((str(self.cli_path), "--version"), cwd=root, env=env) + if (type(result) is not CommandResult or type(result.returncode) is not int + or result.returncode != 0 or type(result.stdout) is not bytes + or not 1 <= len(result.stdout) <= 2048 + or result.stdout.decode("ascii").split()[0] != f"aws-cli/{self.expected_version}"): + raise PublicationUnknown("publication_unknown") + request = {"Bucket": BUCKET, "Key": key, "IfNoneMatch": "*", "ExpectedBucketOwner": OWNER, + "ContentLength": len(body), "ContentType": "application/json", + "ChecksumAlgorithm": "SHA256", "ChecksumSHA256": checksum} + argv = (str(self.cli_path), "s3api", "put-object", "--cli-input-json", + json.dumps(request, separators=(",", ":")), "--body", str(root / "body"), + "--region", REGION, "--endpoint-url", "https://s3.us-east-1.amazonaws.com", + "--output", "json", "--no-cli-pager", "--no-cli-auto-prompt", + "--cli-connect-timeout", "2", "--cli-read-timeout", "2") + result = self.runner(argv, cwd=root, env=env) + if (type(result) is not CommandResult or type(result.returncode) is not int + or result.returncode != 0 or type(result.stdout) is not bytes + or not 1 <= len(result.stdout) <= MAX_OUTPUT): + raise PublicationUnknown("publication_unknown") + receipt = _document(result.stdout) + version = receipt.get("VersionId") if type(receipt) is dict else None + if (type(version) is not str or version == "null" or not _VERSION.fullmatch(version) + or receipt.get("ChecksumSHA256") != checksum + or receipt.get("ChecksumType", "FULL_OBJECT") != "FULL_OBJECT"): + raise PublicationUnknown("publication_unknown") + return {"status": "published", "version_id": version, "body_sha256": digest.hex()} + except PublicationUnknown: + raise + except Exception: + # Includes lost ACK, process cleanup failure, 409/412, malformed + # response and local I/O failure. No alternate key or second PUT. + raise PublicationUnknown("publication_unknown") from None diff --git a/docs/sekko-release-notices.md b/docs/sekko-release-notices.md index 2a8b731..e07027e 100644 --- a/docs/sekko-release-notices.md +++ b/docs/sekko-release-notices.md @@ -200,3 +200,130 @@ lost acknowledgements, unsigned-payload persistence before signing, stale cleanu and safe gap evidence. No live inbox/readiness/deployment/provider/model is called. The existing deploy harness additionally requires Docker and its pinned yq image; missing tools are verification gaps, not live-test permission. + +## Inactive S3 publisher library + +`actions/sekko-release-notice/publisher.py` adds an inactive standard-library +adapter for the separately reviewed Sekko release-pull intake. It is not wired +into the action, reusable workflow, Pay callers, roles or secrets. The action's +command-line entry point still selects HTTPS only. No CLI is run and no +credentials are discovered on import or construction. This draft does not +activate publication or establish that a controller is polling. + +The destination is fixed in code: + +- Bucket: `zkp2p-sekko-releases-411399509833-us-east-1` +- Prefix: `notices/v1/pay-api/staging/` +- Expected owner: `411399509833`; region: `us-east-1` +- Object key: prefix + lowercase SHA-256 of the ASCII stable event ID + `.json` + +The flat hash key contains no timestamp or raw event fields. The signed payload +still contains the original event identity. No endpoint, bucket, prefix, region, +profile or role can be selected through a notice or action input. + +The library interfaces are: + +- `OidcPublicationIdentity(role_arn, token)`: an explicit trusted-construction + value containing the exact proposed role ARN + `arn:aws:iam::411399509833:role/sekko-release-publisher` and bounded OIDC JWT + bytes. Other roles, including the existing deployment role, are rejected. + This name is a proposed binding, not evidence that the role exists or is safe. + The token is excluded from its representation. Syntax validation is + not token verification or evidence of a dedicated IAM policy. +- `AwsCliPublisher(cli_path, *, expected_version, identity=None, + activated=False, qualified=False, runner=None)`: requires an absolute CLI path + and exact `2.x.y` version. Both booleans must be explicitly true and a trusted + identity must be supplied before any CLI execution is possible. `runner` is a + trusted testing seam, never a field in the notice. +- `publisher(event_id, signed_envelope_bytes)`: consumes the exact frozen bytes, + bounded to 65,536 bytes, and returns only `status: published`, `version_id` and + the hex `body_sha256`. The event must match the envelope's payload. It does not + change, sign or extend the envelope, and does not validate the consumer's scope. +- `notice.execute(..., publisher=None)` and `notice.main(..., publisher=None)`: + trusted Python injection only. `None` retains the existing HTTPS contract and + retries. Supplying a publisher requires the existing config fields **except** + `inbox_url`, which must be omitted. Every existing eligibility, configuration, + signing-key, public readiness/SHA and unsigned-payload persistence gate still + applies before signing or publication. + +A future trusted CI wrapper must separately select a **dedicated short-lived +OIDC publication identity**, then supply it through construction. This adapter +does not reuse the existing deployment role or fetch an OIDC token. It creates +a fresh private HOME, empty AWS config/credentials/Boto files and a mode `0600` +token file from the supplied bytes. Its environment is an allowlist: ambient +profiles, static keys, container credentials, proxy variables, custom endpoints, +CA overrides and Python paths are absent; EC2 metadata credentials are disabled. +The only configured credential provider is explicit web identity for the supplied +role. Actual issuer/audience/subject/expiry, role trust and least-privilege IAM +must be qualified independently; the Python constructor cannot prove them. + +For each call, the adapter first verifies the qualified CLI's exact version, +then performs **one** `s3api put-object` with `IfNoneMatch: *`, the fixed expected +owner, exact content length, JSON content type and the base64 SHA-256 checksum of +the original envelope bytes, using documented +[PutObject fields](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-object.html). +The regional S3 endpoint is fixed and uses CLI +default TLS verification. AWS retries are disabled (`AWS_MAX_ATTEMPTS=1`), with +two-second connect/read timeouts and a five-second total limit per subprocess. +No shell, pager, prompt, Get, List, identity probe or installation is used. + +Success requires a nonempty, non-`null`, bounded version ID and a returned +`ChecksumSHA256` matching the original bytes. An ETag is not checksum proof. +An explicitly non-full-object checksum is rejected. Conditional errors 409/412, +timeouts, lost acknowledgements, missing/malformed proof, CLI failures and cleanup +failures all raise the fixed `PublicationUnknown("publication_unknown")`. +The adapter neither retries a PUT nor chooses another key. It has no cross-run +delivery journal: another separately authorized invocation still makes at most +one conditional PUT and may return unknown. The write-only role has no Get/List +proof with which to turn an existing object or lost ACK into confirmed success. + +The runner captures stdout/stderr through backpressured pipes, with a combined +131,072-byte bound; stderr is discarded and no raw output is logged. Private +scratch contains the bounded body, at most 16,384 token bytes and empty config +files; output is not spooled to disk. While running and on completion, scratch +is checked for at most 64 entries and 262,144 regular-file bytes; symlinks and +special files fail closed. The check is sampled at intervals up to 50ms, rather +than an OS disk quota. Scratch is removed on success and failure. +Each child starts an owned process group; cleanup signals the group even after +its leader exits, waits a 200ms grace and kills remaining descendants. After +SIGKILL it probes for group disappearance for at most one second; an exited +leader alone is insufficient. Unconfirmed group cleanup produces +`publication_unknown`, even with valid storage metadata. These +are lifecycle bounds for a trusted, qualified CLI, not an OS sandbox. Runner +loss or forced termination can prevent normal scratch cleanup; runner isolation +and cleanup remain deployment requirements. + +On confirmed storage proof, `notice` reports `status: published` and +`reason: controller_intake_unconfirmed`, with the safe hash/version reference. +It never reports `queued`, `duplicate` or `delivered` from S3 metadata. On any +unconfirmed publisher outcome it reports `failed / publication_unknown`, makes +no retry, and retains the same unsigned pending payload and deployment success. +No response body, OIDC token, signing key, signature or signed envelope appears +in logs or the safe report. Only the controller's signed-release/scope +validation and durable queue receipt can establish intake. + +S3 conditional writes protect the **current** version. A missing current object +or a current delete marker can permit another write to the same key; versioning +alone is not permanent immutability, as described in +[S3 conditional-write semantics](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html). +The actual bucket versioning, retention, +delete protection and create-only IAM policy must be reviewed before activation. +There is no retry timestamp, alternate-key recovery or publisher readback in +this unit. Never rerun deployment or regenerate timestamps to resend an unknown +publication. Preserve the original unsigned payload/signature inputs and expiry; +operator reconciliation and any recovery publication require a separate decision. + +Live qualification remains gated on a pinned/qualified CLI artifact, an isolated +CI execution environment, a separately selected OIDC publication role with exact +trust and destination permissions, actual service identity/network behavior, +immutable version/checksum behavior, and independent controller intake proof. +Publisher IAM must not inherit the deployment role or gain Get/List as an +unreviewed recovery convenience. No role, workflow permission, secret, caller +adoption or actual AWS CLI/cloud call is added by this draft. + +The existing native test script also runs synthetic publisher/CLI fixtures for +activation denial, clean environment/identity selection, exact key/checksum and +frozen body, body/output limits, pin mismatch, version/checksum rejection, +409/412/lost ACK uncertainty, scratch/group cleanup, all prior HTTPS behavior, +and distinct publication/deployment/controller outcomes. Test CLI versions and +OIDC values are public fixtures, not qualified deployment configuration. diff --git a/scripts/test-sekko-release-notice.py b/scripts/test-sekko-release-notice.py index 652c910..319cc53 100644 --- a/scripts/test-sekko-release-notice.py +++ b/scripts/test-sekko-release-notice.py @@ -2,6 +2,7 @@ """Local fixture/injected transport tests only; no sockets or external services.""" import contextlib +import base64 import hashlib import io import hmac @@ -11,6 +12,7 @@ import os from pathlib import Path import subprocess +import sys import tempfile import unittest from unittest.mock import patch @@ -19,6 +21,10 @@ SPEC = importlib.util.spec_from_file_location("notice", ROOT / "actions/sekko-release-notice/notice.py") notice = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(notice) +PUBLISHER_SPEC = importlib.util.spec_from_file_location("publisher", ROOT / "actions/sekko-release-notice/publisher.py") +publisher = importlib.util.module_from_spec(PUBLISHER_SPEC) +sys.modules[PUBLISHER_SPEC.name] = publisher +PUBLISHER_SPEC.loader.exec_module(publisher) SHA = "a" * 40 KEY = "01" * 32 # Public deterministic fixture, never a credential. CONFIG = {"inbox_url": "https://inbox.example.test/v1/releases", "scope_id": "reviewed-scope", @@ -315,5 +321,353 @@ def test_failure_evidence_is_safe_and_does_not_change_deployment(self): self.assertEqual(Path(temp, "sekko-release-notice-report.json").stat().st_mode & 0o777, 0o600) +class PublisherTests(unittest.TestCase): + EVENT = f"pay:staging:41051883943:2:{SHA}" + TOKEN = b"synthetic.ci_oidc.fixture" # Public fake, never a usable identity. + ROLE = "arn:aws:iam::411399509833:role/sekko-release-publisher" # Proposed binding, not provisioned here. + + def setUp(self): + self.calls, self.roots, self.saved = [], [], [] + self.body = notice.canonical({"key_id": "release-ci", "purpose": "release-v1", + "payload": {"event_id": self.EVENT}, "signature": "1" * 64}) + self.checksum = base64.b64encode(hashlib.sha256(self.body).digest()).decode() + self.reply = publisher.CommandResult(0, notice.canonical({"VersionId": "immutable-version+1", + "ChecksumSHA256": self.checksum, "ChecksumType": "FULL_OBJECT"})) + + def runner(self, argv, *, cwd, env): + self.calls.append((argv, dict(env))) + self.roots.append(cwd) + self.assertTrue(cwd.is_dir()) + self.assertEqual(cwd.stat().st_mode & 0o777, 0o700) + self.assertEqual(list(Path(env["HOME"]).iterdir()), []) + self.assertEqual(Path(env["AWS_CONFIG_FILE"]).read_bytes(), b"") + self.assertEqual(Path(env["AWS_SHARED_CREDENTIALS_FILE"]).read_bytes(), b"") + self.assertEqual(Path(env["AWS_WEB_IDENTITY_TOKEN_FILE"]).read_bytes(), self.TOKEN) + for name in ("body", "config", "credentials", "oidc"): + self.assertEqual((cwd / name).stat().st_mode & 0o777, 0o600) + self.assertEqual((cwd / "body").read_bytes(), self.body) + if argv[1:] == ("--version",): + return publisher.CommandResult(0, b"aws-cli/2.31.20 Python/3 fixture\n") + self.saved.append((cwd / "body").read_bytes()) + if isinstance(self.reply, Exception): + raise self.reply + return self.reply + + def client(self, **changes): + options = {"expected_version": "2.31.20", "activated": True, "qualified": True, + "identity": publisher.OidcPublicationIdentity(self.ROLE, self.TOKEN), "runner": self.runner} + options.update(changes) + return publisher.AwsCliPublisher("/qualified/aws", **options) + + def test_inactive_import_construction_and_each_gate_never_execute_cli(self): + for changes in ({"activated": False}, {"qualified": False}, {"identity": None}): + with self.subTest(changes=changes): + client = self.client(**changes) + self.assertEqual(self.calls, []) + with self.assertRaises(publisher.PublicationInactive): + client(self.EVENT, self.body) + self.assertEqual(self.calls, []) + with patch.object(publisher.subprocess, "Popen", side_effect=AssertionError("no CLI")): + publisher.AwsCliPublisher("/qualified/aws", expected_version="2.31.20") + + def test_strict_trusted_configuration_and_no_static_identity_interface(self): + for changes in ({"expected_version": "latest"}, {"expected_version": "2.31.20\n"}, + {"activated": 1}, {"qualified": "true"}, {"identity": {"AWS_ACCESS_KEY_ID": "fake"}}, + {"runner": 1}): + with self.subTest(changes=changes), self.assertRaises(publisher.PublicationError): + self.client(**changes) + with self.assertRaises(publisher.PublicationError): + publisher.AwsCliPublisher("aws", expected_version="2.31.20") + for role, token in ((self.ROLE.replace("411399509833", "000000000000"), self.TOKEN), + ("arn:aws:iam::411399509833:role/peer-deploy", self.TOKEN), + (self.ROLE, b"static-key"), (self.ROLE, self.TOKEN * 2000), + (self.ROLE + "\n", self.TOKEN), (self.ROLE, "token")): + with self.subTest(role=role), self.assertRaises(publisher.PublicationError): + publisher.OidcPublicationIdentity(role, token) + self.assertNotIn(self.TOKEN.decode(), repr(publisher.OidcPublicationIdentity(self.ROLE, self.TOKEN))) + + def test_exact_frozen_bytes_fixed_hash_destination_and_one_conditional_put(self): + receipt = self.client()(self.EVENT, self.body) + self.assertEqual(receipt, {"status": "published", "version_id": "immutable-version+1", + "body_sha256": hashlib.sha256(self.body).hexdigest()}) + self.assertEqual(len(self.calls), 2) + argv, env = self.calls[1] + self.assertEqual(argv[:3], ("/qualified/aws", "s3api", "put-object")) + request = json.loads(argv[argv.index("--cli-input-json") + 1]) + self.assertEqual(request, {"Bucket": "zkp2p-sekko-releases-411399509833-us-east-1", + "Key": "notices/v1/pay-api/staging/" + hashlib.sha256(self.EVENT.encode()).hexdigest() + ".json", + "ExpectedBucketOwner": "411399509833", "IfNoneMatch": "*", + "ContentLength": len(self.body), "ContentType": "application/json", + "ChecksumAlgorithm": "SHA256", "ChecksumSHA256": self.checksum}) + self.assertEqual(argv[argv.index("--region") + 1], "us-east-1") + self.assertEqual(argv[argv.index("--endpoint-url") + 1], "https://s3.us-east-1.amazonaws.com") + self.assertEqual(self.saved, [self.body]) + self.assertTrue(all(not root.exists() for root in self.roots)) + for private in (self.body.decode(), self.TOKEN.decode()): + self.assertNotIn(private, repr(argv) + repr(receipt)) + + def test_clean_environment_ignores_ambient_profiles_keys_proxies_endpoints_and_roles(self): + ambient = {"AWS_PROFILE": "personal", "AWS_ACCESS_KEY_ID": "fake-personal", "AWS_SECRET_ACCESS_KEY": "fake", + "AWS_SESSION_TOKEN": "fake", "AWS_ROLE_ARN": "deploy-role", "AWS_ENDPOINT_URL": "http://127.0.0.1", + "HTTPS_PROXY": "http://127.0.0.1", "HTTP_PROXY": "http://127.0.0.1", "ALL_PROXY": "private", + "AWS_CONTAINER_CREDENTIALS_FULL_URI": "http://127.0.0.1", "PYTHONPATH": "ambient", "BOTO_CONFIG": "ambient"} + with patch.dict(os.environ, ambient): + self.client()(self.EVENT, self.body) + env = self.calls[1][1] + for name in ambient: + if name not in ("AWS_ROLE_ARN", "BOTO_CONFIG"): + self.assertNotIn(name, env) + self.assertEqual(env["AWS_ROLE_ARN"], self.ROLE) + self.assertEqual(env["AWS_EC2_METADATA_DISABLED"], "true") + self.assertEqual(env["AWS_MAX_ATTEMPTS"], "1") + self.assertEqual(env["AWS_IGNORE_CONFIGURED_ENDPOINT_URLS"], "true") + self.assertEqual(env["NO_PROXY"], "*") + self.assertTrue(all(not root.exists() for root in self.roots)) + + def test_invalid_or_mismatched_event_and_envelope_do_not_execute_cli(self): + values = [(self.EVENT + "/evil", self.body), (self.EVENT, b""), (self.EVENT, b"x" * 65537), + (self.EVENT, bytearray(self.body)), (self.EVENT, b"{}"), (self.EVENT, b"not-json"), + (self.EVENT, self.body.replace(b"release-v1", b"scope-v1")), + (self.EVENT, self.body.replace(self.EVENT.encode(), b"wrong")), + (self.EVENT, self.body.replace(b'"purpose":"release-v1"', b'"purpose":"release-v1","purpose":"release-v1"'))] + for event, body in values: + with self.subTest(length=len(body)), self.assertRaises(publisher.PublicationError): + self.client()(event, body) + self.assertEqual(self.calls, []) + + def test_body_hard_limit_and_original_whitespace_bytes_are_preserved(self): + self.body += b" " * (65536 - len(self.body)) + self.checksum = base64.b64encode(hashlib.sha256(self.body).digest()).decode() + self.reply = publisher.CommandResult(0, notice.canonical({"VersionId": "v", "ChecksumSHA256": self.checksum})) + self.client()(self.EVENT, self.body) + self.assertEqual(self.saved, [self.body]) + + def test_409_412_timeout_lost_ack_and_nonzero_results_are_unknown_without_retry(self): + for reply in (TimeoutError("private lost ACK"), OSError("private"), + publisher.CommandResult(409, b"private conflict"), publisher.CommandResult(412, b"private exists"), + publisher.CommandResult(1, b"private credentials"), publisher.CommandResult(True, b"{}")): + self.calls, self.saved = [], [] + self.reply = reply + with self.subTest(reply=type(reply)), self.assertRaisesRegex(publisher.PublicationUnknown, "^publication_unknown$"): + self.client()(self.EVENT, self.body) + self.assertEqual(len(self.calls), 2) + self.assertEqual(self.saved, [self.body]) + self.assertTrue(all(not root.exists() for root in self.roots)) + + def test_missing_malformed_or_mismatched_immutable_proof_never_succeeds(self): + valid = {"VersionId": "v", "ChecksumSHA256": self.checksum} + fixtures = [b"{}", b"[]", b"not-json", b"x" * (publisher.MAX_OUTPUT + 1), + b'{"VersionId":"v","VersionId":"v"}', b'{"VersionId":NaN}'] + for version in (None, "", "null", True, "x" * 1025, "v\n"): + fixtures.append(notice.canonical({**valid, "VersionId": version})) + fixtures += [notice.canonical({"VersionId": "v"}), notice.canonical({**valid, "ChecksumSHA256": "wrong"}), + notice.canonical({**valid, "ChecksumType": "COMPOSITE"})] + for raw in fixtures: + self.calls = [] + self.reply = publisher.CommandResult(0, raw) + with self.subTest(rawlen=len(raw)), self.assertRaises(publisher.PublicationUnknown): + self.client()(self.EVENT, self.body) + self.assertEqual(len(self.calls), 2) + + def test_version_pin_failure_prevents_put_and_cleans_scratch(self): + for reply in (publisher.CommandResult(0, b"aws-cli/2.31.21 fixture"), publisher.CommandResult(0, b""), + publisher.CommandResult(1, b"private"), publisher.CommandResult(0, b"x" * 2049)): + roots = [] + def runner(argv, *, cwd, env): + roots.append(cwd) + self.assertEqual(argv[1:], ("--version",)) + return reply + with self.assertRaises(publisher.PublicationUnknown): + self.client(runner=runner)(self.EVENT, self.body) + self.assertTrue(roots) + self.assertTrue(all(not root.exists() for root in roots)) + + def test_notice_injected_seam_preserves_gates_signing_and_no_https_post(self): + calls, saved, clocks, published = [], [], [], [] + config = {key: value for key, value in CONFIG.items() if key != "inbox_url"} + env = {**ENV, "SEKKO_NOTICE_CONFIG": json.dumps(config)} + def transport(method, url, body=None): + calls.append((method, url)) + self.assertEqual(method, "GET") + return 200, notice.canonical(READY) + def publish(event, body): + self.assertEqual(saved, [notice.canonical(json.loads(body)["payload"])]) + self.assertEqual(event, self.EVENT) + signed = hmac.new(bytes.fromhex(KEY), b"release-v1\x00" + saved[0], hashlib.sha256).hexdigest() + self.assertEqual(json.loads(body)["signature"], signed) + published.append(body) + return {"status": "published", "version_id": "v", "body_sha256": hashlib.sha256(body).hexdigest()} + result = notice.execute(env, persist_payload=saved.append, transport=transport, + publisher=publish, now=lambda: clocks.append(True) or 1000, + sleep=lambda _: self.fail("no publication retry")) + self.assertEqual((result["status"], result["reason"], result["attempts"], result["deployment_outcome"]), + ("published", "controller_intake_unconfirmed", 1, "success")) + self.assertEqual(len(published), 1) + self.assertEqual(clocks, [True]) + self.assertEqual(calls, [("GET", notice.STAGING_ORIGIN + "/readyz")]) + for gate in ("SEKKO_NOTICE_ENABLED", "NOTICE_DEPLOY_RESULT"): + skipped = notice.execute({**env, gate: "false"}, persist_payload=lambda *_: self.fail("persist"), + publisher=lambda *_: self.fail("publish"), transport=lambda *_: self.fail("probe")) + self.assertEqual(skipped["status"], "skipped") + failed = notice.execute(env, persist_payload=lambda *_: self.fail("persist"), + publisher=lambda *_: self.fail("publish"), transport=lambda *_: (503, b"private")) + self.assertEqual(failed["reason"], "readiness_failed") + + def test_unknown_publication_and_invalid_receipt_keep_successful_deployment_and_safe_evidence(self): + for outcome in (TimeoutError("private token and signed envelope"), None, {"status": "queued"}, + {"status": "published", "version_id": "null", "body_sha256": "wrong"}): + with self.subTest(outcome=type(outcome)), tempfile.TemporaryDirectory() as temp: + attempts = [] + def publish(event, body): + attempts.append(body) + if isinstance(outcome, Exception): + raise outcome + return outcome + config = {key: value for key, value in CONFIG.items() if key != "inbox_url"} + env = {**ENV, "SEKKO_NOTICE_CONFIG": json.dumps(config), "RUNNER_TEMP": temp, + "GITHUB_OUTPUT": temp + "/output", "GITHUB_STEP_SUMMARY": temp + "/summary"} + with patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()) as captured: + code = notice.main(transport=lambda *_: (200, notice.canonical(READY)), publisher=publish, + now=lambda: 1000, sleep=lambda _: self.fail("retry")) + report = json.loads(Path(temp, "sekko-release-notice-report.json").read_bytes()) + self.assertEqual(code, 1) + self.assertEqual((report["reason"], report["deployment_outcome"], report["attempts"]), + ("publication_unknown", "success", 1)) + self.assertEqual(len(attempts), 1) + self.assertEqual(Path(temp, "sekko-release-notice-pending.json").read_bytes(), + notice.canonical(json.loads(attempts[0])["payload"])) + combined = captured.getvalue() + json.dumps(report) + Path(temp, "summary").read_text() + for private in (KEY, "private", "signature", CONFIG["description"], CONFIG["inbox_url"]): + self.assertNotIn(private, combined) + self.assertNotIn("queued", combined) + + def test_published_main_reports_storage_only_without_controller_ack(self): + with tempfile.TemporaryDirectory() as temp: + config = {key: value for key, value in CONFIG.items() if key != "inbox_url"} + env = {**ENV, "SEKKO_NOTICE_CONFIG": json.dumps(config), "RUNNER_TEMP": temp, + "GITHUB_OUTPUT": temp + "/output", "GITHUB_STEP_SUMMARY": temp + "/summary"} + def publish(event, body): + return {"status": "published", "version_id": "v", "body_sha256": hashlib.sha256(body).hexdigest()} + with patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()) as captured: + self.assertEqual(notice.main(transport=lambda *_: (200, notice.canonical(READY)), + publisher=publish, now=lambda: 1000), 0) + report = json.loads(Path(temp, "sekko-release-notice-report.json").read_bytes()) + self.assertEqual((report["status"], report["reason"]), ("published", "controller_intake_unconfirmed")) + self.assertEqual(Path(temp, "output").read_text(), "status=published\n") + self.assertIn("controller intake unconfirmed", Path(temp, "summary").read_text()) + self.assertEqual(captured.getvalue(), "") + + def test_bounded_runner_uses_pipes_no_shell_and_cleans_even_exited_leader(self): + process = unittest.mock.MagicMock(pid=123456789, returncode=0) + streams = [] + for raw in (b"ack", b"private stderr"): + reader, writer = os.pipe() + os.write(writer, raw) + os.close(writer) + streams.append(os.fdopen(reader, "rb")) + process.stdout, process.stderr = streams + try: + with tempfile.TemporaryDirectory() as scratch, \ + patch.object(publisher.subprocess, "Popen", return_value=process) as popen, \ + patch.object(publisher.os, "killpg", side_effect=ProcessLookupError()) as kill: + result = publisher.BoundedCliRunner()(("/qualified/aws", "--version"), cwd=Path(scratch), env={}) + self.assertEqual(result, publisher.CommandResult(0, b"ack")) + self.assertNotIn("private", repr(result)) + self.assertTrue(popen.call_args.kwargs["start_new_session"]) + self.assertTrue(popen.call_args.kwargs["close_fds"]) + self.assertNotIn("shell", popen.call_args.kwargs) + self.assertEqual(popen.call_args.kwargs["stdin"], subprocess.DEVNULL) + kill.assert_called_once_with(process.pid, publisher.signal.SIGTERM) + self.assertTrue(all(stream.closed for stream in streams)) + finally: + for stream in streams: + stream.close() + + def test_runner_output_overflow_and_deadline_stop_owned_group(self): + for limit, seconds in ((2, 5), (100, 0)): + process = unittest.mock.MagicMock(pid=123456789, returncode=0) + streams = [] + for raw in (b"oversize", b"private"): + reader, writer = os.pipe() + os.write(writer, raw) + os.close(writer) + streams.append(os.fdopen(reader, "rb")) + process.stdout, process.stderr = streams + try: + with tempfile.TemporaryDirectory() as scratch, \ + patch.object(publisher, "MAX_OUTPUT", limit), patch.object(publisher, "COMMAND_SECONDS", seconds), \ + patch.object(publisher.subprocess, "Popen", return_value=process), \ + patch.object(publisher, "_stop_group") as stop: + with self.assertRaises(publisher.PublicationUnknown): + publisher.BoundedCliRunner()(("/qualified/aws",), cwd=Path(scratch), env={}) + stop.assert_called_once_with(process) + self.assertTrue(all(stream.closed for stream in streams)) + finally: + for stream in streams: + stream.close() + + def test_group_cleanup_kills_remaining_descendants_independently_of_leader(self): + process = unittest.mock.MagicMock(pid=123456789) + process.poll.return_value = 0 + with patch.object(publisher.time, "monotonic", side_effect=range(20)), \ + patch.object(publisher.os, "killpg", side_effect=[None, None, None, ProcessLookupError()]) as kill: + publisher._stop_group(process) + self.assertEqual(kill.call_args_list, [unittest.mock.call(process.pid, publisher.signal.SIGTERM), + unittest.mock.call(process.pid, 0), + unittest.mock.call(process.pid, publisher.signal.SIGKILL), + unittest.mock.call(process.pid, 0)]) + process.wait.assert_called_once_with(timeout=1) + with patch.object(publisher.time, "monotonic", side_effect=range(20)), \ + patch.object(publisher.os, "killpg", side_effect=PermissionError()): + with self.assertRaises(publisher.PublicationUnknown): + publisher._stop_group(process) + + def test_cleanup_cannot_confirm_success_while_group_remains_after_kill(self): + process = unittest.mock.MagicMock(pid=123456789) + process.poll.return_value = 0 + with patch.object(publisher.time, "monotonic", side_effect=range(20)), \ + patch.object(publisher.time, "sleep"), patch.object(publisher.os, "killpg") as kill: + with self.assertRaisesRegex(publisher.PublicationUnknown, "^publication_unknown$"): + publisher._stop_group(process) + self.assertIn(unittest.mock.call(process.pid, publisher.signal.SIGKILL), kill.call_args_list) + process.wait.assert_called_once_with(timeout=1) + + def test_valid_storage_receipt_stays_unknown_if_exited_leader_group_survives_kill(self): + process = unittest.mock.MagicMock(pid=123456789) + process.poll.return_value = 0 + def runner(argv, *, cwd, env): + result = self.runner(argv, cwd=cwd, env=env) + if argv[1:3] == ("s3api", "put-object"): + publisher._stop_group(process) + return result + with patch.object(publisher.time, "monotonic", side_effect=range(20)), \ + patch.object(publisher.time, "sleep"), patch.object(publisher.os, "killpg"): + with self.assertRaisesRegex(publisher.PublicationUnknown, "^publication_unknown$"): + self.client(runner=runner)(self.EVENT, self.body) + self.assertEqual(len(self.calls), 2) + self.assertEqual(self.saved, [self.body]) + self.assertTrue(all(not root.exists() for root in self.roots)) + + def test_scratch_size_entry_count_and_special_files_fail_closed(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "bounded").write_bytes(b"x" * publisher.MAX_SCRATCH) + publisher._check_scratch(root) + with (root / "bounded").open("ab") as stream: + stream.write(b"x") + with self.assertRaises(publisher.PublicationUnknown): + publisher._check_scratch(root) + (root / "bounded").unlink() + for number in range(publisher.MAX_FILES + 1): + (root / str(number)).touch() + with self.assertRaises(publisher.PublicationUnknown): + publisher._check_scratch(root) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "link").symlink_to("/nonexistent-fixture") + with self.assertRaises(publisher.PublicationUnknown): + publisher._check_scratch(root) + + if __name__ == "__main__": unittest.main()