Identity plane split, plan I3f1: the Rust clients (epic &133)

Status: Done (2026-10-11) — !1593
Epic: &133 (stage I3 of &130)
Issues: #2847 (U1, w2); #2848 (U2, w2); #2849 (U3, w1); #2850 (U4, w3); #2851 (U5, w5); #2852 (U6, w3); #2853 (U7, w3); #2854 (U8, w3).
MR: feat/identity-rust-clients, "the Rust clients (#2847 … #2854)".

One MR, one commit per issue, under the maintainer’s one-MR-per-related-group ruling. It merges once the pre-push battery passes. This is a Design + Scope plan: GitLab owns tracking, and the plan freezes when U1 starts. O1–O8 are this plan’s decisions (ADR-049 Amendment 23); R18–R20 are the maintainer’s rulings.

Context

T5 holds the switch until I3c–I3f land. I3f is ADR-049 Amendment 11’s last cut-over stage: the portal, canopy-cli’s device flow, the operator tools, the TypeScript broker with Playwright sign-in, and k6 (plan I3a). All of them still use Keycloak.

K1 (Amendment 11) sets what may land before the switch: "only additive code and devstack infrastructure: library code no service wires … Main never holds … a sender holding two credentials." So each client below is library code, and the switch MR wires it, as it does I3e’s. Behaviour-preserving moves land, as Amendment 22’s Q2 and Q4 did.

What exists:

  • canopy-cli (tools/canopy-cli) reaches Keycloak three ways: a ROPC login, login service (client credentials), and an exchanger exchange for crypto-shred.

    • Tokens are stored per profile under config_dir() (dirs::config_dir()/canopy) by its private owner_only writer: 0600 file, 0700 directory, O_EXCL, then rename. The file is fsynced, but not its directory.

    • A failed cleanup prints to stderr; canopy-cli allows print_stderr.

  • The server side of canopy-cli’s device flow is built and proven: D7, Amendment 9 N1–N11, Amendment 21 and Amendment 22.

    • A device authorization answers device_code, user_code, verification_uri, expires_in and interval.

    • A redemption or refresh answers access_token, token_type, expires_in and refresh_token (services/canopy-security/src/identity/token_endpoint/native.rs:265-272).

    • On the wire, a stale session is invalid_grant with canopy_refusal session_stale. A replay, an ended session, or a device code reused after a lost redemption is invalid_grant with session_ended (native.rs:117-176).

    • The four request forms are those of the Cli stand-in in crates/canopy-test-lib/tests/native_session_test.rs. Each carries client_id=canopy-cli; revocation sends no proof.

  • The edge reads a body within EDGE_BODY_READ_TIMEOUT (2 s), then forwards within EDGE_FORWARD_TIMEOUT (6.5 s).

  • canopy-signing: keygen::generate_key_pair encodes PKCS#8 into a plain String. ProvisionedP256Key::from_pkcs8_pem loads one.

  • canopy-auth: the delegation client holds a granted token to its type, lifetime, audience and client (identity_client/delegation.rs:482).

  • The portal keeps its applicant authentication (D11). It mints Keycloak client-credentials tokens through nine ServiceTokenSources. IdentitySender refuses it (NotAService), since the portal’s sender is I3f’s (E4). Its nine edges are all System.

  • Operator tooling:

    • cargo xtask identity verify is ADR-019’s Keycloak probe. Its devstack proof (Devstack::prove) recognizes only the recorded Keycloak port.

    • .ports.env records CANOPY_PORT_CANOPY_SECURITY_8012.

The maintainer’s rulings (2026-10-11):

  • R18. Two plans. I3f1: canopy-cli’s device client, the portal’s sender and the operator tools. I3f2: the TypeScript broker, Playwright sign-in and k6.

  • R19. canopy-cli keeps its DPoP device key in an owner-only file, per profile.

  • R20. The device client is canopy-auth library code. canopy-cli’s commands move onto it in the switch MR.

Decisions (ADR-049 Amendment 23, O1–O8; land with U1)

  • O1. Staging (R18). I3f1 and I3f2 are library and devstack work. The switch MR does the rest:

    • it moves canopy-cli’s commands onto the device client, the portal onto its sender (retiring PortalTokenSources), and sweep-finalize-orphans onto the operator’s device session;

    • it deletes the Keycloak identity verify;

    • it removes canopy-cli’s notice mark-read verb (#2805). The verb works only under login service until then, so removing it earlier is not additive.

  • O2. canopy-cli’s owner-only writer moves to canopy_common::owner_only, with a typed OwnerOnlyError. The device store and the CLI then share it.

    • Cleanup failures are returned, never printed. A successful write answers the stale staged files it could not remove, and a failed write’s error carries the failure to remove its own staged file. canopy-cli prints both to stderr as it does today, so its diagnostics are preserved.

    • Durability. The writer fsyncs the directory after its rename, and remove_owner_only(path) removes a file and fsyncs its directory. An acknowledged write or removal therefore survives a machine crash. This is the move’s one deliberate change, and it covers canopy-cli’s token files too.

    • Lock files. open_owner_only_lock(path) creates the parent directory at 0700, then the file O_EXCL at 0600. An existing file must be a regular file by symlink_metadata before it is opened.

    • The in-place 0600 writers in xtask and canopy-test-lib stay as they are.

  • O3. A persistable device key. canopy_signing::keygen::generate_p256_pkcs8() → Result<Zeroizing<String>, SigningError> returns a fresh P-256 key as PKCS#8 PEM (KeyGeneration on failure). ProvisionedP256Key::from_pkcs8_pem loads it. LocalP256Key keeps its guarantee.

  • O4. The device store (R19). DeviceStore::at(dir); device_store_dir(canopy_dir, profile) is <canopy_dir>/identity/<profile>, with canopy_dir canopy-cli’s config_dir(). ProfileName refuses an empty name, a path separator and ...

    • session.json holds the issuer identifier, the key’s PKCS#8 PEM and the refresh credential. It has no Debug.

      • It is serialized into a zeroizing buffer and read from one. On every path, failures included, the buffer is wiped.

      • Secrets are deserialized into a Secret(Zeroizing<String>) wrapper with a hand-written Deserialize, as the broker’s is.

      • It is written by O2’s durable rename and removed by remove_owner_only. A session the store cannot use (malformed, or for another issuer) is kept until a login replaces it.

    • session.lock is never removed. Its exclusive lock serializes each read–refresh–write, login and logout across processes. The lock is std File::try_lock, retried for at most DEVICE_LOCK_BOUND (15 s), then Busy.

    • Mutations survive cancellation. Each mutation (a refresh, storing a login, a logout) runs as one spawned task. That task owns the lock from acquisition through its last write, with its file work done by awaited spawn_blocking calls.

      • The caller awaits the task’s handle. Cancelling the caller drops only the handle, which detaches the task and never aborts it.

      • So the lock is released only after the last write. A refresh the issuer answered is still stored, and two invocations never present one credential twice: a replay would end the session (N6).

    • Store failures are StoreError.

  • O5. The device client (R20): canopy_auth::identity_device_client::DeviceClient::new(&IdentitySettings, store, http), failing with DeviceError.

    • Endpoints. It calls the settings' internal device-authorization, token and revocation endpoints. Proofs come from identity_dpop::mint_proof, with htu the issuer identifier’s /token.

      • Before the switch, the devstack’s internal URL is canopy-security’s published one. From the switch, it is canopy-web’s edge.

      • A target off canopy-cli’s compiled edges is NoEdge, and nothing is sent.

    • begin_login() → PendingLogin posts device authorization (client_id=canopy-cli) and draws a fresh key (O3).

      • PendingLogin holds the issuer identifier, DeviceCode, UserCode, verification_uri, expires_at, the interval and the key. It has no Debug, Display or Clone.

      • Required fields that are missing or malformed give Malformed. An absent interval is 5 s (RFC 8628 §3.2). expires_in is capped at 1800 s, so a hostile value cannot hold the CLI.

    • complete_login(pending, resource) → NativeToken first requires the pending login’s issuer to be the client’s settings'. Otherwise it is IssuerMismatch, and nothing is sent. Then it polls per RFC 8628 §3.4–3.5:

      • each wait is the current interval exactly, never shortened, and each poll carries a fresh proof and resource;

      • the codes are read by a private parser, since TokenEndpointError does not know them;

      • the whole poll ends at the device code’s expiry (Expired).

        The answers:

        Answer Effect

        authorization_pending

        poll again

        slow_down

        add 5 s to the interval, each time

        429

        wait the larger of Retry-After and the interval

        503

        wait the interval

        connection failure or timeout

        double the interval (§3.5 backoff)

        access_denied

        Denied

        expired_token

        Expired

        any other refusal (e.g. invalid_grant with session_ended, after a lost redemption)

        LoginFailed { status, error, refusal }

        A failed login never touches the stored session. Only success replaces it: under the lock, the new session is stored, then the prior one (if it was the settings' issuer’s) is revoked, best effort.

    • token(target) → NativeToken. Under the lock, it loads the session and refreshes with a fresh proof and resource = target.audience(). No stored session, or one for another issuer, gives LoginRequired, and nothing is sent.

    • A refresh’s 200 is held to the delegation client’s precedent:

      • token_type Bearer;

      • an access token that parses as a compact JWS within MAX_TOKEN_BYTES, its aud the target and its current actor canopy-cli;

      • a lifetime, and expires_in, within 1..=DELEGATION_TOKEN_MAX_LIFETIME_SECS; expires_at is the token’s exp;

      • a refresh_token parsing as a RefreshCredential.

        The successor is stored whenever it parses, before anything is answered, since the presented credential is spent. Any failed check is then Malformed. A successor that cannot be written is Store, which says to log in again.

    • Refresh refusals:

      • session_stale gives Stale, and the credential is kept: the sweep renews it within its pass (Amendment 21, Z7);

      • subject_suspended gives Suspended, and the credential is kept;

      • any other invalid_grant gives LoginRequired, and session.json is removed;

      • anything else gives Refused, and the store is unchanged.

        Refusals are parsed with TokenEndpointError and CanopyRefusal::from_code.

    • logout(). Under the lock, it revokes the credential as a public client (N8). A 200 removes session.json. Another answer is Refused and no answer is Transport or Timeout; both keep the store. With no session, it is Ok.

    • NativeToken zeroizes, has no Debug, Display or Clone, and offers expose_for_call() and expires_at(). Answers are read capped at TOKEN_RESPONSE_CAP. Refusals quote nothing secret.

    • Test hooks. The slow-down step, the lock bound and the call bound are private fields the tests shorten (Amendment 22, Q7).

  • O6. Bounds. Each call is bounded by DEVICE_CALL_TIMEOUT (10 s). A const assertion holds it above EDGE_BODY_READ_TIMEOUT + EDGE_FORWARD_TIMEOUT + 1 s of transport (9.5 s). Since EDGE_FORWARD_TIMEOUT is above NATIVE_BUDGET, the issuer answers first, then the edge.

    • Some answers can still be lost: an answer past every bound, or the edge’s 503 after the issuer committed (Amendment 22, Q6). Either leaves a spent credential, so the next refresh replays it and the session ends (LoginRequired). This is documented, not retried.

  • O7. The portal’s sender: canopy_auth::PortalSender::from_secrets(settings, secrets, http). It reads the portal’s key under client_key_secret(Portal), with no file fallback (D10).

    • bearer(&self, target) → Result<OwnedBearer, SendError> mints the portal’s system token within SENDER_BUDGET, as Outbound::system does (SystemTokenSource::token(audience, None)).

    • A target off its nine edges is NoEdge, and nothing is sent.

    • rejected(target) drops the cached token (E6).

    • The applicant claim stays portal-signed (D11).

  • O8. The operator tools.

    • cargo xtask identity check --issuer <identifier> --internal <url> --client <id> is canopy-identity’s deploy gate. Its one mint is its only side effect, as with verify. It checks:

      • the metadata names the issuer, and each endpoint it names lies under it, with token, revocation and JWKS present;

      • the JWKS holds at least one ES256 P-256 key with a canonical kid;

      • one client-credentials mint by client, for its first compiled purpose, validates at that purpose’s receiver. The validated principal must be a system token whose client is client, whose purpose is that purpose, and whose scopes are the purpose’s. The receiver alone does not compare them.

    • The key is read through SecretProvider under client_key_secret. The devstack key file .devstack/identity/keys/<client>.pem is used only when a new proof, Devstack::prove_identity(issuer, internal), holds:

      • the issuer is devstack_identity::ISSUER;

      • the internal URL is plain-http loopback at /identity;

      • its port is .ports.env's CANOPY_PORT_CANOPY_SECURITY_8012.

        There is no switch bypass.

    • sweep-finalize-orphans takes the operator’s canopy-cli device session at the switch (device_store_dir, token(Persons)), so no operator holds a second credential.

Units

Every commit goes through the pre-commit review (its J1–J8). Each subject is at most 72 characters with its ` (#N)`.

Erratum (2026-10-11): The device client’s code is split into identity_device_client/answer.rs (answer parsing), client.rs and store.rs beside the module root, each with its own tests.rs. U4 was committed with the store’s dead-code warnings, which the quality budgets forbid suppressing, until U5 used the store. The store adds StoreError::Unstorable (a session the format cannot hold, refused before any write), and ProfileName also refuses a trailing dot or space and a name over 128 bytes. U2’s writer answers the cleanup failures it could not remove as Stored::leftovers and inside OwnerOnlyError::Store. U5 caps interval as it caps expires_in, and a redemption’s 200 carrying a well-formed refresh credential still stores its session and revokes the prior one when its access token fails a check, as a refresh stores its successor; a login that fails otherwise leaves the stored session untouched. U7’s --client defaults to canopy-eligibility; its key choice takes the secret provider and the keys directory; and xtask gains the thiserror and zeroize workspace dependencies.

  1. U1 (#2847, w2) docs(adr): record the Rust clients.

    • ADR-049 Amendment 23 (R18–R20, O1–O8), and its Status line.

    • This page (In progress) and its nav group.

    • #2805 gains a comment moving it to the switch (O1). Its labels are unchanged.

  2. U2 (#2848, w2) refactor(common): share the owner-only writer (O2).

    • Files: the new crates/canopy-common/src/owner_only.rs (+ tests), and lib.rs. In canopy-cli, auth.rs prints the returned cleanup failures and lib.rs loses owner_only.rs.

    • Tests:

      • The generic mode, rename and stale-staging tests move.

      • Cleanup failures are returned, both on success and with an error.

      • remove_owner_only removes a file.

      • open_owner_only_lock creates a file at 0600, re-opens an existing one, and refuses a link.

      • stores_a_login_token_owner_only stays in canopy-cli’s auth::tests, re-executing its own test binary on its own name under umask 000.

    • Docs: shared-crates.adoc.

  3. U3 (#2849, w1) feat(signing): generate a persistable P-256 key (O3).

    • Files: crates/canopy-signing/src/keygen.rs.

    • Tests:

      • A generated PEM loads through from_pkcs8_pem, and its signatures verify under its JWK.

      • Two keys differ.

      • The label is PRIVATE KEY.

    • Docs: shared-crates.adoc.

  4. U4 (#2850, w3) feat(auth): add the device store (O4).

    • Files: the new crates/canopy-auth/src/identity_device_client.rs (the module, ProfileName, device_store_dir), identity_device_client/store.rs (+ store/tests.rs), and lib.rs.

    • Tests:

      • A stored session reads back as written, 0600 in a 0700 directory.

      • Two stores over one directory take the lock in turn. A lock held past its bound is Busy.

      • Ending removes session.json and keeps session.lock.

      • A caller cancelled mid-mutation leaves the task to finish its write before another store takes the lock.

      • A directory at session.json's path makes a write fail with StoreError.

      • A malformed session, or one for another issuer, reads as unusable and is kept.

      • A table refuses each bad ProfileName: empty, ., .., /, \, NUL and C:x.

      • Proptests:

        • an accepted name is exactly one normal component, and parsing never panics;

        • a session round-trips;

        • arbitrary bytes never panic the reader.

    • Docs: shared-crates.adoc.

  5. U5 (#2851, w5) feat(auth): add canopy-cli’s device client (O5, O6).

    • Files: identity_device_client.rs (DeviceClient), its tests.rs, and lib.rs.

    • Tests run against a scripted loopback issuer. It checks every proof with identity_dpop::verify_proof against the htu, and counts overlapping refreshes.

      • Login:

        • the forms;

        • pending, then slow_down twice (each adds 5 s, shortened), then success;

        • an absent interval waits 5 s;

        • a connection failure doubles the interval;

        • a 429 waits its Retry-After;

        • each poll carries a distinct jti;

        • the stored key is the one the proof’s thumbprint names;

        • success revokes the prior session.

      • Login failures:

        • access_denied gives Denied, and the expiry gives Expired;

        • a refused poll (invalid_grant) is LoginFailed with the prior session kept;

        • a malformed answer is Malformed;

        • another issuer’s PendingLogin is IssuerMismatch, with nothing sent.

      • Tokens:

        • token sends resource, a fresh proof and the stored credential, and stores the successor before it answers;

        • an off-edge target gives NoEdge, and no session gives LoginRequired, both with nothing sent;

        • a 200 with a wrong token type, audience, actor or lifetime is Malformed, with its parseable successor stored;

        • two clients over one directory refreshing at once present distinct credentials in turn;

        • a caller cancelled mid-refresh still has the successor stored, and the next client presents it.

      • Refusals and faults:

        • session_ended gives LoginRequired;

        • session_stale gives Stale and subject_suspended gives Suspended, each keeping the credential;

        • an unwritable successor is Store;

        • a call past its bound is Timeout.

      • Logout:

        • a 200 removes session.json;

        • another answer is Refused, and no answer keeps the store;

        • with no session it is Ok.

      • Invariants:

        • the const bound (O6);

        • an answer-parsing proptest: it never panics, an absent interval is 5 s, and expires_in stays within its cap;

        • the E7 probes: NativeToken and PendingLogin have no Debug, Display or Clone.

    • Docs: shared-crates.adoc; idp-integration.adoc, section "canopy-identity’s device approval and native sessions".

  6. U6 (#2852, w3) feat(auth): add the portal’s sender (O7).

    • Files: the new crates/canopy-auth/src/identity_portal_sender.rs (+ tests.rs), and lib.rs.

    • Tests run against the scripted token endpoint of identity_client's tests:

      • each of the nine targets mints with the portal’s assertion and the target’s audience;

      • an off-edge target is NoEdge, with nothing sent;

      • rejected re-mints;

      • a private budget field, shortened, gives Timeout;

      • a missing key is Key.

    • Docs: shared-crates.adoc.

  7. U7 (#2853, w3) feat(xtask): check canopy-identity as a deploy gate (O8).

    • Files: xtask/src/cmd/identity.rs (the check subcommand), the new xtask/src/cmd/identity/check.rs (+ tests), and xtask/src/devstack_target.rs (prove_identity).

    • Tests run against a scripted issuer:

      • a conforming issuer passes, with or without a device-authorization endpoint;

      • each broken issuer fails, naming its check: a wrong metadata issuer, an endpoint outside it, an empty JWKS, a refused mint, a token for the wrong audience, another client’s token, another purpose’s, other scopes, and a delegation token;

      • prove_identity refuses a remote host, a mismatched port and a missing .ports.env, and accepts the devstack pair.

    • Docs: idp-integration.adoc, a subsection of "canopy-identity’s upstream profile" naming the gate; tooling/xtask-catalog.adoc; and local-dev.adoc.

  8. U8 (#2854, w3) test(auth): prove the device client and the portal’s sender.

    • The test file: crates/canopy-test-lib/tests/device_client_test.rs. It repeats native_session_test.rs's plane construction; each test file builds its own.

    • The device client is one test, so there is one sign-in:

      • a DeviceClient logs in over a temporary store, with its settings' internal URL set to canopy-security’s published one;

      • jane.supervisor, the one cast worker no plane test signs in, approves; the broker’s spacing applies;

      • tokens for two targets verify at their receivers with act [canopy-cli];

      • two clients over the one directory refresh concurrently; both succeed, and the session lives on;

      • the test copies session.json's bytes and calls logout. It then restores the copy, and the next token is LoginRequired, because the server revoked the session.

    • The portal’s sender: the portal’s key is read from BrokerConfig::keys_dir and served under CANOPY_PORTAL__IDENTITY_CLIENT_PRIVATE_KEY. Each of its nine targets' tokens validates at its receiver as the portal’s system token under its purpose.

    • A verification run of cargo xtask identity check with canopy-eligibility against the devstack is recorded in the MR.

    • Close:

      • CHANGELOG.adoc: Added, and Changed for owner_only's move and its directory fsync;

      • Amendment 23’s as-built record;

      • the plan Done and archived;

      • plan-lint --done with --allow-open for U1–U8;

      • after merge, I3f1’s tasks ticked on the epic, which stays open for I3f2.

Scope

In: the owner-only move, the persistable key, the device client and its store, the portal’s sender, identity check, and the devstack proof.

Out:

  • The switch: canopy-cli’s commands, the portal’s wiring, sweep’s token, #2805, and the deletions.

  • I3f2: the TypeScript broker, Playwright and k6.

  • A keychain store, cached access tokens on disk, and migrating the in-place 0600 writers.

Risks

  • A lost answer. If an answer is lost past every bound, the credential is spent, and the next refresh ends the session (N6). O4’s detached tasks remove the cancellation case; the durable writes remove the crash-after-acknowledgement case.

  • The key file sits beside the credential. An attacker with the user’s account holds both. That is R19’s trade: no new dependency, and headless use.

  • The devstack proof waits. It spends the server’s 5 s interval once, and the broker’s spacing for jane.supervisor.

Verification

  • Per unit: fmt; clippy (workspace with the lane’s features, and canopy-auth with test-helpers); quality-budgets; check-docs; plan-lint; private rustdoc.

  • nextest: canopy-common, canopy-signing, canopy-auth, canopy-cli and xtask; and cargo xtask test --integration --host -p canopy-test-lib --no-refresh --skip-static (U8).

  • Per MR: the pre-push battery.

Review log

Round Vendor Resolved model Verdict

1

Anthropic

claude-opus-5-5

No-ship. Three blockers, fixed: the polling rules (session_ended on the wire, a private RFC 8628 parser, the unmapped outcomes); proptests for ProfileName, session.json and answer parsing; U4 split into the store and the client. Notes folded in.

2

not stated (the maintainer’s other vendor)

not stated

No-ship. Seven findings and six smaller ones, fixed in-plan: mutations run as detached tasks that hold the lock until their last write; a failed login keeps the prior session; PendingLogin is bound to its issuer; RFC 8628 polling: default interval, cumulative slow_down, backoff, the expiry bound; a 10 s bound over both edge phases; the gate checks the minted principal; a new devstack proof; native 200 validation, with the successor kept; durable rename and removal; a zeroizing output buffer; returned cleanup diagnostics; canonical type:: labels; the portal key from keys_dir. (An earlier round-2 submission reviewed the old I2c plan by mistake, so it was not applied.)

Edit this page · default