#!/usr/bin/env python3 """One attended founder approval/login for the reviewed platform SMTP reader. Default is read-only. Does not switch the sender, read inboxes or submit mail. """ from __future__ import annotations import argparse import hashlib import importlib import json import os import subprocess import sys import urllib.request from datetime import UTC, datetime from pathlib import Path PLATFORM = Path("/home/worsch/railiance-platform") EXPECTED = "sha256:d9f8785060db902f969e5d8d0917494858b2114e8f93ae812dda3a059c090844" CCR = "CCR-2026-0056" HUB = "http://127.0.0.1:8000" PHRASE = "ADMIT PLATFORM SMTP" SCOPE = ( "As founder, platform owner and email-connect owner, admit email-connect as a third " "reader of the existing platform SMTP record alongside telemetry and Authelia. " "The new role reads that whole exact record; ESO projects only SMTP_PASSWORD. " "Tokens last at most 15 minutes. Preserve the mailbox and existing readers. " "This step creates the scoped projection and verifies SMTP AUTH without sending mail. " "It grants no IMAP access, suppression caller or additional transactional template." ) def require(condition, message): if not condition: raise RuntimeError(message) def owner(): sys.dont_write_bytecode = True sys.path.insert(0, str(PLATFORM / "scripts")) return importlib.import_module("email_connect_smtp_foundation") def preflight(foundation, expected_status="proposed"): ccr, proposal, value = foundation.prepare() require(value == EXPECTED, "Proposal changed; refresh the review before execution") require(ccr["status"] == expected_status, "Existing CCR state requires inspection") native = foundation.Native() bundle = proposal["foundation"] for name, key in (("kube-system", "cluster_uid"), ("email-connect", "namespace_uid")): obj = native.get("namespace", name, namespace=None) require(obj and obj["metadata"]["uid"] == bundle[key], "Cluster identity changed") before = foundation.protected_application(native, bundle) for wanted in bundle["resources"]: require( native.get(wanted["kind"], wanted["metadata"]["name"]) is None, "Existing target requires inspection", ) require( native.target_metadata("email-connect-platform-smtp") is None, "Existing target Secret requires inspection", ) return ccr, proposal, before def write_private(path, value): fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, "w") as stream: json.dump(value, stream, indent=2) stream.write("\n") stream.flush() os.fsync(stream.fileno()) fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) try: os.fsync(fd) finally: os.close(fd) def private_json(path): info = path.lstat() require( path.is_file() and info.st_uid == os.getuid() and not info.st_mode & 0o077 and not any(p.is_symlink() for p in (path, *path.parents)), "Private original receipt required", ) return json.loads(path.read_text()) def _attempt_incomplete(path): return ( (path / "approval.json").is_file() and not (path / "outcome.json").exists() and not (path / "foundation.jsonl").exists() ) def _attempt_login_failed(path): outcome_path = path / "outcome.json" if not outcome_path.is_file() or (path / "foundation.jsonl").exists(): return False outcome = json.loads(outcome_path.read_text()) return outcome.get("warden_exit_code") == 10 and outcome.get("proposal_digest") == EXPECTED def next_retry_directory(original): """Keep each login attempt. A finished exit 10 may be followed once more.""" first = original / "login-retry-01" if not first.exists(): return first second = original / "login-retry-02" if not second.exists(): if (first / "outcome.json").exists(): require( _attempt_login_failed(first), "Earlier login retry has an outcome and requires inspection", ) else: require( _attempt_incomplete(first), "Earlier login retry has an outcome and requires inspection", ) return second third = original / "login-retry-03" require(not third.exists(), "The preserved third login attempt requires inspection") require(_attempt_login_failed(second), "The preserved second login attempt requires inspection") if (first / "outcome.json").exists(): require( _attempt_login_failed(first), "Earlier login retry has an outcome and requires inspection", ) else: require( _attempt_incomplete(first), "Earlier login retry has an outcome and requires inspection", ) return third def retry_login(foundation): require(sys.stdin.isatty(), "Run this command in your own terminal") original = Path.home() / ".local/state/coulomb-social" / ("smtp-" + EXPECTED[7:]) approval = private_json(original / "approval.json") outcome = private_json(original / "outcome.json") require( approval.get("proposal_digest") == outcome.get("proposal_digest") == EXPECTED and approval.get("scope") == SCOPE and outcome.get("warden_exit_code") == 10 and not (original / "foundation.jsonl").exists(), "Only a proven pre-controller login failure can use this retry", ) ccr, proposal, before = preflight(foundation, expected_status="approved") require( before == approval["protected_application"], "Application changed since admission review" ) decision_id = ccr.get("state_hub", {}).get("decision_id") require(decision_id == outcome.get("decision_id"), "Original founder decision changed") validator = foundation.admission.module( "attended_retry_ccr", PLATFORM / "scripts/credential-change.py" ) decision = validator.state_hub_get_json(HUB, "/decisions/" + decision_id) require( decision.get("status") == "resolved" and decision.get("decided_by") == "Bernd Worsch" and decision.get("rationale", "").startswith("APPROVE:") and EXPECTED in decision["rationale"], "Original exact founder approval required", ) print("Reusing your recorded approval; completing only the outstanding private-browser login.") print("Close every Edge window first. This attempt uses a new empty browser profile.") print("Sign in as platform-root throughout. Close the window if it shows tegwick.") print("After the one-time code, click Continue on the page titled You are signed in.") directory = next_retry_directory(original) directory.mkdir(mode=0o700) intent = { **approval, "retry_of": str(original / "outcome.json"), "retry_started_at": datetime.now(UTC).isoformat(), "launcher_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "foundation_receipt": str(directory / "foundation.jsonl"), } write_private(directory / "approval.json", intent) return run_controller( foundation, proposal, before, directory, intent, decision_id, private_browser=True ) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) actions = parser.add_mutually_exclusive_group() actions.add_argument("--execute", action="store_true") actions.add_argument("--retry-login", action="store_true") args = parser.parse_args(argv) require(__debug__, "Optimized Python is unsupported") foundation = owner() if args.retry_login: return retry_login(foundation) ccr, proposal, before = preflight(foundation) print(SCOPE) print("Reviewed proposal:", EXPECTED) if not args.execute: print("Read-only preflight passed; no approval or runtime changes made.") return 0 require(sys.stdin.isatty(), "Run this command in your own terminal") require( input(f"Type {PHRASE} to approve this exact scope: ").strip() == PHRASE, "Approval not given", ) # Recheck after human review; do not approve or write a journal for stale scope. ccr, proposal, second = preflight(foundation) require(second == before, "Application changed during review") directory = Path.home() / ".local/state/coulomb-social" / ("smtp-" + EXPECTED[7:]) directory.parent.mkdir(mode=0o700, parents=True, exist_ok=True) info = directory.parent.lstat() require( info.st_uid == os.getuid() and not info.st_mode & 0o077 and not any(p.is_symlink() for p in (directory.parent, *directory.parent.parents)), "Private caller-owned state directory required", ) directory.mkdir(mode=0o700) # Exclusive: a lost response requires inspection. receipt = directory / "foundation.jsonl" intent = { "schema": "coulomb.attended-smtp-admission.v1", "proposal_digest": EXPECTED, "approved_at": datetime.now(UTC).isoformat(), "approved_by": "Bernd Worsch (attended founder/platform/email-connect owner)", "scope": SCOPE, "protected_application": before, "launcher_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "foundation_receipt": str(receipt), } write_private(directory / "approval.json", intent) validator = foundation.admission.module( "attended_ccr", PLATFORM / "scripts/credential-change.py" ) intake = foundation.admission.module("attended_intake", PLATFORM / "scripts/ccr_intake.py") # This runs in the founder's terminal, after their explicit review. The agent # never resolves this decision or impersonates an owner approval. ccr["review"]["comments"].append( { "at": intent["approved_at"], "reviewer": "railiance-platform-owner (Bernd Worsch)", "decision": "approved", "comment": SCOPE + " Exact proposal " + EXPECTED, } ) validator.dump_yaml(foundation.admission.CCR, ccr) decision_id = (ccr.get("state_hub") or {}).get("decision_id") if not decision_id: decision_id = intake.request_decision(foundation.admission.CCR, validator, HUB)["id"] else: decision = validator.state_hub_get_json(HUB, "/decisions/" + decision_id) require(decision["status"] == "open", "Existing founder decision requires inspection") rationale = ( f"APPROVE: {CCR}; exact proposal {EXPECTED}; {SCOPE} " "Approval entered by the founder in the attended terminal." ) request = urllib.request.Request( HUB + "/decisions/" + decision_id + "/resolve", data=json.dumps({"rationale": rationale, "decided_by": "Bernd Worsch"}).encode(), headers={"Content-Type": "application/json"}, method="POST", ) with urllib.request.urlopen(request, timeout=20) as response: require(json.load(response)["status"] == "resolved", "Founder decision unconfirmed") validator.sync_state_hub_decision(foundation.admission.CCR, HUB) return run_controller(foundation, proposal, before, directory, intent, decision_id) def run_controller( foundation, proposal, before, directory, intent, decision_id, *, private_browser=False ): receipt = directory / "foundation.jsonl" env = { **os.environ, "BAO_ADDR": "http://127.0.0.1:18200", "VAULT_ADDR": "http://127.0.0.1:18200", "PYTHONDONTWRITEBYTECODE": "1", } if private_browser: profile = directory / "edge-profile" profile.mkdir(mode=0o700) env["PATH"] = str(Path(__file__).resolve().parent / "smtp-private-browser") + ( os.pathsep + env.get("PATH", "") ) env["SMTP_EDGE_PROFILE"] = str(profile) result = subprocess.run( [ "warden", "access", "openbao-platform-admin-login", "--exec", "--", "python3", str(PLATFORM / "scripts/email_connect_smtp_foundation.py"), "--execute", "--expect-digest", EXPECTED, "--receipt", str(receipt), ], env=env, check=False, ) outcome = { **intent, "warden_exit_code": result.returncode, "decision_id": decision_id, "finished_at": datetime.now(UTC).isoformat(), } write_private(directory / "outcome.json", outcome) require(result.returncode == 0, "Retain receipts; Warden outcome requires inspection") data = receipt.read_bytes() require(data.endswith(b"\n"), "Incomplete foundation receipt requires inspection") final = json.loads(data.splitlines()[-1]) require( final["status"] == "foundation_admitted_projection_ready" and final["proposal_digest"] == EXPECTED, "Foundation result requires inspection", ) require( foundation.protected_application(foundation.Native(), proposal["foundation"]) == before, "Application changed; inspect before the sender step", ) print( json.dumps( { "status": "attended_foundation_completed", "proposal_digest": EXPECTED, "receipt": str(receipt), "outcome": str(directory / "outcome.json"), "warden_exit_code": 0, "sender_changed": False, "mail_sent": False, } ) ) return 0 if __name__ == "__main__": try: sys.exit(main()) except (RuntimeError, OSError, ValueError, KeyError) as error: print( f"Stopped: {error}. Preserve existing receipts; do not retry an attempt blindly.", file=sys.stderr, ) sys.exit(1)