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 privateowner_onlywriter:0600file,0700directory,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_inandinterval. -
A redemption or refresh answers
access_token,token_type,expires_inandrefresh_token(services/canopy-security/src/identity/token_endpoint/native.rs:265-272). -
On the wire, a stale session is
invalid_grantwithcanopy_refusalsession_stale. A replay, an ended session, or a device code reused after a lost redemption isinvalid_grantwithsession_ended(native.rs:117-176). -
The four request forms are those of the
Clistand-in incrates/canopy-test-lib/tests/native_session_test.rs. Each carriesclient_id=canopy-cli; revocation sends no proof.
-
-
The edge reads a body within
EDGE_BODY_READ_TIMEOUT(2 s), then forwards withinEDGE_FORWARD_TIMEOUT(6.5 s). -
canopy-signing:
keygen::generate_key_pairencodes PKCS#8 into a plainString.ProvisionedP256Key::from_pkcs8_pemloads 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.IdentitySenderrefuses it (NotAService), since the portal’s sender is I3f’s (E4). Its nine edges are allSystem. -
Operator tooling:
-
cargo xtask identity verifyis ADR-019’s Keycloak probe. Its devstack proof (Devstack::prove) recognizes only the recorded Keycloak port. -
.ports.envrecordsCANOPY_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), andsweep-finalize-orphansonto 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 serviceuntil then, so removing it earlier is not additive.
-
-
O2. canopy-cli’s owner-only writer moves to
canopy_common::owner_only, with a typedOwnerOnlyError. 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 at0700, then the fileO_EXCLat0600. An existing file must be a regular file bysymlink_metadatabefore it is opened. -
The in-place
0600writers 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 (KeyGenerationon failure).ProvisionedP256Key::from_pkcs8_pemloads it.LocalP256Keykeeps its guarantee. -
O4. The device store (R19).
DeviceStore::at(dir);device_store_dir(canopy_dir, profile)is<canopy_dir>/identity/<profile>, withcanopy_dircanopy-cli’sconfig_dir().ProfileNamerefuses an empty name, a path separator and...-
session.jsonholds the issuer identifier, the key’s PKCS#8 PEM and the refresh credential. It has noDebug.-
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-writtenDeserialize, 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.lockis never removed. Its exclusive lock serializes each read–refresh–write, login and logout across processes. The lock is stdFile::try_lock, retried for at mostDEVICE_LOCK_BOUND(15 s), thenBusy. -
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_blockingcalls.-
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 withDeviceError.-
Endpoints. It calls the settings' internal device-authorization, token and revocation endpoints. Proofs come from
identity_dpop::mint_proof, withhtuthe 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() → PendingLoginposts device authorization (client_id=canopy-cli) and draws a fresh key (O3).-
PendingLoginholds the issuer identifier,DeviceCode,UserCode,verification_uri,expires_at, the interval and the key. It has noDebug,DisplayorClone. -
Required fields that are missing or malformed give
Malformed. An absentintervalis 5 s (RFC 8628 §3.2).expires_inis capped at 1800 s, so a hostile value cannot hold the CLI.
-
-
complete_login(pending, resource) → NativeTokenfirst requires the pending login’s issuer to be the client’s settings'. Otherwise it isIssuerMismatch, 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
TokenEndpointErrordoes not know them; -
the whole poll ends at the device code’s expiry (
Expired).The answers:
Answer Effect authorization_pendingpoll again
slow_downadd 5 s to the interval, each time
429
wait the larger of
Retry-Afterand the interval503
wait the interval
connection failure or timeout
double the interval (§3.5 backoff)
access_deniedDeniedexpired_tokenExpiredany other refusal (e.g.
invalid_grantwithsession_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 andresource = target.audience(). No stored session, or one for another issuer, givesLoginRequired, and nothing is sent. -
A refresh’s 200 is held to the delegation client’s precedent:
-
token_typeBearer; -
an access token that parses as a compact JWS within
MAX_TOKEN_BYTES, itsaudthe target and its current actor canopy-cli; -
a lifetime, and
expires_in, within 1..=DELEGATION_TOKEN_MAX_LIFETIME_SECS;expires_atis the token’sexp; -
a
refresh_tokenparsing as aRefreshCredential.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 isStore, which says to log in again.
-
-
Refresh refusals:
-
session_stalegivesStale, and the credential is kept: the sweep renews it within its pass (Amendment 21, Z7); -
subject_suspendedgivesSuspended, and the credential is kept; -
any other
invalid_grantgivesLoginRequired, andsession.jsonis removed; -
anything else gives
Refused, and the store is unchanged.Refusals are parsed with
TokenEndpointErrorandCanopyRefusal::from_code.
-
-
logout(). Under the lock, it revokes the credential as a public client (N8). A 200 removessession.json. Another answer isRefusedand no answer isTransportorTimeout; both keep the store. With no session, it isOk. -
NativeTokenzeroizes, has noDebug,DisplayorClone, and offersexpose_for_call()andexpires_at(). Answers are read capped atTOKEN_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). Aconstassertion holds it aboveEDGE_BODY_READ_TIMEOUT+EDGE_FORWARD_TIMEOUT+ 1 s of transport (9.5 s). SinceEDGE_FORWARD_TIMEOUTis aboveNATIVE_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 underclient_key_secret(Portal), with no file fallback (D10).-
bearer(&self, target) → Result<OwnedBearer, SendError>mints the portal’s system token withinSENDER_BUDGET, asOutbound::systemdoes (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 withverify. 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 isclient, whose purpose is that purpose, and whose scopes are the purpose’s. The receiver alone does not compare them.
-
-
The key is read through
SecretProviderunderclient_key_secret. The devstack key file.devstack/identity/keys/<client>.pemis 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'sCANOPY_PORT_CANOPY_SECURITY_8012.There is no switch bypass.
-
-
sweep-finalize-orphanstakes 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.
-
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.
-
-
U2 (#2848, w2)
refactor(common): share the owner-only writer(O2).-
Files: the new
crates/canopy-common/src/owner_only.rs(+ tests), andlib.rs. In canopy-cli,auth.rsprints the returned cleanup failures andlib.rslosesowner_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_onlyremoves a file. -
open_owner_only_lockcreates a file at0600, re-opens an existing one, and refuses a link. -
stores_a_login_token_owner_onlystays in canopy-cli’sauth::tests, re-executing its own test binary on its own name under umask 000.
-
-
Docs:
shared-crates.adoc.
-
-
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.
-
-
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), andlib.rs. -
Tests:
-
A stored session reads back as written,
0600in a0700directory. -
Two stores over one directory take the lock in turn. A lock held past its bound is
Busy. -
Ending removes
session.jsonand keepssession.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 withStoreError. -
A malformed session, or one for another issuer, reads as unusable and is kept.
-
A table refuses each bad
ProfileName: empty,.,..,/,\, NUL andC: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.
-
-
U5 (#2851, w5)
feat(auth): add canopy-cli’s device client(O5, O6).-
Files:
identity_device_client.rs(DeviceClient), itstests.rs, andlib.rs. -
Tests run against a scripted loopback issuer. It checks every proof with
identity_dpop::verify_proofagainst thehtu, and counts overlapping refreshes.-
Login:
-
the forms;
-
pending, then
slow_downtwice (each adds 5 s, shortened), then success; -
an absent
intervalwaits 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_deniedgivesDenied, and the expiry givesExpired; -
a refused poll (
invalid_grant) isLoginFailedwith the prior session kept; -
a malformed answer is
Malformed; -
another issuer’s
PendingLoginisIssuerMismatch, with nothing sent.
-
-
Tokens:
-
tokensendsresource, a fresh proof and the stored credential, and stores the successor before it answers; -
an off-edge target gives
NoEdge, and no session givesLoginRequired, 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_endedgivesLoginRequired; -
session_stalegivesStaleandsubject_suspendedgivesSuspended, 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
constbound (O6); -
an answer-parsing proptest: it never panics, an absent interval is 5 s, and
expires_instays within its cap; -
the E7 probes:
NativeTokenandPendingLoginhave noDebug,DisplayorClone.
-
-
-
Docs:
shared-crates.adoc;idp-integration.adoc, section "canopy-identity’s device approval and native sessions".
-
-
U6 (#2852, w3)
feat(auth): add the portal’s sender(O7).-
Files: the new
crates/canopy-auth/src/identity_portal_sender.rs(+tests.rs), andlib.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; -
rejectedre-mints; -
a private budget field, shortened, gives
Timeout; -
a missing key is
Key.
-
-
Docs:
shared-crates.adoc.
-
-
U7 (#2853, w3)
feat(xtask): check canopy-identity as a deploy gate(O8).-
Files:
xtask/src/cmd/identity.rs(thechecksubcommand), the newxtask/src/cmd/identity/check.rs(+ tests), andxtask/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_identityrefuses 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; andlocal-dev.adoc.
-
-
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 repeatsnative_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
DeviceClientlogs 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 callslogout. It then restores the copy, and the nexttokenisLoginRequired, because the server revoked the session.
-
-
The portal’s sender: the portal’s key is read from
BrokerConfig::keys_dirand served underCANOPY_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 checkwith canopy-eligibility against the devstack is recorded in the MR. -
Close:
-
CHANGELOG.adoc:Added, andChangedforowner_only's move and its directory fsync; -
Amendment 23’s as-built record;
-
the plan Done and archived;
-
plan-lint --donewith--allow-openfor 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
0600writers.
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
intervalonce, and the broker’s spacing forjane.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 ( |
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; |