# cortexkit-claustrum-client
> [!WARNING]
> **Alpha.** cortexkit-claustrum-client is in early development and is not yet released for general use.
> Breaking changes will happen between versions, including changes to its settings,
> stored data and interfaces. Pin an exact version if you depend on it.
Rust client for the claustrum credential vault, used by subc-supervised CortexKit
modules. The vault owns this client alongside its TypeScript client so the wire
decoders can be tested against the producer's serialized replies.
The resolver for claim-bound modules uses a caller-owned `subc-client-rs` 0.47.1
consumer. Its subc dependencies use `subc-protocol` 0.39.0, `subc-control` 0.47.0
(via the SDK), `subc-transport` 0.19.0, and `subc-os` 0.1.61. The legacy raw
constructors remain available. Listed credentials carry optional
`plan_tier_since_ms`: use the operator's effective start when present, otherwise
fall back to `plan_tier_observed_at_ms`.
```toml
[dependencies]
cortexkit-claustrum-client = "0.19.0"
```
The default `transport` and `consumer` features provide the resolver, live watch,
and SDK consumer adapter. For decoders only, use `cortexkit-claustrum-client = { version =
"0.19.0", default-features = false }` for the public `decode_*_reply` functions,
the route-open and established-route error decoders, record/error types,
`WatchNotice`, and `WatchTracker` without
`subc-client-rs`, `subc-transport`, `subc-os`, or Tokio. `subc-protocol` remains a dependency;
no socket or authentication code is built in this mode.
### Claim-bound modules
A module registered through the daemon's registration channel must reuse its SDK
consumer, which authenticates consumer connections with the module's claim. It
must not open a raw connection with a module ID and launch nonce. Use the
`consumer` feature (enabled by default):
```rust,no_run
use std::sync::Arc;
use cortexkit_claustrum_client::{ClaustrumCredentialResolver, CredentialResolver};
use subc_client_rs::SubcConsumer;
async fn read_from_vault(consumer: Arc<SubcConsumer>) {
let resolver = ClaustrumCredentialResolver::with_consumer(Arc::clone(&consumer));
let credential = resolver.get_scoped("provider:account").await.unwrap();
// Pass credential.expose() to the provider; never log the bytes.
let mut watch = resolver.watch_scoped(None).await.unwrap();
while let Some(notice) = watch.next().await {
// Re-read the inventory or held keys indicated by WatchTracker.
let _ = notice;
}
}
```
Register the module with the SDK before connecting the consumer, and keep that
registration serving while the consumer is in use. `SubcConsumer` is not `Clone`,
so callers share it with `Arc`. All resolver operations, including
`auth.watch_scoped`, use this consumer. The adapter supplies no consumer identity
or launch nonce; the SDK binds the connection. Dropping a resolver does not close
the caller's consumer. Watches cancel their own subscriptions, not other calls.
Reply decoding, refusal classes, retry policy, and `WatchTracker` are shared with
the raw path; `seal` and scoped reads still make one unary attempt.
The client neither acquires grants nor enrolls a consumer.
For processes still using launch-nonce registration, construct
`ClaustrumCredentialResolver::new(connection_file_path, consumer_module_id)`
(or the existing `with_live_consumer_identity` constructor). Import the
`CredentialResolver` trait to call it. Bind
identity carries only harness/session labels; a route's project comes from its
session scope, not a caller-supplied project path. The resolver lazily opens a
route to `claustrum`, presenting the reserved consumer
identity and launch nonce obtained through `subc_os`. Scoped calls require a
supervised process with that nonce and the corresponding vault grants; the
client does not acquire grants or enroll a consumer.
`resolve` reads a credential through a capability handle. `get_scoped` and
`status_scoped` address a credential by its vault ID under the route's
principal. Use `get_scoped_with_min_ttl(credential_id, min_ttl_ms)` when the
served token must remain valid for a bounded request duration; ordinary
`get_scoped` omits `min_ttl_ms` from the wire request. Successful reads expose
optional `account_id`, `email`, and `org_name` metadata on `ResolvedCredential`
when the vault has captured those identity fields. These values are non-secret;
the credential payload remains redacted in `Debug` output.
The read decoders require a byte-integer-array payload and an unsigned-integer
`record_version` on the wire; the public version is still a string. String payloads
and string versions are not supported. Malformed present expiry, identity, or status
metadata returns `InvalidResponse` rather than silently becoming absent. Optional
identity and expiry fields may be omitted or null; status `record_version` must be
omitted when unavailable, and an absent `stale_pending` still defaults to `false`.
`report_auth_failure(credential_id, record_version, provider_status)` sends a
version-fenced report for the credential version that was used. The client
rejects statuses other than 401 and 403 before sending. Its boolean result is the
vault's `accepted` answer, not proof that state changed: a stale version is
accepted and ignored. After reporting, read again; if the version did not move,
stop rather than looping. For a static API key, a 401 means the key is dead.
`sign` uses vault-held signing keys, which never leave the vault. `public_key` returns
the public half of a vault-held key: an Ed25519 signing key or an X25519 KEM key.
`CredentialPublicKey::algorithm` is a `PublicKeyAlgorithm` (`Ed25519` or `X25519`);
check it before use, because a KEM key cannot verify a signature. The decoder refuses
any other algorithm, and a `key_id` that is not the first 8 bytes of SHA-256 over
the public key.
`seal(SealRequest { credential_id, recipient_public_key, info, aad, plaintext })`
seals one message in HPKE Auth mode (RFC 9180 mode 2) under a vault-held KEM key,
for a recipient that opens it with that key's public half. It needs an exact `seal`
grant. Seal makes exactly one attempt and hands a retryable error back: every seal is
a fresh ciphertext with its own audit row, so the caller decides whether to retry.
`list_scoped` lists the credentials the caller's grants cover. Handle reads retry
transport failures, not classified vault refusals. Signing and public-key reads
also retry transient vault refusals. Retries are bounded, with a 100 ms backoff
between attempts. Scoped reads return the first error. Each unary attempt has one
deadline for waiting in the queue, opening the route, and receiving the reply.
Listing failures are row-local: callers should check `undecodable_credentials` and
`undecodable_grants`, because the library does not log them. A grant tuple with
a missing, empty or non-string field is skipped and reported there, never turned
into an empty-string grant.
A missing `grant_tuples` field is accepted for older vaults; a present non-array
rejects the whole listing as `InvalidResponse`, not an empty grant inventory.
The client uses `subc_protocol::error_codes::is_retryable_route_open_refusal` for
`Error` frames. A retryable refusal
is `Transport` and clears the cached route. `unknown_module`, `missing_identity`,
unknown codes, and refusals with `detail.expected_back: false` are terminal. They
return `CredentialErrorClass::Unclassified` and do not trigger a retry. Both cases
preserve the wire code in `code()`. They do not describe a credential's state.
On an SDK-backed route with a negotiated request window, a daemon `route_busy`
refusal proves the request was not forwarded. It returns `Transient` with the
code `route_busy`; the caller can retry without the client reopening the route
or replaying the request. A `route_busy` error frame without that proof remains
`Unclassified`. The client also reports `Transient` when the SDK confirms its
deadline expired waiting for credit before it sent the request. If the resolver's
own deadline expires first, the error is still `Transport`.
For a scoped watch, `unknown_method` ends the watch as `Unsupported`, the signal to
poll instead.
## Watching for changes
`CredentialResolver::watch_scoped(enrollment_token)` opens one dedicated raw
transport connection so a held watch cannot block ordinary resolver calls. Its
`ScopedWatch` yields typed notices with `next().await`; drain those before awaiting
`closed().await`. `stop()` (or dropping the handle) sends best-effort CANCEL. The
32-notice queue is bounded: a slow reader ends with `TransportLost`, not silent
loss inside the client. The client never reconnects or re-subscribes on its own.
For SDK-backed watch starts, the SDK can resend the start request on the same
route after a verified `route_busy` refusal, until its start deadline.
`ScopedWatchOutcome` distinguishes `Refused(error)` (including revocation after
notices), `Ended` (STREAM_END after notices), `TransportLost(error)` (including
`route_closed`), `Unsupported` (`unknown_method`, so poll), and `Stopped`.
`InvalidNotice` and `InvalidResponse(error)` are typed protocol failures. A
zero-notice STREAM_END confirms `list_scoped` once with the same token: a refusal
is terminal, success is `NotAccepting` (retry only after caller backoff/reconnect).
Raw Response refusals are decoded directly, without that confirming read.
### Reusing an existing SubcConsumer
No second connection or SDK dependency is needed to use the public transport-free
`WatchNotice::decode(bytes)` and `WatchTracker`. The decoder denies unknown fields,
requires `kind: "changed"`, a nonempty epoch, a positive safe-integer sequence, and
string view/key digests. The tracker is synchronous and pure: no IO, timers, clocks,
or async work. Feed it observations from your own `SubcConsumer::subscribe` or
`subscribe_route` and execute the returned `WatchAction` in your existing loop.
Read `list_scoped` on connect and call `tracker.inventory_read(listing.view)` only
after that read succeeds. Key-announcing callers likewise call `keys_read(digest)`
after re-reading held public keys. Do not acknowledge a hint as a completed read.
Call `opened()` for every new subscription, then feed each decoded notice to
`notice(¬ice)`. The decision table is pinned row by row by `tracker_*` tests:
| First notice / new epoch / noncontiguous seq | `Reread { inventory: true, keys: <digest differs> }` |
| Changed view vs last successful list read | Re-read inventory (even if an earlier hint asked for the same read). |
| Only keys changed | `Reread { inventory: false, keys: true }` |
| Contiguous notice, acknowledged view and keys unchanged | `Reread { inventory: false, keys: false }` |
| Subscription closes after notices | `ResubscribeAndReread` once; duplicate close observations return `Stop`. |
| Subscription closes with zero notices | `ReadListOnce`, never re-subscribe blindly. |
| Confirming list succeeds | `list_result(true)` → `RetryLater`; caller supplies backoff/reconnect. |
| Confirming list refuses | `list_result(false)` → `Stop`. |
| Route lost (including `route_closed`) | `route_lost()` → `ReconnectAndReread`; duplicate loss after closure → `Stop`. |
| `unknown_method` | `unknown_method()` → named `Fallback` (keep polling). |
| A visible Response refusal | `refused()` → `Stop`. |
| Notice after closure | `Stop`. |
For an SDK that erases terminal Response bodies, feed a successful `closed()` to
`tracker.closed()`. A revoked mid-watch enrollment first returns
`ResubscribeAndReread`; on the new zero-notice watch, `ReadListOnce` discovers the
terminal refusal. Never loop after that zero-notice close. For each close after
notices, perform at most one re-read/re-subscribe action, then call `opened()`.
```rust,ignore
let mut tracker = WatchTracker::default();
tracker.inventory_read(list_scoped_on_existing_consumer().await?.view);
tracker.opened();
let mut subscription = consumer.subscribe_route(route, watch_request, options).await?;
while let Some(bytes) = subscription.events().recv().await {
let notice = WatchNotice::decode(&bytes)?;
let action = tracker.notice(¬ice);
// Execute action with the same consumer; acknowledge completed reads above.
apply_watch_action(action).await?;
}
let action = match subscription.closed().await {
Ok(()) => tracker.closed(),
Err(error) if error.code() == Some("unknown_method") => tracker.unknown_method(),
Err(_) => tracker.route_lost(),
};
apply_watch_action(action).await?;
```
`view` compares the inventory last read; `keys` is independent and only matters to
callers announcing vault-held public keys. After reconnecting a route, reopen the
watch: its first notice has seq 1 and current digests, covering changes that may
have happened while disconnected. Neither digest is an event journal, and refresh-only writes do
not change them.
## Module-owned secrets
Version 0.13.0 adds inherent `module_secret_put`, `module_secret_get`,
`module_secret_delete` and `module_secret_list` methods. Use `with_consumer` on
the module's claim-bound SDK connection; a raw `new` connection cannot supply the
required `own` attestation and the daemon refuses it with `not_found`.
Pass owned bytes as `Secret::new(bytes)` and borrow returned bytes with
`secret.value.expose()`. The client scrubs its owned value, base64, serialized
request and reply buffers on drop and redacts their `Debug`. Copies in SDK and
transport frame buffers are outside this guarantee.
`ModuleSecretError::{VersionConflict, Protected, Limit}` preserve the specific
module-secret refusals; other failures use `Other(CredentialResolverError)`.
Missing values are `Other` with class `CredentialAbsent`. None of these methods
retries automatically, even for transient failures: a lost put reply may already
have incremented the stored version. The caller decides whether to retry.
The methods use a separate `callosum-self` route on the same SDK consumer, so
Callosum keeps its own principal regardless of the member-mapping gate. The
ordinary credential resolver's route and retry behavior are unchanged.
## Fleet epoch records
The four fleet epoch methods use the normal Claustrum route. In a claim-bound
module, use `ClaustrumCredentialResolver::with_consumer` with the module's SDK
consumer. The vault admits `reserved:magic-context`, `reserved:prefrontal` and
`reserved:entorhinal` and chooses the encryption domain from the attested
caller. There is no caller or domain argument; a record cannot be opened from
another caller's domain.
```rust,no_run
use cortexkit_claustrum_client::{
ClaustrumCredentialResolver, CredentialResolverError, FleetEpochOpenRequest,
FleetEpochSealRequest, Secret,
};
async fn round_trip(resolver: &ClaustrumCredentialResolver, aad: &[u8], plaintext: Secret<Vec<u8>>)
-> Result<Secret<Vec<u8>>, CredentialResolverError>
{
let sealed = resolver.fleet_epoch_seal(FleetEpochSealRequest {
aad,
plaintext: &plaintext,
}).await?;
resolver.fleet_epoch_open(FleetEpochOpenRequest {
epoch: sealed.epoch,
nonce: &sealed.nonce,
ciphertext: &sealed.ciphertext,
aad,
}).await
}
```
Store the epoch, nonce, and ciphertext alongside the exact AAD needed to reopen
the record. The client takes and returns bytes, converting to canonical unpadded
base64url on the wire. Plaintext is borrowed from `Secret<Vec<u8>>` when sealing
and returned as `Secret<Vec<u8>>` when opening. The client redacts and scrubs its
owned plaintext, base64 plaintext and serialized buffers. SDK and transport
frame copies are outside this guarantee.
`fleet_epoch_seal_batch` and `fleet_epoch_open_batch` take slices of the same
request types with 1–256 items. The vault remains responsible for checking byte
limits. Reply items follow request order. An open batch returns one
`FleetEpochOpenResult` per input: plaintext or a refusal with the vault's exact
`code()` and `class`. A whole-call refusal, malformed reply, or wrong item count
returns an outer error and no list. All four methods send once and never retry;
retrying a seal can produce a second ciphertext.
The `decode_fleet_epoch_*_reply` functions are usable without transport features.
They take a Response frame's JSON body, including its `result` envelope. Keep
open reply bytes in zeroizing storage too. Decode Error frame bodies (such as
`invalid_params`) with `decode_wire_error`.
## Contract tests
The reply decoders are tested against real bytes the vault serialises: the
tests read `../credentials-module/tests/fixtures/enrollment_wire_contract.json`
at run time, so they run from a checkout of the vault repository and the fixture
is not part of the published package:
```sh
cargo test --locked -p cortexkit-claustrum-client
```
The fixture holds real `list_scoped`, `credential.get`, `credential.get_scoped`,
`credential.status`, `credential.sign`, `credential.public_key`, `credential.seal`
and `credential.report_auth_failure` replies. The Rust tests decode producer-generated
account identity metadata when present, verify absence when omitted, and decode
the report's `accepted` answer. The signing and scoped successes run through the
vault's real read surface and request dispatcher with synthetic test material.
Rust tests pin the decoded Ed25519 key ID, algorithm and exact signature and
public-key hex, and verify the signature over the fixture's message with `ring`.
They also decode the X25519 public-key reply for the vault KEM key that produced
the seal sample.
The seal tests pin that the client sends exactly the producer's accepted request
and decodes its reply's exact bytes.
Login condition tests read the producer's `login-conditions-v1/` samples for
scoped listings and report and clear replies. Fleet epoch tests also read the
tagged Magic Context and Prefrontal samples in
`../credentials-module/tests/fixtures/fleet-epoch-*-v1/` at run time.
## Changes
- 0.17.3: SDK-backed calls report proven route-credit refusals as `Transient`.
See the [changelog](CHANGELOG.md).
- 0.17.2: SDK-backed calls and watches use the `subc-client-rs` 0.43 route-death
verdict. See the [changelog](CHANGELOG.md).
- 0.17.0: `with_consumer` uses `SubcConsumer` from the `subc-client-rs` 0.42 line.
See the [changelog](CHANGELOG.md).
- 0.16.0: optional `org_id` on scoped listings. See the [changelog](CHANGELOG.md).
- 0.15.0: optional `condition` on scoped listing rows, and single-attempt
`report_condition` and `clear_condition`. A vault without login conditions
lists no condition and answers both calls `unknown_method`.
- 0.14.0: typed single and batch fleet epoch seal/open operations and pure reply
decoders. Requires a vault that serves the four `fleet.epoch_*` methods.
- 0.13.0: module-owned secret operations, typed refusals and redacted, zeroizing
value buffers. Requires a daemon with `module_secret.*` support.
- 0.9.0: requires subc-protocol 0.36 and, with the default `transport` feature,
subc-transport 0.17 and subc-os 0.1.30. The client's own API is unchanged, and
no subc type appears in it. The minor version moves so that a consumer still on
subc-protocol 0.34 keeps 0.8 and a single protocol copy, and moves to 0.9 when
it moves to 0.36.
- 0.8.0 (breaking): `ClaustrumCredentialResolver::new` and the hidden
`with_live_consumer_identity` constructor no longer take `project_root`.
`route.open` omits project fields, matching subc-protocol 0.34. Bind identity
carries only harness/session labels; project attribution comes from the
route's session scope. The transport-free decoders, `WatchNotice`, and
`WatchTracker` are unchanged.
- 0.7.0 (breaking): `CredentialPublicKey::algorithm` is now the
`PublicKeyAlgorithm` enum instead of a `String`, and `decode_public_key_reply`
accepts X25519 KEM public keys as well as Ed25519 signing keys. Callers that
compared the field to `"ed25519"` should match `PublicKeyAlgorithm::Ed25519`.
License: MIT.