Track B / Volume 1 / B1.05

Lab B1.05 — Approval gates

Lab handout · Fictional examples

Lab starter repo: Coming soon

The public starter will use fictional data only. Read this handout alongside the lab specifications; executable starter files are not available yet.

Time: ~90 minutes, an unmeasured pilot estimate with supplied helpers; allow review and rework.
Prerequisites: B1.01–B1.04, including owner brief, privacy/access/stop preflight, Python 3.12 code with type hints, asynchronous calls and positive/negative pytest assertions.
Outcome: Implement complete-envelope approval and demonstrate allowed execution and denied bypasses in the local mock.

This handout specifies the learner interface and acceptance contract. It does not claim an implemented Python starter repository is included on this site. Python is the working default, using Python 3.12 with type hints and dataclasses. Runtime support is pending verification. The lab repository will be public and contain fictional Lane & Hoy data only, no real customer data or secrets; assessment-specific reviewer responses and variation seeds stay outside candidate-controlled public state. Install the released package and its verified uv.lock with uv sync --frozen. No API keys, database, Docker, network or cloud are required for core lab execution after setup; installation may download packages.

Starting state and supplied helpers

Start from the passing B1.04 checkpoint, not an unsafe reset. The system factory has runtime, policy, private connector facade/adapters and log; unknown actions are denied. The AP proposer has scoped mailbox/file reads and bill drafts. Send/pay/delete are denied until their gates are implemented. The baseline still has no provider send/pay capability on the proposer.

The lab harness supplies a mock grant administrator who explicitly enables mailbox-scoped send and supplier-account-scoped pay on the private executor, not the proposer. A separate missing-scope fixture omits each capability in turn. Supplies also include strict envelope validation, recursive canonicalisation, opaque mock sign-ins, fake clock, durable atomic claim/intent/receipt helpers, fixture loader and isolated fault hooks. Learners implement the policy transitions, authorisation checks and orchestration using these helpers.

Fixtures: INV-4200 query and payment batch (SGD 4,200 = 420000 minor units), THB variant without conversion, an attachment with fixed bytes/digest, a SGD 42,000 mutation, CC/sender/beneficiary changes, an inactive person, stranger, agent and shared inbox, forged token/context, failing intent writer and failing outcome writer. All people and .invalid addresses are fictional. Use a fresh namespace and clock for every case; deleting the fixture namespace never deletes a prior learner checkpoint.

Tasks

  1. Inspect the owner brief and show the approval card's full envelope and evidence.
  2. Implement policy-only token issuance and authenticated approval transitions.
  3. Require adapter verification of token origin, scope, identity, expiry, digest and operation claim.
  4. Record durable intent before execution, then receipt/outcome or unknown status.
  5. Run the cases below and all earlier invariants. Inspect a successful send and a held payment from the log.
  6. Deliberately break a control in an isolated copy and show the runner fails; restore it before submission.

Shared execution and approval contract

This contract governs B1.02 onward, the B1.05 lesson/handout, later identity/eval labs and the capstone. Unknown actions and unknown payload fields are denied. No standing policy grant covers send, pay or delete. These actions always require a separate, authenticated named person's approval of one execution envelope. Underlying connector capability is a separate prerequisite and never substitutes for approval.

Two authority layers. The proposer fw-agent-ap has mailbox/folder read and draft capabilities only. It never receives a raw connector or a send/pay/delete credential. B1.04 is draft-only. At B1.05 a mock grant administrator explicitly provisions the private executor with mailbox-scoped send and supplier-account-scoped payment capability; B1.07 adds record-scoped delete capability. The facade owns those capabilities. Validate current provider scope, tenant, resource, currency/amount constraints and authority at execution. Missing/revoked scope denies even a valid approval; existing scope never bypasses a gate. B2.04 narrows this executor configuration rather than silently removing the capability needed by earlier positive tests.

Complete execution envelope. Validate and freeze a versioned schema containing: tenant and workflow IDs; request and operation/idempotency IDs; action and connector contract version; agent principal; executor identity and acting-for authority; purpose/evidence version references; all execution fields; and any policy/config version whose change invalidates approval. Email includes sender, reply-to, ordered to/cc/bcc lists, subject, exact body, content type, and each attachment's identifier, filename, media type and byte digest. Payment includes the complete ordered batch, beneficiary account identifiers (fictional), invoice/PO/delivery evidence versions, amount in integer minor units, currency, due date and fees/options. Delete includes exact resource IDs and versions, delete mode and cascade effects. Reject unsupported options rather than let them escape the hash. Attachment bytes must match their frozen digests at dispatch; do not fetch a mutable attachment URL after approval.

Hash the entire validated envelope with SHA-256 over UTF-8 canonical JSON: recursively sort object keys, preserve array order, include explicit nulls/defaults, reject duplicates/unknown keys, non-finite numbers and floating-point money. Do not normalise or translate body text after hashing. Sorted insertion order yields the same digest; changed attachment bytes, sender, CC, beneficiary, tenant, authority or action yields a different digest. A change voids approval and requires a new request/operation; reusing an operation ID with a changed digest is an error.

Authenticated people and token origin. The mock IdP supplies an opaque authenticated caller context from a protected fixture/session registry. Approval derives the actor from that context, never from an approverId supplied by the proposer. Check current active person status and role at approval and execution. Reject forged contexts, agent principals, shared mailboxes, strangers and departed/revoked people. Only the policy service can mint an opaque decision token after these checks; protected durable policy state stores its token ID, request, envelope digest, principal, executor, action, tenant/workflow, approver, issue/expiry time and consumption state. The connector adapter checks that registry through the trusted facade boundary before performing a side effect. Copying token fields or supplying a plausible plain object is not valid issuance. Tokens cannot be used by a different principal or workflow.

State and timeout rules. Requests begin pending. Mei is the primary approver; the fictional operations director is the named backup. A send request reaches escalated after 8 hours without a decision: only the backup may then approve during a new 8-hour window. After that it is expired. A payment request reaches held after 24 hours; it cannot be approved late. Delete also holds after 24 hours. An authorised owner may cancel a held/expired request and create a new reviewed request, never revive the old token. The backup cannot approve before escalation; for payment/delete the owner must explicitly reassign a new request to the backup with a recorded reason. A permitted person can reject (rejected); the owner can cancel (cancelled); a changed envelope makes it void. All these states are terminal for execution. Approval gives approved, with token expiry at the earlier of 15 minutes after approval or the active request-window deadline. An approval may be withdrawn before execution claims it, returning a terminal cancelled state. A transaction serialises withdrawal and dispatch claims: once executing, withdrawal cannot undo a side effect and triggers stop/reconciliation. No timeout issues a token or auto-approves.

Durable dispatch. Under a per-operation atomic claim, recheck token origin, envelope, actor status, scope, freeze and time. Persist a minimal intent before calling the connector; assert its presence at the connector boundary. If persistence fails, receipts remain unchanged. Consume the token for that single operation and dispatch through the checked adapter. Record outcome and connector receipt after execution, or unknown when acceptance cannot be established. A receipt proves acceptance, not necessarily delivery to a human. Duplicate calls for the identical operation return the existing result or in-progress without a second dispatch; a consumed token on a new request is replay and is denied. Restart recovery queries the receipt before any retry. An intent without a confirmed receipt is uncertain, not permission to send again. The B1 supplied ledger covers one-process retries and crash reconciliation; B3.07 extends this with cross-process concurrency and checkpoints.

Event records include event/operation/request IDs, time, tenant/workflow, authenticated actor, acting-for/executor, action, envelope and approved hashes, gate, approver, policy/config version, decision/state, receipt or error code. Keep bodies/attachments in restricted expiring storage, not in general logs. Denial logging is also required; failure to log a denial must still deny. Application append-only behavior does not claim host-level tamper resistance. Retention/correction follows the regional privacy briefing.

Acceptance cases and fixture API

The proposed Python adapter exposes make_harness(fixture), h.sign_in_fixture(person), h.propose(envelope), h.approve(context, request_id, displayed_hash), h.execute(agent_context, envelope, token), h.clock.advance(seconds), h.receipts(), h.events() and h.restart(). Only the test harness can create sign-in contexts, inject faults, inspect raw receipts or reset storage. Runtime imports must not expose those helpers. Errors return stable codes; assert both the code and unchanged receipts on every denial. Await all asynchronous operations.

Case / given and whenRequired assertion
Direct bypass / call adapter without registered token; also remove gate configTOKEN_INVALID or boot GATE_REQUIRED; zero send/pay receipts. A draft with valid scope remains possible.
Positive send / Mei approves exact INV-4200 envelope with executor scopeOne send receipt; intent existed at the adapter boundary; outcome links the same hash, request, approver and receipt.
Positive pay / approve the complete batch with supplier-scoped capabilityExactly one payment for 420000 SGD minor units to the approved fictional account; no currency conversion.
Scope / approve correctly, then omit or revoke executor send/pay capabilitySCOPE_DENIED, no new receipts; restoring capability still requires a current unconsumed approval.
Caller / pass a plain object claiming Mei, or sign in as agent, shared inbox, stranger or departed approverAuthentication/role denial for every variant; never an approved request or token. Valid Mei is the positive control.
Complete hash / independently change attachment bytes, filename, CC, sender, body, amount, beneficiary, action, workflow or authority after approvalENVELOPE_CHANGED, request void, no additional effect. Reordered nested object keys alone keep the digest; reordered arrays do not.
Schema / supply unknown nested field, NaN, floating-point money or missing recipientSCHEMA_INVALID before token issuance; no receipt. A validated SGD/THB envelope passes unchanged.
Token / fabricate token fields; use token from another tenant/workflow; use consumed token on a new operationTOKEN_INVALID, binding denial or REPLAY; receipts unchanged. Tokens may only originate from policy's protected registry.
Send timeout / no decision at 8 hours, then at 16 hoursState escalated with zero receipts at 8h; primary/early-backup approval denied; backup approval in the active window succeeds once. At 16h the unapproved request is expired.
Payment timeout / no decision at 24 hoursHeld, no token/payment; late approval denied. A new explicitly reassigned request is independently reviewed.
Token expiry / approve at minute zero; execute at 15 minutes, or at the earlier request deadlineEXPIRED; zero new receipts. Execute just before the deadline is the positive control.
Terminal states / reject, cancel, withdraw before claim or mutate an approved requestEach refuses execution with a state-specific denial; withdrawing after claim reports too late and requires reconciliation.
Intent failure / force durable append to fail before adapter entryINTENT_UNAVAILABLE; connector call count and receipts both unchanged. Inspect intent from inside the adapter, not only after return.
Outcome failure / connector accepts, then outcome append failsOne receipt, unknown local status; restart reconciliation records that receipt without redispatch. Do not assert zero sends after acceptance.
Duplicate / execute twice sequentially or concurrently with identical operation and envelopeOne dispatch and one receipt; second call returns recorded result or in-progress. Changed envelope under the same operation key fails.
Restart / crash after intent but before dispatch; separately after acceptance before outcomeResume from persistent state; query receipts first. Known unstarted operation may proceed once with valid authority; accepted operation is reconciled; unknowable outcome stays held.

Assertions above are executable contracts, not empty test bodies. For example, with the supplied adapter the missing-scope case has actual assertions:

import asyncio

import pytest
from labs.testing.harness import Denied, make_harness


@pytest.mark.lab_b1_05
def test_missing_send_scope() -> None:
    async def scenario() -> None:
        h = await make_harness("missing-send-scope")
        request = await h.propose(h.query)
        mei = h.sign_in_fixture("mei")
        token = await h.approve(mei, request.id, request.hash)
        before = h.receipts()
        with pytest.raises(Denied) as error:
            await h.execute(h.agent, h.query, token)
        assert error.value.code == "SCOPE_DENIED"
        assert h.receipts() == before == []

    asyncio.run(scenario())

uv run --offline pytest -m lab_b1_05 must run the B1.01–B1.04 invariants plus these cases. A selected lab with zero tests, skipped/todo tests, a load error or an unawaited failure is nonzero, never a pass. The released tests/conftest.py supplies cumulative markers and fail-closed hooks; it also rejects xfail/xpass and unawaited-coroutine cases. Plain pytest markers alone do not enforce this contract. asyncio.run drives the example without an async pytest plugin; Denied.code and fresh receipt snapshots are supplied harness interfaces. Tests do not use the network. A reviewer also varies identifiers, amounts and attachment bytes so implementations cannot pass by recognising INV-4200 alone.

Reference-solution outline

Keep policy, authenticated session registry and executor capabilities outside the proposer. Use the supplied validator and canonical digest before storing the frozen request. A state-transition function checks clock, active person and primary/backup authority. Approval alone mints a registered token; no public constructor produces one.

The facade/adapter claims the operation atomically, revalidates identity/grants/freeze/token/envelope, commits intent and calls the idempotent connector. Receipt and outcome are separate records. Duplicate callers query the same ledger; replay on another operation is denied. On restart reconcile the connector receipt and persist an outcome, or hold the unknown result. Never translate or mutate a frozen approved payload during this process.

The normal runtime retains all earlier guarantees. Raw unsafe doubles exist only in isolated test fixtures. B1.06 deepens restricted snapshot storage and retention; B1.07 exercises delete and aliases; B3.07 adds multi-process contention and batch checkpoints without removing B1 retry protection.

Runner challenge and evidence

When the public starter repository is released, use its documented cumulative pytest runner to establish a clean baseline before attempting this challenge. The runner and executable fixtures are not available yet. In separate isolated variants: remove the scope check; omit attachments from the digest; accept a fabricated token; skip token consumption; execute before intent persistence; let timeout approve; remove atomic idempotency. Each variant must produce a nonzero run with a failing behavioral assertion. A test that merely searches source text or checks a document heading does not count. Record selected test count, failures, fixture seed and implementation/config fingerprint. Restore controls and rerun the cumulative suite.

Check yourself

  1. What happens when the intent writer fails before dispatch?
  2. What happens when the outcome writer fails after acceptance?
  3. Why can a valid scope and a real approver still be insufficient?

Answers

  1. No additional call or receipt; execution fails closed.
  2. The action may already have happened. Hold/reconcile from its receipt under the same operation key; do not blindly retry.
  3. Approval may be expired, withdrawn, replayed or bound to a different complete envelope; actor status or freeze may also have changed. Recheck every condition at execution.