48 KiB
story_id, story_key, requirement, status, baseline_commit, created
| story_id | story_key | requirement | status | baseline_commit | created |
|---|---|---|---|---|---|
| 1.10 | 1-10-lifecycle-auth-profiles-machine-keys | FR-3 | done | 767428436d + uncommitted Story 1.7/1.8/1.9 worktree |
2026-08-15T19:09:52+03:00 |
Story 1.10: Защитить lifecycle Auth Profiles и machine keys
Status: done
Story
As an администратор, I want безопасно создавать, ротировать и отзывать credentials, so that Agents и Operations получают только необходимый доступ без возможности повторно извлечь секрет.
Operational Brief
Story 1.10 закрывает security identity layer поверх уже hardened Operation/runtime/outbound цепочки. После 1.7–1.9 продукт умеет сохранять immutable Operation, выполнять REST через единый typed runtime и защищать outbound network. Теперь надо сделать так, чтобы все credentials, которые питают эти execution paths, имели строгий lifecycle: raw value принимается только на write boundary, хранится только в encrypted/hash форме, раскрывается только один раз, revocation действует без restart, rotation атомарна, а Admin/MCP/approval boundaries не могут использовать чужой тип ключа.
Значение для плана: это первая половина FR-3. Она делает текущие Auth Profiles, Secrets, MCP keys и approval keys production-safe. Story 1.11 отдельно согласует master-key identity и re-encryption; Story 1.12 отдельно закрывает admin bootstrap/login/session. Нельзя переносить эти будущие задачи внутрь 1.10, но 1.10 должна оставить для них совместимые audit/status/version contracts.
Requirement: FR-3
Primary architecture: AD-15, AD-22, AD-23; AD-1/4/11/16/19/20 conventions
Applicable NFR: NFR-S1, NFR-S2, NFR-S4, NFR-S7, NFR-S8, NFR-O1, NFR-O4, NFR-O5, NFR-C1, NFR-C3, NFR-C4
Primary risk/evidence: credential exfiltration, stale/revoked key acceptance, boundary confusion between MCP/approval/Admin credentials.
Scope
In scope:
- Auth Profile lifecycle for existing bearer/basic/api-key-header/api-key-query configs.
- Workspace Secrets lifecycle used by Auth Profiles: create, rotate, metadata read/list, delete restrictions, execution read/touch.
- MCP machine key lifecycle for Agent endpoints.
- Approval key lifecycle for approval endpoints.
- One-time raw key disclosure semantics and UI cleanup for machine keys.
- Raw secret/key/hash/prefix redaction in API responses, exports, logs, traces, metrics, diagnostics and UI error state.
- Immediate revocation semantics against PostgreSQL source of truth; any cache/projection must revalidate or fail closed.
- Rotation semantics:
- Auth Profile credential rotation is performed by creating a new Secret version and switching current version atomically.
- Machine/approval key rotation is create-new-key + explicit revoke-old-key policy, never recover old raw value.
- Bounded audit events for create/rotate/revoke/delete/read-denied outcomes with actor, credential type/ref, action, outcome, Request ID and Trace ID.
- RU/EN UI states for create, rotate, revoke, one-time reveal, stale response and destructive confirmation.
- Capability Inventory/baseline evidence for FR-3 after tests pass.
Out of scope:
- Master-key fingerprint/epoch registration, re-encryption and restore proof; owned by Story 1.11.
- Admin bootstrap/login/session/CSRF recovery; owned by Story 1.12.
- OpenAPI security scheme mapping beyond preserving current Auth Profile refs; detailed importer UX belongs Epic 2.
- Agent catalog lifecycle redesign; owned by Story 1.13.
- Approval side-effect workflow redesign; owned by Story 1.14.
- Full backup/restore qualification and recovery RPO/RTO; owned by Epic 7/8.
- New RBAC/teams/SSO/multi-workspace; Community remains one workspace/admin, but object-scope checks remain mandatory.
Acceptance Criteria
-
Auth Profile write boundary stores references only
- Given a new Auth Profile
- When administrator provides credential material
- Then raw material is accepted only through a protected Secret write/rotate contract
- And Auth Profile stores only typed Secret refs and compatible auth config
- And Operations, YAML export, Admin API responses and UI state never contain raw credential material.
-
Secrets are encrypted before persistence and never read back
- Given Secret create or rotate
- When the write succeeds
- Then plaintext is encrypted before persistence and only ciphertext/key-version metadata is stored
- And list/get/export/diagnostics return metadata only
- And privileged Admin API callers cannot retrieve plaintext after save.
-
MCP/approval key one-time disclosure
- Given creation of MCP key or approval key
- When creation succeeds
- Then raw key is returned exactly once in the create response
- And persistence stores only safe hash, non-sensitive bounded prefix, scope, status and timestamps
- And no subsequent get/list/export/diagnostic path can reconstruct or return the raw key.
-
Machine key scope is exact and non-leaking
- Given MCP key used against an Agent endpoint
- When workspace, Agent, key kind, status, expiry or scope does not match
- Then access is denied with safe unauthorized/forbidden outcome
- And response/log/trace/history does not reveal whether another workspace/Agent/key exists.
-
Approval key is accepted only at approval boundary
- Given approval key
- When it is used for MCP initialize/list/call or Admin API
- Then it is rejected before execution
- And MCP/Admin credentials cannot be used to approve/deny pending approval requests
- And approval key allowed-origin policy is enforced where origin is available.
-
Revocation is immediate and fail-closed
- Given active Auth Profile credential, MCP key or approval key
- When administrator revokes/deletes/disables it
- Then PostgreSQL transaction records the terminal state atomically
- And new MCP/approval/Auth Profile resolution observes revocation without service restart
- And any cache or Valkey projection is invalidated or treated as untrusted when status cannot be confirmed.
-
Rotation is explicit and atomic
- Given Auth Profile credential rotation
- When a new Secret version is submitted
- Then the new version is encrypted and validated before becoming current
- And the previous version is no longer used for new execution after commit
- And Operation/Auth Profile refs do not need raw values or mass rewrite.
- Given machine/approval key rotation
- When administrator creates a replacement key
- Then new key is independently scoped and disclosed once
- And old key remains active or is revoked only according to explicit confirmed policy.
-
Audit evidence is bounded and non-secret
- Given create, rotate, revoke, delete, denied access or failed credential operation
- When outcome is recorded
- Then audit/log event includes actor if available, credential type/ref, action, outcome, Request ID and Trace ID
- And raw secret, hash, full prefix, bearer token, ciphertext, request body and internal error text are absent.
-
One-time disclosure UI is safe
- Given raw machine/approval key is shown after create
- When user copies it, closes modal, navigates, refreshes, goes back or switches workspace/Agent
- Then raw value is cleared from app state/DOM and cannot be restored
- And UI clearly warns in RU/EN that the value cannot be shown again.
-
Credential UI states and destructive confirmations
- Given Secrets/Auth Profiles/API Keys UI
- When create, rotate, revoke, delete or load fails/succeeds
- Then loading, empty, error, success, confirmation and stale-response states are implemented in RU and EN
- And destructive revoke/delete requires explicit confirmation and disables duplicate submit.
-
Security/regression gates
- Given Story 1.10 completion
- When targeted suites and final gates run
- Then Admin API, MCP, runtime, registry and UI tests prove no raw secrets leak, revoked credentials stop access, wrong-kind credentials fail closed, and
just verifypasses - And Capability Inventory FR-3 evidence is updated only after successful verification.
Tasks / Subtasks
-
Task 1 — Freeze RED credential lifecycle/security oracle (AC: 1–11)
- Add registry/Admin/MCP tests proving raw Secret values and raw machine keys appear only on write/create response and never on list/get/export/error/log/debug paths.
- Add negative tests for wrong workspace/Agent/key kind/scope/status/expiry and approval-vs-MCP boundary confusion.
- Add revocation/rotation tests proving immediate no-restart effect on Admin Test, MCP
tools/list, MCPtools/calland approval endpoints. - Add UI/Playwright tests for one-time disclosure cleanup, revoke confirmation, stale response and RU/EN states.
-
Task 2 — Harden domain models and wire DTOs (AC: 1–5, 8)
- Introduce/verify typed credential lifecycle actions and stable error/audit codes in
crank-core; do not expose secret/hash/ciphertext fields via serializable public DTOs. - Split create response DTOs from read/list DTOs so
secretraw field cannot accidentally appear in non-create responses. - Add bounded validation for key names, scopes, allowed origins, expiries, auth config fields and Secret payload shapes.
- Ensure all boundary errors carry Request ID/Trace ID and localized safe messages without raw causes.
- Introduce/verify typed credential lifecycle actions and stable error/audit codes in
-
Task 3 — Registry persistence and transactional lifecycle (AC: 2–8)
- Store/rotate Secret versions transactionally with checked version increment, workspace predicate and active-status validation.
- Revoke/delete machine keys through explicit terminal lifecycle; delete must not erase audit/provenance needed for historical evidence.
- Add or update append-only migration only if required for audit/revoked/version fields; use Story 1.4 migration authority, never runtime/startup DDL.
- Add PostgreSQL tests for concurrent create/rotate/revoke, duplicate names, stale revocation, wrong workspace, and no plaintext/hash exposure.
-
Task 4 — Admin API service/route hardening (AC: 1–3, 6–8, 10)
- Enforce owner/write authorization for Secret/Auth Profile/key mutations; read-only roles must fail safely if present in fixtures.
- Validate Auth Profile secret refs in workspace at create and before Operation publish/test execution; missing/revoked refs return typed outcome.
- Add rotate key operation or document/implement create-new + revoke-old as the only machine-key rotation contract.
- Emit bounded audit/log events for create/rotate/revoke/delete success and failure with actor/request/trace IDs.
-
Task 5 — MCP and approval boundary enforcement (AC: 4–6, 8)
- Ensure MCP key lookup requires exact workspace slug, Agent slug,
mcp_clientkind, active status, expiry and required scope before execution/listing. - Ensure approval lookup requires
approvalkind, active status, expiry, approval scope and approval boundary only. - Map denied/unavailable outcomes through existing typed execution/boundary error paths without metadata leakage.
- Prove revoked/wrong-kind/wrong-Agent/wrong-workspace keys stop access without restart and without relying on stale cache.
- Ensure MCP key lookup requires exact workspace slug, Agent slug,
-
Task 6 — Runtime/Auth Profile resolution hardening (AC: 1–2, 6–8)
- Resolve Auth Profile and all referenced Secrets under workspace scope immediately before execution.
- Reject missing/revoked/deleted Secret/Auth Profile as typed non-secret execution failures.
- Touch last-used metadata with bounded best-effort semantics that does not change product result or leak DB errors.
- Preserve Story 1.9 reserved-header provenance: Auth Profile credentials remain system-owned and cannot be overridden by mapping/static headers.
-
Task 7 — UI one-time disclosure and credential lifecycle UX (AC: 9–10)
- Update API Keys UI to keep raw key in modal-local state only, clear on close/navigation/workspace/Agent switch/refresh/back, and never place raw key into persistent state.
- Add explicit rotate-as-create-new + optional revoke-old workflow or clear copy explaining the policy; destructive revoke/delete needs confirmation and duplicate-submit lock.
- Update Secrets UI create/rotate/delete states with request generation guard, stale response discard, disabled submit, safe errors and RU/EN strings.
- Ensure DOM/test snapshots/error telemetry cannot recover raw key/secret canaries.
-
Task 8 — Documentation, inventory and evidence (AC: 8, 11)
- Update
docs/admin-api.md,docs/mcp-interface.md,docs/data-model.md,docs/database-schema.md,docs/manual-regression-checklist.mdwith actual credential lifecycle contracts. - Update
docs/capability-inventory.jsonand baseline manifest/results only after tests pass; FR-3 implemented evidence must point to real commands. - Record deferred master-key/re-encryption work explicitly as Story 1.11 scope, not as completed in 1.10.
- Run explicit Community scope scan over every new/updated Story 1.10 path.
- Update
-
Task 9 — Final verification (AC: 11)
- Run targeted Rust unit/integration suites for registry, Admin API, MCP, runtime and outbound/auth interactions.
- Run UI build and relevant Playwright specs for Secrets/API Keys/approval flow.
- Run
just migration-contract-check, boundary checks, capability inventory check,git diff --check, and finaljust verify. - Update Story File List and Dev Agent Record with exact commands/results before moving to review.
Review Findings
- [Review][Patch] Platform key delete tombstones must not reserve names after delete — Fixed in Chunk 1: added v6 partial unique index excluding deleted rows and create-after-delete regression coverage.
- [Review][Patch] Disabled/non-active Secrets can still be referenced, rotated, touched and used — Fixed in Chunk 1: active-status validation now applies to Auth Profile refs, rotation, current-version reads and execution resolution.
- [Review][Patch] Secret rotation is not atomic and lacks active-status/CAS protection — Fixed in Chunk 1: rotation now locks the Secret row, validates active status and updates with checked current_version.
- [Review][Patch] Failed credential operations are not audited — Fixed in Chunk 1: failed Secret/AuthProfile/platform-key create/rotate/revoke/delete paths emit bounded non-secret audit records.
- [Review][Patch] Secret delete can race concurrent Auth Profile creation and leave a profile pointing at a deleted Secret — Fixed in Chunk 1: AuthProfile save and Secret delete now share transaction-scoped advisory locks and delete rechecks refs in-transaction.
- [Review][Patch] Platform key terminal states are not guarded; deleted keys can become revoked again — Fixed in Chunk 1: revoke/delete now use state predicates and typed inactive-key conflicts.
- [Review][Patch] Approval allowed-origin policy rejects missing Origin and does not fail-closed on duplicate Origin — Fixed in Chunk 2: missing Origin is allowed for non-browser/server-side clients, duplicate/malformed Origin fails closed, with unit and integration coverage.
- [Review][Patch] Known approval-key denial by scope/origin is not written as bounded audit evidence — Fixed in Chunk 2: known approval-key scope/origin denial now emits bounded structured audit log evidence with credential ref, outcome, reason and request/trace correlation only.
- [Review][Patch] Copying a one-time API key does not clear the raw key from DOM — Fixed in Chunk 3: copy now wipes the reveal value immediately and Playwright asserts the DOM is empty after copy.
- [Review][Patch] Pending API-key create response can reveal a raw key after modal close or workspace/Agent/key-kind switch — Fixed in Chunk 3: create responses are guarded by modal/workspace/Agent/key-kind generation and stale responses are discarded without rendering the raw key.
- [Review][Patch] API-key load/revoke/delete flows lack stale-response and duplicate-submit guards — Fixed in Chunk 3: API-key loading and mutations now carry context guards, and per-key mutation locks disable duplicate revoke/delete.
- [Review][Patch] Browser navigation/BFCache can restore API-key reveal DOM without an explicit wipe hook — Fixed in Chunk 3: pagehide/pageshow cleanup wipes the reveal value, with Playwright navigation/back coverage.
- [Review][Patch] Secret modal submit can be unlocked by close/reopen and stale completion can close a newer modal — Fixed in Chunk 3: Secret modal submissions now use generation tokens and preserve the pending lock until the owning request settles.
- [Review][Patch] Playwright coverage does not prove the required credential cleanup/stale/duplicate-submit scenarios — Fixed in Chunk 3: API Keys and Secrets specs now cover copy cleanup, stale create discard, navigation/back cleanup and duplicate-submit request counting.
- [Review][Patch] Auth Profile header injection does not remove all case-variant untrusted headers before REST dispatch — Fixed in Chunk 4: runtime Auth Profile injection removes every case-insensitive header variant before inserting the trusted system value, with Bearer and API-key regression tests.
- [Review][Patch] Runtime Auth Profile resolution ignores mismatched
kindversusconfigvariant — Fixed in Chunk 4:AuthConfig::kind()is authoritative and runtime resolution fails closed on mismatched profile/config pairs before using secrets. - [Review][Patch] Operation publish validates Auth Profile existence but not active/current referenced Secrets — Fixed in Chunk 4: operation validation now resolves Auth Profile secret refs, requires active Secret plus current version, and credential lifecycle integration covers publish fail-closed after Secret disablement.
- [Review][Patch] Auth Profile/Secret read-denied execution failures lack bounded credential audit/log evidence — Fixed in Chunk 4: Admin credential resolution denial paths emit bounded credential audit/log evidence with request/trace correlation and no secret material.
- [Review][Patch] Authorization store failures normalize to
runtime_internalinstead of a typed credential/store outcome — Fixed in Chunk 4: authorization store failures now normalize tosafety_store_unavailablewith after-delay/certain semantics and targeted runtime test coverage. - [Review][Patch] Capability baseline provenance does not prove the reviewed FR-3 credential changes — Fixed in Chunk 4: baseline results now include an accepted
rust-admin-integrationcredential lifecycle run linked to FR-3 credential/API flows and manifest checksum was updated. - [Review][Patch] MCP and approval bearer parsing accepts ambiguous duplicate Authorization headers — Fixed: bearer parsing now requires exactly one Authorization header; duplicate-header regression is covered in
crank-community-mcp accesstests. - [Review][Patch] Platform key touch can allow one post-revocation MCP/approval request — Fixed:
touch_platform_api_keynow revalidates active/non-expired state at touch time; MCP and approval paths map inactive touch to 401 instead of a post-revocation success. - [Review][Patch] MCP Auth Profile resolution does not enforce active Secret parity and treats best-effort Secret touch as fatal — Fixed: MCP Auth Profile resolution now requires active Secret records before decrypting and treats Secret last-used touch as bounded best-effort audit metadata.
- [Review][Patch] Pending approval invocation history stores raw request payload and approval response preview — Fixed: pending-approval Invocation History now stores only approval metadata previews, not the raw request payload or full approval response; integration coverage asserts canary absence.
- [Review][Patch] MCP machine-key denied access lacks bounded credential audit evidence — Fixed: missing/ambiguous, unknown/inactive and scope-denied MCP key paths now emit bounded credential audit evidence with credential type, outcome, reason and request/trace correlation only.
- [Review][Patch] Approval key revocation lacks no-restart endpoint evidence for list/approve/deny — Fixed: approval integration now revokes an approval key against a live MCP server and proves list/approve/deny all return 401 without restart while the request remains pending.
- [Review][Patch] MCP tool error remediation text is not localized for EN clients — Fixed: MCP confirmation messages and suggested actions are localized for RU/EN; unit coverage asserts EN retry and confirmation text.
- [Review][Patch] Concurrent approval finish conflicts are reported as persistence unavailable — Fixed:
finish_approval_requestreturningNonenow maps to stable 409approval_state_conflict; storage failures remain 503persistence_unavailable. - [Review][Defer] Auth Profiles have no lifecycle status for retired/disabled profiles [crates/crank-community-mcp/src/app.rs:1007] — deferred, pre-existing; current Story 1.10 can enforce Secret/credential terminal state, but adding AuthProfile status/tombstones is a broader domain/storage lifecycle extension.
- [Review][Patch] Machine-key bearer secrets must use a full-entropy CSPRNG instead of UUIDv7 — Fixed: machine secrets now use 32 CSPRNG bytes encoded as base64url; key identifiers remain UUIDv7.
- [Review][Patch] Platform-key writes need bounded name/scope validation, duplicate-scope rejection and future expiry enforcement — Fixed: create validates trimmed bounded names, scope count/uniqueness/kind compatibility and future expiry.
- [Review][Patch] Secret create/rotate must validate bounded payload shape against
SecretKindbefore encryption or current-version switch — Fixed: bounded JSON size and kind-specific payload shapes are enforced before encryption and persistence. - [Review][Patch] Auth Profile writes must bound names and validate HTTP header/query parameter names, not only the enum variant — Fixed: names and HTTP header/query identifiers now use bounded fail-closed validation.
- [Review][Patch] Credential service spans must skip
audit_contextandcreated_byso actor email/session IDs are not captured by#[instrument]— Fixed: sensitive actor/audit inputs are explicitly skipped on credential service spans. - [Review][Patch] Early platform-key and Secret lookup/expiry failures must emit the same bounded failure audit evidence as later mutation failures — Fixed: early lookup, expiry and registry failures now emit the shared bounded audit contract.
- [Review][Patch] Known MCP scope denial must retain the resolved bounded platform-key ID instead of auditing
credential_ref = unknown— Fixed: known-key scope denials audit the resolved key ID; unknown credentials remain non-enumerating. - [Review][Patch] Credential mutation audit payloads need a stable bounded reason/error code so operational failures are distinguishable — Fixed: audit records include stable bounded
reasoncodes sourced from typed API errors. - [Review][Patch] Platform-key and Secret touch queries must linearize status validation with the row update to close post-revocation execution races — Fixed: locked CTEs serialize lifecycle validation with touch; deterministic PostgreSQL race tests cover revoke/disable winners.
- [Review][Patch] Secret rotation must not return an ambiguous error after a successful commit when the metadata read fails — Fixed: rotation returns committed version metadata directly from the transactional registry result.
- [Review][Patch] Approval origins must be parsed and stored canonically with valid host/port and no userinfo/path/query/fragment — Fixed: URL parsing accepts only canonical HTTP(S) origins and rejects malformed or non-origin components and duplicates.
- [Review][Patch] A stale successful key-create response must reconcile server metadata, warn about the lost one-time value and not let an older request unlock a newer modal — Fixed: stale success wipes raw data, reloads metadata, shows a lost-value warning and uses modal generations.
- [Review][Patch] Playwright must prove successful/failed MCP config copy clears or preserves every raw-key DOM copy — Fixed: E2E covers successful cleanup and clipboard-failure preservation.
- [Review][Patch] Playwright must prove duplicate revoke/delete actions emit only one destructive key request — Fixed: E2E double-action coverage asserts exactly one revoke/delete request.
- [Review][Patch] Playwright must execute the Secret rotation stale-response guard, not only the create branch — Fixed: E2E executes stale rotate completion after close/reopen and verifies the newer modal remains authoritative.
- [Review][Patch] MCP no-restart revocation evidence must cover initialize and tools/call in addition to tools/list — Fixed: live-server integration proves revoked keys fail initialize, tools/list and tools/call without restart or leakage.
- [Review][Defer] Secret deletion hard-deletes encrypted versions and there is no explicit disable/tombstone API [crates/crank-registry/src/postgres/secret.rs:315] — deferred, pre-existing; durable Secret tombstones and disable/restore semantics require a broader schema and retention-policy change.
- [Review][Defer] Credential audit recording remains best-effort after lifecycle transactions rather than using a durable transactional outbox [apps/admin-api/src/service.rs:317] — deferred, pre-existing; atomic mutation/audit delivery requires a cross-cutting persistence and delivery architecture change.
Dev Notes
Current brownfield state
apps/admin-api/src/service/secrets.rsalready creates Secrets, encrypts payloads throughSecretCrypto, stores ciphertext insecret_versions, rotates by inserting a new version and movingsecrets.current_version, and blocks delete when an Auth Profile references the Secret.apps/admin-api/src/service/secrets.rscreates Auth Profiles as config objects referencing existing Secret IDs. It validates kind/config shape and current workspace Secret existence, but Auth Profile lifecycle is create/get/list only.apps/admin-api/src/service/api_keys.rscreates Agent-scoped platform keys, generates raw secret once, storeshash_access_secret(secret), stores bounded prefix, scopes, kind, status and timestamps, and returns{ api_key, secret }on create.crates/crank-registry/src/postgres/api_key.rsfilters active, non-expired, kind-specific keys for MCP/approval lookup and toucheslast_used_atwith one-minute throttling.crates/crank-community-mcp/src/access.rsfirst verifies static Agent key for MCP, then falls back toMachineCredentialVerifier; approval access uses separateget_approval_api_key_by_secret_for_agent_slug.- UI surfaces already exist:
apps/ui/js/api-keys.js,apps/ui/html/api-keys.html,apps/ui/js/secrets.js,apps/ui/html/secrets.html, and Playwright specsapi-keys.spec.js,secrets.spec.js. - Current UI displays one-time key in
#reveal-key-value, but story must prove it is cleared on close/navigation/workspace/Agent switch and not restored by back/refresh.
Current gaps and traps to avoid
- Do not treat CRUD as lifecycle. Story requires terminal states, rotation policy, revocation evidence, one-time disclosure and audit.
- Do not expose raw key by reusing
CreatedPlatformApiKeyResponsefor list/get/export. Create response and read DTO must remain separate. - Do not log or serialize
secret_hash, ciphertext, raw token, full prefix, credential-bearing URL, or parser/internal error chain. - Do not implement master-key identity/re-encryption here; only preserve
key_versioncompatibility and document Story 1.11 dependency. - Do not rely on Valkey/cache for credential truth. PostgreSQL is the mandatory source of truth. Cache failures on credential status must fail closed.
- Do not let approval keys authenticate MCP execution. Do not let MCP/Admin credentials approve/deny pending approval requests.
- Do not let operation/static/mapped headers override Auth Profile credential headers; preserve Story 1.9 trusted-header provenance.
- Do not hard-delete active/revoked keys if audit/provenance would be destroyed. If UI keeps delete for revoked keys, define whether delete is metadata tombstone, soft delete, or restricted cleanup.
- Do not add teams/RBAC/SSO. Community is one workspace/admin, but tests still need scoped object access and safe not-found/denied behavior.
Architecture compliance
- Domain enums, DTO invariants and safe serialization belong in
crank-core; SQLx belongs incrank-registry; Axum route mapping belongs in Admin/MCP composition roots. - Durable schema changes, if any, must be append-only through migration authority. Do not edit frozen v1/v2/v3/v4/v5 sources/checksums except by adding a new migration descriptor.
- All newly user-visible strings must be RU and EN together.
- Metrics must use typed low-cardinality labels only. Request ID/Trace ID/key ID/secret ID/full prefix must not become ordinary metric labels.
- Audit/log events may include bounded credential refs and action/outcome, but not secret material, hash or ciphertext.
- Boundary errors must include safe Request ID/Trace ID from Story 1.5 and use typed errors from Story 1.8 where execution is involved.
File map
Likely UPDATE:
crates/crank-core/src/access.rscrates/crank-core/src/operation.rscrates/crank-runtime/src/auth.rscrates/crank-runtime/src/execution_failure.rscrates/crank-runtime/src/executor.rsapps/admin-api/src/dto.rsapps/admin-api/src/error.rsapps/admin-api/src/routes/agents.rsapps/admin-api/src/routes/auth_profiles.rsapps/admin-api/src/routes/secrets.rsapps/admin-api/src/service.rsapps/admin-api/src/service/api_keys.rsapps/admin-api/src/service/secrets.rsapps/admin-api/src/service/operations.rscrates/crank-community-mcp/src/access.rscrates/crank-community-mcp/src/app.rscrates/crank-community-mcp/src/app/stages.rscrates/crank-community-mcp/src/approval_execution.rscrates/crank-registry/src/error.rscrates/crank-registry/src/model.rscrates/crank-registry/src/postgres/api_key.rscrates/crank-registry/src/postgres/auth.rscrates/crank-registry/src/postgres/secret.rscrates/crank-registry/src/migrations/authority.rscrates/crank-registry/src/migrations/schema_guard.rsdocs/schemas/migration-sequence.jsonapps/ui/js/api-keys.jsapps/ui/html/api-keys.htmlapps/ui/js/secrets.jsapps/ui/html/secrets.htmlapps/ui/js/i18n.jsapps/ui/tests/e2e/api-keys.spec.jsapps/ui/tests/e2e/secrets.spec.jsapps/admin-api/tests/integration/community_access_usage.rsapps/admin-api/tests/integration/secrets_import_auth.rscrates/crank-registry/tests/integration/workspace_access.rscrates/crank-registry/tests/integration/operations_artifacts.rscrates/crank-community-mcp/tests/integrationor existingmcp-serverintegration tests that exercise access boundariesdocs/admin-api.mddocs/mcp-interface.mddocs/data-model.mddocs/database-schema.mddocs/manual-regression-checklist.mddocs/capability-inventory.jsondocs/capability-baseline/manifest.jsondocs/capability-baseline/results.json
Likely NEW if schema/audit gaps require it:
crates/crank-registry/src/migrations/credential_lifecycle_v6.sqlcrates/crank-registry/src/migrations/credential_lifecycle_v6.rsapps/admin-api/tests/integration/credential_lifecycle.rscrates/crank-community-mcp/tests/integration/credential_lifecycle.rsor equivalent under current test layout
Do not modify:
- Frozen migration source bytes for v1–v5 except expected sequence metadata when adding v6.
- Cargo/npm/toolchain versions unless an explicit Story task proves a required dependency and user approves it.
- Operation lifecycle semantics from 1.7, execution taxonomy from 1.8, outbound policy from 1.9 except preserving Auth Profile provenance.
Testing requirements
Required RED/P0 tests before implementation:
- Create Secret with canary value → list/get/export/error/log/debug do not contain canary; current Secret metadata has no plaintext.
- Rotate Secret referenced by Auth Profile → next Admin Test/MCP execution uses new version; old value no longer appears; refs unchanged.
- Missing/revoked/deleted Secret/Auth Profile → execution fails with typed non-secret error and persists safe history.
- Create MCP key → create response contains raw exactly once; list/get/export never contain raw; hash is never serialized.
- Revoke MCP key → subsequent
initialize,tools/list,tools/callfail without restart. - Wrong Agent/workspace MCP key → safe denied/not-found, no metadata leakage.
- Approval key → approval endpoints accepted only with approval scopes; MCP execution/Admin API reject it.
- MCP key/Admin credential → approval endpoint rejects before decision mutation.
- Duplicate/concurrent key create/revoke/rotate → deterministic typed result; no 500/raw storage error.
- UI key create modal → raw key is visible only in reveal step, copy works, close/navigation/workspace/Agent switch clears it.
- UI revoke/delete/rotate → confirmation, loading, duplicate-submit lock, error recovery, RU/EN strings.
Suggested targeted commands:
cargo test -p crank-core access operation -- --test-threads=1
cargo test -p crank-runtime auth -- --test-threads=1
cargo test -p crank-registry --test integration workspace_access operations_artifacts -- --test-threads=1
cargo test -p admin-api --test integration credential_lifecycle -- --test-threads=1
cargo test -p admin-api --test integration community_access_usage secrets_import_auth -- --test-threads=1
cargo test -p mcp-server --test integration catalog_access -- --test-threads=1
cd apps/ui && npx playwright test tests/e2e/api-keys.spec.js tests/e2e/secrets.spec.js --project=chromium
just migration-contract-check
just rust-boundaries
just capability-inventory-check
python3 scripts/check-community-scope.py --root . --files <every NEW/UPDATE path>
git diff --check
just verify
Previous story intelligence
- Story 1.7 showed that “implemented UI/API flow” is insufficient when the durable state model is mutable. For 1.10, lifecycle invariants must be enforced in domain + PostgreSQL transaction, not only in UI buttons.
- Story 1.8 established typed execution errors and parity. Credential resolution failures in execution paths must use that taxonomy rather than raw
500/ad-hoc status. - Story 1.9 established trusted header provenance and adapter-owned dispatch evidence. Auth Profile credentials are system-owned headers/query params and must preserve that invariant.
- Review loops repeatedly found overstated evidence. Do not mark FR-3 implemented until tests prove raw disclosure, revocation, boundary separation and UI cleanup.
References
_bmad-output/planning-artifacts/epics.md— FR-3 and Story 1.10 AC._bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/prd.md— FR-3 consequences and FR-43 recovery relation._bmad-output/planning-artifacts/prds/prd-crank-2026-08-03/addendum.md— backup/restore evidence contract involving encrypted Auth Profile._bmad-output/planning-artifacts/architecture/architecture-crank-2026-08-03/ARCHITECTURE-SPINE.md— AD-15, AD-16, AD-22, AD-23._bmad-output/implementation-artifacts/1-9-outbound-rest.md— previous story handoff and Auth Profile reserved-header boundary.apps/admin-api/src/service/secrets.rs— current Secrets/Auth Profile service behavior.apps/admin-api/src/service/api_keys.rs— current machine key create/revoke/delete behavior.crates/crank-registry/src/postgres/api_key.rs— current key persistence and lookup.crates/crank-community-mcp/src/access.rs— current MCP/approval credential boundary.apps/ui/js/api-keys.js,apps/ui/js/secrets.js— current credential UI.
Dev Agent Record
Agent Model Used
GPT-5 Codex
Debug Log References
- 2026-08-15: Story context created by
bmad-create-story. - 2026-08-15: Story moved to in-progress; baseline commit
767428436d3a54e60809a727044dfcec48e1f1ddplus uncommitted Story 1.7/1.8/1.9 worktree. - 2026-08-15: Added RED/GREEN Admin credential lifecycle tests for one-time machine key disclosure, duplicate key typed conflict, Secret plaintext canary redaction and approval allowed-origin validation.
- 2026-08-15: Added RED/GREEN MCP integration coverage for approval
allowed_originsenforcement and no-restart revoked MCP key rejection on an existing session. - 2026-08-15: Hardened duplicate platform-key constraint mapping to typed 409
platform_api_key_name_conflict; added approval origin validation and MCP approval-origin boundary check. - 2026-08-15: Hardened API Keys UI one-time reveal cleanup; raw key DOM value is wiped on modal close, modal open, Agent/key-kind switch and workspace change.
- 2026-08-15: Added typed secret-reference conflict code
secret_referenced_by_auth_profile; delete-denied path remains 409 but no longer emits genericconflict. - 2026-08-15: Added Admin Test rotation proof: Auth Profile Secret rotation changes the next execution credential without rewriting the Operation/Auth Profile refs and without exposing old/new raw values in Auth Profile responses.
- 2026-08-15: Added Admin credential audit events for Secret create/rotate/delete/delete-denied, Auth Profile create, platform key create/revoke/delete. Events carry actor/session, bounded credential ref/type/action/outcome and request_id/trace_id; raw secret/key/hash/ciphertext are excluded. Audit sink failure is best-effort safe log to avoid losing one-time raw key after DB commit.
- 2026-08-15: Hardened terminal delete semantics for platform keys: delete now preserves metadata/provenance as
deleted, while revoked/deleted keys remain unusable for MCP/approval access. - 2026-08-15: Hardened Secrets UI stale/duplicate-submit behavior: modal fields clear on close/workspace switch, create/rotate submit is locked while in flight, and stale workspace responses are discarded.
- 2026-08-15: Updated credential lifecycle docs and Capability Inventory evidence; baseline manifest checksum was refreshed after the inventory change.
- 2026-08-15: Verification passed:
cargo fmt --all --check;cargo test -p admin-api --test integration integration::credential_lifecycle -- --test-threads=1(5 passed);cargo test -p admin-api --test integration integration::secrets_import_auth -- --test-threads=1(6 passed);cargo test -p admin-api --test integration integration::community_access_usage::manages_agent_platform_api_keys -- --exact --test-threads=1;cargo test -p mcp-server --test integration integration::catalog_access -- --test-threads=1(19 passed);cd apps/ui && npx playwright test tests/e2e/api-keys.spec.js --project=chromium;cd apps/ui && npx playwright test tests/e2e/secrets.spec.js --project=chromium(4 passed);just ui-build;just migration-contract-check;just rust-boundaries;just capability-inventory-check; scopedgit diff --check; explicit Community scope scan over 30 Story 1.10 paths. - 2026-08-15: Final verification passed:
just verifycompleted successfully after the clippy argument-count refactor. - 2026-08-15: Explicit Community scope scan including the ignored BMad story artifact failed on story boundary terminology (
one-time,SSO,multi-workspace); production/test/UI path scan passed. The story artifact remains ignored/local evidence, not shipped Community surface. - 2026-08-21: Review patch pass closed MCP/approval findings: duplicate Authorization now fails closed; platform-key touch revalidates active/non-expired state; MCP Auth Profile resolution requires active Secrets and treats Secret touch as best-effort metadata; pending approval Invocation History stores only approval metadata previews; MCP/approval denied credential paths emit bounded audit evidence; approval-key revocation is proven against list/approve/deny without restarting the MCP server; MCP tool-error remediation is RU/EN localized; concurrent approval finish conflicts now return stable 409.
- 2026-08-21: Verification passed:
cargo test -p crank-community-mcp access --lib -- --test-threads=1(4 passed);cargo test -p crank-community-mcp tool_error --test unit -- --test-threads=1(6 passed);cargo test -p mcp-server --test integration integration::catalog_access::approval_access -- --test-threads=1(11 passed);cargo check -p admin-api -p mcp-server;cargo test -p crank-registry --test integration workspace_access -- --test-threads=1(8 passed);cargo fmt --all --check;git diff --check; explicit Community scope scan over 8 production/test patch files passed. Explicit scan including this ignored BMad artifact still flags pre-existing story terminology and is not treated as shipped Community surface evidence. - 2026-08-21: Final closure checks completed after full-gate drift fixes:
just verifypassed;just verify-uipassed via UI Docker build; explicit Community scope scan over 15 changed/new production/test paths passed;git diff --checkpassed. - 2026-08-21: Full-gate drift corrections made during closure:
Cargo.lockupdatedh2from 0.4.15 to 0.4.16 to satisfyRUSTSEC-2026-0258; migration command and migration-authority tests now expect canonical v6 sequence; registry Auth Profile fixture tests now create active Secret records before saving Secret-backed Auth Profiles. - 2026-08-25: Final adversarial review remediation closed all 16 remaining PATCH findings: CSPRNG key material, bounded credential validation, safe spans/audit reasons, linearized credential touches, unambiguous Secret rotation results, canonical approval origins, stale/duplicate UI guards and complete no-restart MCP revocation evidence.
- 2026-08-25: Final verification passed: targeted Admin credential lifecycle (7), registry credential race (2), MCP access unit (5), MCP revoked-key integration (1), API Keys/Secrets Playwright (10), explicit Community scope scan (15 files),
git diff --check, fulljust verifyand Docker-backedjust verify-ui.
Completion Notes List
- Ultimate context engine analysis completed — comprehensive developer guide created.
- Implementation completed for 1.10 credential boundaries: raw key one-time list redaction, duplicate key typed conflict, Secret plaintext canary redaction, approval origin validation/enforcement, immediate revoked MCP key denial without restart and UI raw-key cleanup.
- Secret deletion blocked by Auth Profile now has a stable safe error code and recovery hint for UI/operator handling.
- Auth Profile Secret rotation is verified against real Admin Test execution: old credential used before rotation, new credential used after rotation, refs unchanged, no plaintext in Auth Profile readback.
- Credential mutation audit is now implemented through the existing
AuditSinkseam and covered by a canary integration test proving request/trace IDs are present and secret material is absent. - Platform key delete is now terminal soft-delete: metadata remains visible as
deleted, provenance is preserved, and raw/hash material is not exposed. - Secrets UI now clears sensitive modal inputs, rejects duplicate submit while saving, discards stale workspace responses and keeps safe localized create/rotate/delete states.
- Documentation, Capability Inventory and baseline manifest now describe the actual FR-3 credential lifecycle contract. Master-key identity/re-encryption remains explicitly deferred to Story 1.11.
- Review patch pass completed for MCP/approval credential boundaries: revoked keys stop immediately on touch, ambiguous bearer headers fail closed, denied access is audited, pending approval history no longer stores raw payload previews, and approval completion conflicts are classified as conflict rather than storage outage.
- Full closure gate is green: targeted Rust/API/MCP/UI checks,
just verify,just verify-ui, explicit Community scope scan andgit diff --checkpassed on 2026-08-21. - Dependency security gate is green after
h20.4.16 lockfile remediation forRUSTSEC-2026-0258; no product dependency or API behavior was changed for Story 1.10 beyond this security-gate lockfile update. - Final review is closed: all 16 latest PATCH findings are implemented and independently verified. Remaining Auth Profile lifecycle status, Secret tombstone/disable semantics and transactional audit outbox are explicit cross-cutting deferred work, not hidden blockers for the accepted Story 1.10 contract.
File List
_bmad-output/implementation-artifacts/1-10-lifecycle-auth-profiles-machine-keys.mdapps/admin-api/src/error.rsapps/admin-api/src/routes/agents.rsapps/admin-api/src/routes/auth_profiles.rsapps/admin-api/src/routes/secrets.rsapps/admin-api/src/service.rsapps/admin-api/src/service/api_keys.rsapps/admin-api/src/service/demo.rsapps/admin-api/src/service/secrets.rsapps/admin-api/tests/integration.rsapps/admin-api/tests/integration/common.rsapps/admin-api/tests/integration/credential_lifecycle.rsapps/admin-api/tests/integration/secrets_import_auth.rsapps/admin-api/tests/migration_command.rsapps/mcp-server/tests/integration/catalog_access.rsapps/mcp-server/tests/integration/catalog_access/approval_access.rsapps/mcp-server/tests/integration/catalog_access/approval_access/pending.rsapps/mcp-server/tests/integration/catalog_access/approval_access/revocation.rsapps/ui/js/api-keys.jsapps/ui/js/i18n.jsapps/ui/js/secrets.jsapps/ui/tests/e2e/api-keys.spec.jsapps/ui/tests/e2e/secrets.spec.jscrates/crank-core/src/access.rscrates/crank-community-mcp/src/access.rscrates/crank-community-mcp/src/app.rscrates/crank-community-mcp/src/approval_execution.rscrates/crank-community-mcp/src/approval_response.rscrates/crank-community-mcp/src/tool_error.rscrates/crank-community-mcp/tests/unit/tool_error.rscrates/crank-registry/src/migrations/authority_tests.rscrates/crank-registry/src/error.rscrates/crank-registry/src/migrations.rscrates/crank-registry/src/migrations/authority.rscrates/crank-registry/src/migrations/platform_key_name_reuse_v6.rscrates/crank-registry/src/migrations/platform_key_name_reuse_v6.sqlcrates/crank-registry/src/migrations/schema_guard.rscrates/crank-registry/src/postgres/auth.rscrates/crank-registry/src/postgres/api_key.rscrates/crank-registry/src/postgres/secret.rscrates/crank-registry/tests/integration/migrations.rscrates/crank-registry/tests/integration/operations_artifacts.rscrates/crank-registry/tests/integration.rscrates/crank-registry/tests/integration/credential_touch.rs_bmad-output/implementation-artifacts/deferred-work.mdCargo.lockdocs/admin-api.mddocs/mcp-interface.mddocs/data-model.mddocs/database-schema.mddocs/manual-regression-checklist.mddocs/capability-inventory.jsondocs/capability-baseline/manifest.jsondocs/schemas/migration-sequence.json
Change Log
- 2026-08-15: Created Story 1.10 from Epic 1 FR-3 with brownfield Auth Profile, Secret, machine key and approval-key implementation context.
- 2026-08-15: Implemented first Story 1.10 credential boundary hardening pass and recorded targeted verification evidence; story remains in-progress for remaining lifecycle/audit/docs gates.
- 2026-08-15: Completed Story 1.10 credential lifecycle hardening, documentation, inventory evidence and final verification; moved story to review.
- 2026-08-21: Closed MCP/approval review patch findings and refreshed targeted verification evidence.
- 2026-08-21: Closed final verification loop: full
just verify,just verify-ui, explicit Community scope scan and diff checks passed after fixing v6 migration-test drift, registry Secret-backed Auth Profile fixtures andh2security advisory lockfile drift. - 2026-08-25: Closed all remaining adversarial review findings, reran targeted and full repository/UI gates, recorded broader lifecycle/outbox items in the deferred-work ledger and moved Story 1.10 to done.