From 9997605c422099d962e04e29df93e8c2c39c7135 Mon Sep 17 00:00:00 2001 From: Mohammed Naji Date: Mon, 13 Jul 2026 11:13:18 +0400 Subject: [PATCH 1/2] feat(policy): add one-time MCP approvals Implement connection-bound approvals with native elicitation, safe fallback bearers, lifecycle audit records, expiry/replay protection, and serialized audit-safe transitions. --- CHANGELOG.md | 1 + README.md | 2 +- docs/architecture.md | 2 +- docs/config.md | 10 +- docs/security.md | 2 + src/approvals/approval-store.ts | 318 ++++++++++ src/audit/audit-trail.ts | 41 +- src/audit/audit-types.ts | 7 +- src/cli/exit-codes.ts | 4 + src/mcp/server/miftah-server.ts | 267 +++++++- src/mcp/server/operation-pipeline.ts | 28 +- src/utils/errors.ts | 4 + tests/approval-docs-contract.test.ts | 23 + tests/approval-fallback.test.ts | 897 +++++++++++++++++++++++++++ tests/approval-store.test.ts | 246 ++++++++ tests/cli-exit-codes.test.ts | 4 + tests/operation-pipeline.test.ts | 3 +- 17 files changed, 1833 insertions(+), 26 deletions(-) create mode 100644 src/approvals/approval-store.ts create mode 100644 tests/approval-docs-contract.test.ts create mode 100644 tests/approval-fallback.test.ts create mode 100644 tests/approval-store.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index fdca105a..b0739e6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to this project will be documented in this file. The format - [#22](https://github.com/mohanagy/miftah/issues/22) Delivered typed internal secret providers for environment, dotenv, opt-in plaintext, OS keychains, and 1Password; strict external-reference parsing, bounded no-shell execution and process-tree cleanup, automatic redaction registration, provider timeout configuration, and target-scoped doctor readiness diagnostics. - [#23](https://github.com/mohanagy/miftah/issues/23) Delivered opt-in active-profile persistence with explicit process, session, workspace, and config-identity-namespaced global scope; atomic restrictive state writes, safe restore diagnostics, lock precedence, and selection metadata in MCP current-profile output. - [#26](https://github.com/mohanagy/miftah/issues/26) Policy risk classification now records source and confidence, accepts MCP annotations only from explicitly trusted configured upstreams, preserves local override precedence, fails closed on contradictory hints, and defaults unknown tools to destructive risk unless an operator selects the compatible write default. +- [#27](https://github.com/mohanagy/miftah/issues/27) Delivered connection-bound one-time approvals for confirmation-required tools, resource reads, and prompts: generic MCP form elicitation with a safe fallback flow, exact target/argument binding, one-time consumption, expiry and replay protection, bounded in-memory state, lifecycle audit events, and approval management tools. ### Changed diff --git a/README.md b/README.md index bdb63c3a..17885114 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ Routing can use the active profile or rules matching tool arguments: } ``` -When several profiles match, Miftah refuses to guess. Use explicit profile switching for write and destructive actions. The same routing, policy, redaction, and audit pipeline applies to upstream tool calls, resource reads, and prompt retrieval. Policy patterns use each upstream tool's original name for tools, `resources/read` for reads, and `prompts/get` for prompt retrieval. A deny, confirmation-required, blocked, or ambiguous decision is returned before Miftah forwards the read or prompt request. Provider token scopes still matter: local policy cannot make a write-capable provider token read-only. Profiles that set a policy name must reference an existing entry in `policies`, while profiles with no `policy` field keep the default allow behavior. +When several profiles match, Miftah refuses to guess. Use explicit profile switching for write and destructive actions. The same routing, policy, redaction, and audit pipeline applies to upstream tool calls, resource reads, and prompt retrieval. Policy patterns use each upstream tool's original name for tools, `resources/read` for reads, and `prompts/get` for prompt retrieval. A deny, blocked, or ambiguous decision is returned before Miftah forwards the request. A confirmation-required operation pauses for a connection-bound, one-time approval: form-capable MCP clients receive a generic boolean elicitation, while other clients receive a short-lived fallback bearer for `miftah_approve` or `miftah_deny`. Provider token scopes still matter: local policy cannot make a write-capable provider token read-only. Profiles that set a policy name must reference an existing entry in `policies`, while profiles with no `policy` field keep the default allow behavior. Miftah can also match bounded workspace metadata without treating a project file as configuration. It resolves a valid environment hint, then the nearest valid project-marker hint, then matching rules over tool arguments and collected context, then the configured fallback. Rules that select different profiles return `ROUTING_AMBIGUOUS`, and a context hint never authorizes a destructive operation that requires an explicit rule. `miftah_route_preview` and eligible audit records expose only sanitized routing evidence plus risk-classification source/confidence, not raw project environment values, upstream metadata, or project file contents. See [routing context](docs/config.md#routing-context) for the marker schema, root behavior, and evidence boundary. diff --git a/docs/architecture.md b/docs/architecture.md index 86d6fdca..259bc383 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -22,7 +22,7 @@ The server advertises management tools plus tools discovered from the active pro The metadata-only routing context collector is the sole source of workspace context, profile hints, preview evidence, and proxied-operation audit evidence. It reads only allowlisted bounded metadata: file roots, cwd, two environment selectors, strict project markers, package/workspace fields, and a local Git origin. The runtime configuration file remains separate from that input. Once initialized, `MiftahServer` capability-gates `roots/list`, caches only root URIs per client connection, and refreshes only on an advertised roots-list-changed notification. Every proxied operation and route preview receives one immutable snapshot; it uses that snapshot for rule matching, hint selection, and redacted evidence so routing cannot change between those steps. -Every supported MCP request enters one outer audit scope. The scope records one terminal operation event on success or safe failure and also covers discovery/list failures, unknown names, and management tools that do not enter the proxy pipeline. `OperationPipeline` enriches proxied tool calls, resource reads, and prompt retrieval with captured source/target profile, upstream, routing, policy, risk, risk source/confidence, and sanitized `routingEvidence`; it does not emit its own record. It captures the source tool snapshot before awaiting policy work, normalizes only the four MCP behavioral booleans, and accepts them for classification only when the matching configured base upstream explicitly trusts tool annotations. The snapshot fingerprint includes client-visible annotations, so a routed profile with different metadata fails the same schema-compatibility guard as any other differing tool contract. It then captures the source profile state, resolves routing against that fixed active-profile fallback, evaluates the selected profile policy, resolves the exact target upstream route, executes, and redacts the result or error. Route preview remains side-effect-free: it examines only cached compatible snapshots and falls back conservatively when none exists. Tools retain their original upstream names for routing and policy compatibility; resource reads and prompt retrieval use the stable policy names `resources/read` and `prompts/get`. Denied, confirmation-required, blocked, and ambiguous operations never resolve or execute an upstream read/get route. Upstream managers publish typed lifecycle transitions, which the server records as separate audit events without letting audit I/O interrupt cleanup or recovery. +Every supported MCP request enters one outer audit scope. The scope records one terminal operation event on success or safe failure and also covers discovery/list failures, unknown names, and management tools that do not enter the proxy pipeline. `OperationPipeline` enriches proxied tool calls, resource reads, and prompt retrieval with captured source/target profile, upstream, routing, policy, risk, risk source/confidence, and sanitized `routingEvidence`; it does not emit its own record. It captures the source tool snapshot before awaiting policy work, normalizes only the four MCP behavioral booleans, and accepts them for classification only when the matching configured base upstream explicitly trusts tool annotations. The snapshot fingerprint includes client-visible annotations, so a routed profile with different metadata fails the same schema-compatibility guard as any other differing tool contract. It then captures the source profile state, resolves routing against that fixed active-profile fallback, evaluates the selected profile policy, resolves the exact target upstream route, executes, and redacts the result or error. Route preview remains side-effect-free: it examines only cached compatible snapshots and falls back conservatively when none exists. Tools retain their original upstream names for routing and policy compatibility; resource reads and prompt retrieval use the stable policy names `resources/read` and `prompts/get`. Denied, blocked, and ambiguous operations never resolve or execute an upstream read/get route. Confirmation-required operations resolve only enough to bind the exact target, then enter a separate approval lifecycle before upstream session execution: state is connection-bound, the form-elicitation path carries only a generic boolean, and a fallback bearer can approve only the exact bound operation once. Approval audit records store lifecycle action and safe context, never the raw approval bearer or operation arguments. Upstream managers publish typed lifecycle transitions, which the server records as separate audit events without letting audit I/O interrupt cleanup or recovery. `IdentityManager` is an opt-in, process-only fingerprint verifier keyed by the exact profile/upstream target and live upstream session generation. A named upstream identity replaces the profile identity for that target. It discovers the configured read-risk, no-required-input probe and calls it with `{}`; it never treats a probe as credential, authentication, authorization, or scope validation. Verified results are cached only in memory for the bounded `maxAgeMs`; concurrent verification for the same live target coalesces. A stale verified result is reported as `expired`, and a required protected request refreshes it once. Restart, crash, idle replacement, or wrapper replacement invalidates the session generation and requires re-verification. diff --git a/docs/config.md b/docs/config.md index fd77b6ee..d62ea511 100644 --- a/docs/config.md +++ b/docs/config.md @@ -169,7 +169,7 @@ Identity gating is applied only after routing, policy, and target resolution and Miftah applies one safety pipeline to every proxied upstream tool call, resource read, and prompt retrieval. It captures the active profile once at request start, resolves the routing rule using that immutable fallback, evaluates the selected profile's policy before resolving an aggregate route or forwarding, redacts the result or error, and records the terminal operation metadata in audit output. -Routing rules receive a tool's original arguments unchanged. Resource reads expose the requested URI as `args.uri`; prompt retrieval exposes the prompt arguments and always sets `args.name` to the requested prompt name. Policies evaluate upstream tools by their original tool name, resource reads as `resources/read`, and prompt retrieval as `prompts/get`. For example, `deny: ["resources/read"]` blocks all resource reads for the selected profile, while `requireConfirmation: ["prompts/get"]` returns `POLICY_CONFIRMATION_REQUIRED` without forwarding the request. +Routing rules receive a tool's original arguments unchanged. Resource reads expose the requested URI as `args.uri`; prompt retrieval exposes the prompt arguments and always sets `args.name` to the requested prompt name. Policies evaluate upstream tools by their original tool name, resource reads as `resources/read`, and prompt retrieval as `prompts/get`. For example, `deny: ["resources/read"]` blocks all resource reads for the selected profile, while `requireConfirmation: ["prompts/get"]` requires an approval before forwarding the request. Policies classify operations as `read`, `write`, or `destructive` in this order: @@ -182,6 +182,14 @@ MCP annotations are hints, not authority. They cannot lower risk unless the oper Every policy decision carries stable `riskSource` and `riskConfidence` values. Route previews and audit events expose only those enum values, never raw upstream annotations or tool output. `denyRisk` takes precedence over `allowRisk`; `requireConfirmation` returns a structured error instead of forwarding the operation. +### MCP approvals + +When `requireConfirmation` matches, Miftah binds one approval to the current MCP connection, the source and routed profiles, upstream, operation kind, exact target, a normalized argument digest, and a short expiry. It never forwards the protected operation until that approval is consumed, and a consumed, denied, expired, or prior-connection approval cannot be replayed. + +Clients that advertise MCP **form elicitation** receive a generic boolean form (`approved`) and never receive the target arguments, digest, or bearer. Clients without that capability receive a one-time fallback bearer in `POLICY_CONFIRMATION_REQUIRED`; use `miftah_approve` with its `approval` field, then retry the exact operation. `miftah_deny` rejects that pending approval, and `miftah_list_approvals` returns only safe pending metadata. A fallback bearer is connection-bound and should be treated as a short-lived capability, not as a durable credential or a human-identity assertion. + +Approval lifecycle events record request, approval, denial, expiry, and consumption when audit logging is configured. They contain safe profile/upstream/operation metadata and expiry only; they never contain the fallback bearer or full operation arguments. + Audit logging writes local JSONL when a path is configured. Every supported MCP request emits one terminal operation event with a request ID, per-process session ID, source/selected profiles, stable outcome/error code, duration, and any available upstream, routing, policy, and risk metadata; route previews and proxied operations add sanitized `routingEvidence` when a collector snapshot is available. Wrapper and upstream lifecycle transitions emit separate event records. Arguments are excluded unless `includeArguments` is true, and all configured secret values are redacted before writing. Audit directories and files are created with owner-only permissions where the platform supports them. `audit.failureMode` accepts `"fail-closed"` (the default) or `"fail-open"`. Fail-closed verifies the configured sink before dispatch and refuses a request when the sink cannot be prepared; a terminal write error also surfaces as `AUDIT_WRITE_FAILED`. Because terminal writes occur after an upstream operation, that error can leave a non-idempotent operation's outcome indeterminate; do not blindly retry it. Fail-open preserves the request result and exposes a redacted `AUDIT_WRITE_FAILED` entry through `miftah_health`; it should be used only when availability is more important than complete auditability. diff --git a/docs/security.md b/docs/security.md index 64e10166..531974dc 100644 --- a/docs/security.md +++ b/docs/security.md @@ -18,6 +18,8 @@ External secret providers execute only fixed programs with argument arrays and b Audit writes default to fail-closed: Miftah verifies the configured sink before dispatch and refuses a request when the sink cannot be prepared. A terminal write can fail after an upstream side effect has completed, so a post-dispatch `AUDIT_WRITE_FAILED` has an indeterminate outcome and must not prompt a blind retry of a non-idempotent operation. An operator can set `audit.failureMode` to `"fail-open"` for availability-sensitive deployments; Miftah then preserves the request outcome but exposes a redacted `AUDIT_WRITE_FAILED` health entry. This mode trades complete auditability for availability. +An approval bearer is a short-lived capability for one pending, exact MCP operation, not a credential or proof of a human identity. Miftah binds it to the connection and target context, stores only keyed digests, and invalidates it on denial, consumption, expiry, or a new connection. Prefer MCP form elicitation when the client supports it. Do not copy a fallback bearer into logs, tickets, or another connection; approval audit events deliberately omit both the bearer and full operation arguments. + Active-profile state is configuration-owned: MCP callers can select a profile but never a scope or storage path. `workspace` and `global` storage require explicit opt-in, derive a config-identity-namespaced location, and reject arbitrary state paths. A record contains only a format version, scope, config identity, selected profile, and timestamp; it never contains a secret, raw config path, provider output, or other MCP request data. Miftah writes it through a synced temporary file and atomic rename, applies owner-only permissions where supported, and reports a safe write failure without changing the in-memory selection. A configured profile lock wins over stored state; corrupt, stale, or unreadable state falls back safely and exposes only a stable diagnostic code. The explicit runtime configuration is trusted operator input; workspace routing metadata is not. Project markers cannot inject configuration because their only accepted shape maps the configured wrapper name to an already-known profile. They cannot add credentials, environment variables, headers, upstreams, policies, audit controls, or secret references. Miftah reads only named, bounded metadata files within the applicable working-directory/root boundary and does not scan arbitrary project content. diff --git a/src/approvals/approval-store.ts b/src/approvals/approval-store.ts new file mode 100644 index 00000000..30c17665 --- /dev/null +++ b/src/approvals/approval-store.ts @@ -0,0 +1,318 @@ +import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; +import { MiftahError } from "../utils/errors.js"; + +const DEFAULT_TTL_MS = 5 * 60_000; +const DEFAULT_MAX_RECORDS = 128; +const MAX_BEARERS_PER_PENDING_APPROVAL = 8; +const MAX_BEARER_ISSUE_ATTEMPTS = 32; +const acceptsAnyBearer = (): boolean => true; + +export type ApprovalStatus = "pending" | "approved" | "denied" | "consumed" | "expired"; + +export interface ApprovalBinding { + readonly sourceProfile: string; + readonly profile: string; + readonly upstream: string; + readonly operation: string; + /** The actual target identifier, retained only inside the keyed binding digest. */ + readonly name: string; + /** A safe target label suitable for management output and audit events. */ + readonly displayName: string; + readonly arguments: Record; +} + +export interface ApprovalSummary { + readonly id: string; + readonly status: ApprovalStatus; + readonly sourceProfile: string; + readonly profile: string; + readonly upstream: string; + readonly operation: string; + readonly name: string; + readonly expiresAt: string; +} + +export interface ApprovalRequest { + /** A one-time bearer used only by approve/deny; it is never retained or listed. */ + readonly token: string; + readonly approval: ApprovalSummary; + readonly created: boolean; +} + +export interface ApprovalStoreOptions { + readonly createToken?: () => string; + readonly createId?: () => string; + readonly createSessionId?: () => string; + readonly now?: () => Date; + readonly ttlMs?: number; + readonly maxRecords?: number; +} + +interface ApprovalRecord { + readonly id: string; + status: ApprovalStatus; + readonly sourceProfile: string; + readonly profile: string; + readonly upstream: string; + readonly operation: string; + readonly name: string; + readonly sessionId: string; + readonly tokenDigests: Buffer[]; + readonly bindingDigest: Buffer; + readonly expiresAtMs: number; +} + +/** Holds connection-bound approvals without retaining bearer tokens or raw arguments. */ +export class ApprovalStore { + private readonly records = new Map(); + private expiredTransitions: ApprovalSummary[] = []; + private readonly createToken: () => string; + private readonly createId: () => string; + private readonly createSessionId: () => string; + private readonly now: () => Date; + private readonly ttlMs: number; + private readonly maxRecords: number; + private readonly tokenKey = randomBytes(32); + private readonly bindingKey = randomBytes(32); + private sessionId: string; + + constructor(options: ApprovalStoreOptions = {}) { + this.createToken = options.createToken ?? (() => randomBytes(32).toString("base64url")); + this.createId = options.createId ?? randomUUID; + this.createSessionId = options.createSessionId ?? randomUUID; + this.now = options.now ?? (() => new Date()); + this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS; + this.maxRecords = options.maxRecords ?? DEFAULT_MAX_RECORDS; + if (!Number.isInteger(this.ttlMs) || this.ttlMs <= 0) throw new Error("Approval TTL must be a positive integer."); + if (!Number.isInteger(this.maxRecords) || this.maxRecords <= 0) { + throw new Error("Approval record limit must be a positive integer."); + } + this.sessionId = this.createSessionId(); + } + + get activeSessionId(): string { + return this.sessionId; + } + + beginSession(): void { + this.records.clear(); + this.expiredTransitions = []; + this.sessionId = this.createSessionId(); + } + + request(binding: ApprovalBinding, isBearerSafe: (bearer: string) => boolean = acceptsAnyBearer): ApprovalRequest { + this.expire(); + const bindingDigest = this.digestBinding(binding); + const pending = [...this.records.values()].find( + (record) => + record.sessionId === this.sessionId && + record.status === "pending" && + timingSafeEqual(record.bindingDigest, bindingDigest) + ); + if (pending !== undefined) return this.issueToken(pending, false, isBearerSafe); + this.discardTerminalRecords(); + if (this.records.size >= this.maxRecords) { + throw new MiftahError("APPROVAL_LIMIT_EXCEEDED", "APPROVAL_LIMIT_EXCEEDED: too many outstanding approvals"); + } + + const expiresAtMs = this.now().getTime() + this.ttlMs; + const record: ApprovalRecord = { + id: this.createId(), + status: "pending", + sourceProfile: binding.sourceProfile, + profile: binding.profile, + upstream: binding.upstream, + operation: binding.operation, + name: binding.displayName, + sessionId: this.sessionId, + tokenDigests: [], + bindingDigest, + expiresAtMs + }; + this.records.set(record.id, record); + try { + return this.issueToken(record, true, isBearerSafe); + } catch (error) { + this.records.delete(record.id); + throw error; + } + } + + approve(token: string): ApprovalSummary { + const record = this.requirePending(token); + record.status = "approved"; + return summary(record); + } + + deny(token: string): ApprovalSummary { + const record = this.requirePending(token); + record.status = "denied"; + return summary(record); + } + + /** Removes an approval that could not be durably recorded before its bearer was disclosed. */ + revoke(approvalId: string): void { + this.records.delete(approvalId); + } + + /** Claims an accepted form approval without leaving an async window for a second consumer. */ + approveAndConsume(token: string, binding: ApprovalBinding): ApprovalSummary { + const record = this.requirePending(token); + if (!timingSafeEqual(record.bindingDigest, this.digestBinding(binding))) { + throw new MiftahError("APPROVAL_INVALID", "APPROVAL_INVALID: approval token does not match this operation"); + } + record.status = "consumed"; + return summary(record); + } + + /** Atomically claims one matching approved record before any asynchronous upstream work begins. */ + consume(binding: ApprovalBinding): ApprovalSummary | undefined { + this.expire(); + const bindingDigest = this.digestBinding(binding); + const record = [...this.records.values()].find( + (candidate) => + candidate.sessionId === this.sessionId && + candidate.status === "approved" && + timingSafeEqual(candidate.bindingDigest, bindingDigest) + ); + if (record === undefined) return undefined; + record.status = "consumed"; + return summary(record); + } + + list(): readonly ApprovalSummary[] { + return [...this.records.values()] + .filter((record) => record.sessionId === this.sessionId && record.status === "pending") + .map(summary); + } + + /** Marks stale pending or approved approvals expired before they can authorize a future operation. */ + expire(): readonly ApprovalSummary[] { + const now = this.now().getTime(); + const expired: ApprovalSummary[] = []; + for (const record of this.records.values()) { + if ( + record.sessionId === this.sessionId && + (record.status === "pending" || record.status === "approved") && + record.expiresAtMs <= now + ) { + record.status = "expired"; + const transition = summary(record); + expired.push(transition); + this.expiredTransitions.push(transition); + } + } + return expired; + } + + /** Returns expiry transitions that have not yet been recorded by the owning server. */ + takeExpiredTransitions(): readonly ApprovalSummary[] { + const transitions = this.expiredTransitions; + this.expiredTransitions = []; + return transitions; + } + + /** Restores unrecorded expiry transitions after a fail-closed audit write failure. */ + restoreExpiredTransitions(transitions: readonly ApprovalSummary[]): void { + this.expiredTransitions.unshift(...transitions); + } + + private issueToken( + record: ApprovalRecord, + created: boolean, + isBearerSafe: (bearer: string) => boolean + ): ApprovalRequest { + if (record.tokenDigests.length >= MAX_BEARERS_PER_PENDING_APPROVAL) { + throw new MiftahError( + "APPROVAL_LIMIT_EXCEEDED", + "APPROVAL_LIMIT_EXCEEDED: too many approval bearers were issued for this pending operation" + ); + } + for (let attempt = 0; attempt < MAX_BEARER_ISSUE_ATTEMPTS; attempt += 1) { + const token = this.createToken(); + if (!isBearerSafe(token)) continue; + record.tokenDigests.push(this.digestToken(token)); + return { token, approval: summary(record), created }; + } + throw new MiftahError( + "POLICY_CONFIRMATION_REQUIRED", + "POLICY_CONFIRMATION_REQUIRED: unable to issue a safe one-time approval bearer" + ); + } + + private discardTerminalRecords(): void { + for (const [id, record] of this.records) { + if (record.status === "denied" || record.status === "consumed" || record.status === "expired") { + this.records.delete(id); + } + } + } + + private requirePending(token: string): ApprovalRecord { + this.expire(); + const record = this.findToken(token); + if (record?.status === "expired") { + throw new MiftahError("APPROVAL_EXPIRED", "APPROVAL_EXPIRED: approval token has expired"); + } + if (record === undefined || record.sessionId !== this.sessionId) { + throw new MiftahError("APPROVAL_INVALID", "APPROVAL_INVALID: approval token is invalid for this session"); + } + if (record.status !== "pending") { + throw new MiftahError("APPROVAL_NOT_PENDING", "APPROVAL_NOT_PENDING: approval token cannot be decided again"); + } + return record; + } + + private findToken(token: string): ApprovalRecord | undefined { + const digest = this.digestToken(token); + return [...this.records.values()].find((record) => + record.tokenDigests.some((tokenDigest) => timingSafeEqual(tokenDigest, digest)) + ); + } + + private digestToken(token: string): Buffer { + return createHmac("sha256", this.tokenKey).update(token).digest(); + } + + private digestBinding(binding: ApprovalBinding): Buffer { + return createHmac("sha256", this.bindingKey) + .update( + canonicalJson({ + sessionId: this.sessionId, + sourceProfile: binding.sourceProfile, + profile: binding.profile, + upstream: binding.upstream, + operation: binding.operation, + name: binding.name, + arguments: binding.arguments + }) + ) + .digest(); + } +} + +function summary(record: ApprovalRecord): ApprovalSummary { + return { + id: record.id, + status: record.status, + sourceProfile: record.sourceProfile, + profile: record.profile, + upstream: record.upstream, + operation: record.operation, + name: record.name, + expiresAt: new Date(record.expiresAtMs).toISOString() + }; +} + +function canonicalJson(value: unknown): string { + if (value === null) return "null"; + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; + if (typeof value === "object") { + const entries = Object.entries(value as Record) + .filter(([, entry]) => entry !== undefined) + .sort(([left], [right]) => left.localeCompare(right)); + return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; + } + const serialized = JSON.stringify(value); + return serialized === undefined ? "null" : serialized; +} diff --git a/src/audit/audit-trail.ts b/src/audit/audit-trail.ts index c0d1db76..e7c51c71 100644 --- a/src/audit/audit-trail.ts +++ b/src/audit/audit-trail.ts @@ -1,6 +1,12 @@ import { randomUUID } from "node:crypto"; import { AuditLogger } from "./audit-logger.js"; -import type { AuditEvent, AuditHealth, AuditRoutingSource, AuditStatus } from "./audit-types.js"; +import type { + ApprovalAuditAction, + AuditEvent, + AuditHealth, + AuditRoutingSource, + AuditStatus +} from "./audit-types.js"; import type { RoutingContextEvidence } from "../routing/routing-types.js"; export interface AuditOperationInput { @@ -41,6 +47,18 @@ export interface AuditLifecycleInput { errorCode?: string; } +export interface AuditApprovalInput { + approvalId: string; + approvalSessionId: string; + approvalAction: ApprovalAuditAction; + sourceProfile: string; + profile: string; + upstream: string; + operation: string; + name: string; + expiresAt?: string; +} + /** Creates one final audit record per MCP request when audit logging is configured. */ export class AuditTrail { readonly sessionId = randomUUID(); @@ -85,6 +103,27 @@ export class AuditTrail { }); } + /** Records a safe state transition for a one-time approval without serializing its bearer or arguments. */ + async writeApproval(input: AuditApprovalInput): Promise { + await this.write({ + wrapper: this.wrapperName, + kind: "approval", + eventId: randomUUID(), + sessionId: this.sessionId, + approvalId: input.approvalId, + approvalSessionId: input.approvalSessionId, + approvalAction: input.approvalAction, + sourceProfile: input.sourceProfile, + profile: input.profile, + upstream: input.upstream, + operation: input.operation, + name: input.name, + status: input.approvalAction === "denied" ? "denied" : "success", + durationMs: 0, + ...(input.expiresAt === undefined ? {} : { expiresAt: input.expiresAt }) + }); + } + /** Records a background lifecycle event without letting audit I/O disrupt process management. */ recordLifecycle(input: AuditLifecycleInput): void { void this.writeLifecycle(input).catch(() => undefined); diff --git a/src/audit/audit-types.ts b/src/audit/audit-types.ts index 66c6504a..4c54add3 100644 --- a/src/audit/audit-types.ts +++ b/src/audit/audit-types.ts @@ -20,9 +20,10 @@ export interface AuditHealth { lastFailure?: AuditWriteFailure; } -export type AuditEventKind = "operation" | "lifecycle"; +export type AuditEventKind = "operation" | "lifecycle" | "approval"; export type AuditStatus = "success" | "failure" | "blocked" | "denied" | "confirmation-required" | "ambiguous"; export type AuditRoutingSource = "rule" | "active-profile" | "default-profile"; +export type ApprovalAuditAction = "requested" | "approved" | "denied" | "expired" | "consumed"; export interface AuditEvent { wrapper: string; @@ -33,6 +34,10 @@ export interface AuditEvent { sessionId?: string; sourceProfile?: string; upstream?: string; + approvalId?: string; + approvalSessionId?: string; + approvalAction?: ApprovalAuditAction; + expiresAt?: string; lockToProfile?: string; operation: "tools/call" | "resources/read" | "prompts/get" | string; name: string; diff --git a/src/cli/exit-codes.ts b/src/cli/exit-codes.ts index ac1538eb..b8d53b95 100644 --- a/src/cli/exit-codes.ts +++ b/src/cli/exit-codes.ts @@ -54,6 +54,10 @@ export const ERROR_EXIT_CODES = { ROUTING_BLOCKED: CLI_EXIT_CODES.policy, POLICY_BLOCKED: CLI_EXIT_CODES.policy, POLICY_CONFIRMATION_REQUIRED: CLI_EXIT_CODES.policy, + APPROVAL_INVALID: CLI_EXIT_CODES.policy, + APPROVAL_EXPIRED: CLI_EXIT_CODES.policy, + APPROVAL_NOT_PENDING: CLI_EXIT_CODES.policy, + APPROVAL_LIMIT_EXCEEDED: CLI_EXIT_CODES.policy, IDENTITY_NOT_CONFIGURED: CLI_EXIT_CODES.policy, IDENTITY_MISMATCH: CLI_EXIT_CODES.policy, IDENTITY_PROBE_UNSUPPORTED: CLI_EXIT_CODES.policy, diff --git a/src/mcp/server/miftah-server.ts b/src/mcp/server/miftah-server.ts index f4b3ca46..ff340482 100644 --- a/src/mcp/server/miftah-server.ts +++ b/src/mcp/server/miftah-server.ts @@ -22,6 +22,7 @@ import { type Tool } from "@modelcontextprotocol/sdk/types.js"; import type { MiftahConfig, ToolingConfig } from "../../config/types.js"; +import { ApprovalStore, type ApprovalBinding, type ApprovalSummary } from "../../approvals/approval-store.js"; import { SecretRedactor, redactUri } from "../../secrets/redact.js"; import { ProfileManager } from "../../profiles/profile-manager.js"; import { RoutingEngine } from "../../routing/routing-engine.js"; @@ -47,6 +48,7 @@ import { MiftahError } from "../../utils/errors.js"; import { MIFTAH_VERSION } from "../../version.js"; import { OperationPipeline, + type ApprovalRequestContext, type CapturedProfileState, type ResolvedOperation } from "./operation-pipeline.js"; @@ -71,7 +73,10 @@ const managementTools: Tool[] = [ tool("miftah_list_upstream_tools", "List tools discovered from an upstream profile.", ["profile"]), tool("miftah_restart_profile", "Restart all upstream processes for a profile.", ["profile"]), tool("miftah_verify_identity", "Explicitly verify configured upstream identity.", [], ["profile", "upstream"]), - tool("miftah_route_preview", "Preview routing for a hypothetical tool call.", ["toolName"]) + tool("miftah_route_preview", "Preview routing for a hypothetical tool call.", ["toolName"]), + tool("miftah_list_approvals", "List safe metadata for approvals pending in this connection."), + tool("miftah_approve", "Approve a pending operation using its one-time approval token.", ["approval"]), + tool("miftah_deny", "Deny a pending operation using its one-time approval token.", ["approval"]) ]; const EMPTY_MCP_ROOTS: readonly RoutingContextMcpRoot[] = Object.freeze([]); @@ -163,6 +168,11 @@ interface ResourcePromptProxyUnavailable { type ResourcePromptProxyAvailability = ResourcePromptProxyAvailable | ResourcePromptProxyUnavailable; +type ApprovalResolution = + | { readonly kind: "consumed" } + | { readonly kind: "fallback"; readonly token: string } + | { readonly kind: "form"; readonly token: string }; + /** Hosts Miftah's MCP surface and coordinates profile routing, upstream discovery, and client notifications. */ export class MiftahServer { readonly server: Server; @@ -174,12 +184,15 @@ export class MiftahServer { private readonly resourcePromptProxy: ResourcePromptProxyAvailability; private readonly toolRegistry: ToolRegistry; private readonly operationPipeline: OperationPipeline; + private readonly approvals = new ApprovalStore(); private readonly identities: IdentityManager; private readonly resourcePromptRegistry?: ResourcePromptRegistry; private readonly invalidatedToolSnapshots = new Map(); private readonly restartingProfiles = new Map>(); private readonly pendingResourceListChanges = new Set(); private readonly pendingPromptListChanges = new Set(); + /** Serializes approval state changes through their audit records; native elicitation runs outside this queue. */ + private approvalTransitions: Promise = Promise.resolve(); private profileTransitions: Promise = Promise.resolve(); private mcpRoots: readonly RoutingContextMcpRoot[] = EMPTY_MCP_ROOTS; private mcpRootsReady: Promise = Promise.resolve(); @@ -265,7 +278,8 @@ export class MiftahServer { upstreams, redactor: this.redactor, routingContext: this.provideRoutingContext, - identities: this.identities + identities: this.identities, + approvals: { requireApproval: (binding, context) => this.requireApproval(binding, context) } }); this.server.oninitialized = () => this.handleClientInitialized(); this.server.setNotificationHandler(RootsListChangedNotificationSchema, () => { @@ -286,6 +300,9 @@ export class MiftahServer { async connect(transport: Transport): Promise { await this.profileTransitions; + await this.enqueueApprovalTransition(async () => { + this.approvals.beginSession(); + }); const previousProfile = this.profiles.current().activeProfile; await this.profiles.beginSession(); const activeProfile = this.profiles.current().activeProfile; @@ -397,22 +414,26 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(CallToolRequestSchema, async (request) => { + this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { const name = request.params.name; const args = request.params.arguments ?? {}; const source = this.profiles.current(); const isManagementTool = managementTools.some((tool) => tool.name === name); + const isApprovalManagementTool = name === "miftah_approve" || name === "miftah_deny"; return this.runAudited( { operation: isManagementTool ? managementOperation(name) : "tools/call", name: isManagementTool ? managementName(name, args) : name, sourceProfile: source.activeProfile, - arguments: args + ...(isApprovalManagementTool ? {} : { arguments: args }) }, (audit) => isManagementTool ? this.handleManagement(name, args, audit, source) - : this.handleUpstreamTool(name, args, audit, source), + : this.handleUpstreamTool(name, args, audit, source, { + requestId: extra.requestId, + signal: extra.signal + }), (error) => textResult(error.message, true), (result) => result.isError @@ -447,8 +468,9 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => { + this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { const source = this.profiles.current(); + const approvalContext: ApprovalRequestContext = { requestId: extra.requestId, signal: extra.signal }; return this.runAudited( { operation: "resources/read", @@ -459,12 +481,12 @@ export class MiftahServer { async (audit) => { if (this.resourcePromptRegistry) { try { - return await this.executeResourceRead(source, upstreamName, request.params, audit); + return await this.executeResourceRead(source, upstreamName, request.params, audit, approvalContext); } finally { await this.notifyResourceAvailabilityChange(source.activeProfile); } } - return this.executeResourceRead(source, upstreamName, request.params, audit); + return this.executeResourceRead(source, upstreamName, request.params, audit, approvalContext); } ); }); @@ -493,8 +515,9 @@ export class MiftahServer { ); }); - this.server.setRequestHandler(GetPromptRequestSchema, async (request) => { + this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { const source = this.profiles.current(); + const approvalContext: ApprovalRequestContext = { requestId: extra.requestId, signal: extra.signal }; return this.runAudited( { operation: "prompts/get", @@ -505,12 +528,12 @@ export class MiftahServer { async (audit) => { if (this.resourcePromptRegistry) { try { - return await this.executePromptGet(source, upstreamName, request.params, audit); + return await this.executePromptGet(source, upstreamName, request.params, audit, approvalContext); } finally { await this.notifyPromptAvailabilityChange(source.activeProfile); } } - return this.executePromptGet(source, upstreamName, request.params, audit); + return this.executePromptGet(source, upstreamName, request.params, audit, approvalContext); } ); }); @@ -521,7 +544,8 @@ export class MiftahServer { name: string, args: Record, audit: AuditScope, - sourceState: CapturedProfileState + sourceState: CapturedProfileState, + approvalContext?: ApprovalRequestContext ): Promise { const sourceProfile = sourceState.activeProfile; const previous = this.toolRegistry.peek(sourceProfile) ?? this.invalidatedToolSnapshots.get(sourceProfile); @@ -546,6 +570,7 @@ export class MiftahServer { policyName: mapped.originalName, name: mapped.originalName, args, + ...(approvalContext === undefined ? {} : { approvalContext }), riskMetadataForProfile: (profile) => { const target = this.toolRegistry.peek(profile)?.resolve(name); return hasCompatibleCachedToolTarget(mapped, target) ? this.riskMetadata(target) : undefined; @@ -660,6 +685,44 @@ export class MiftahServer { ); } if (name === "miftah_validate_config") return textResult(JSON.stringify({ ok: true, errors: [] })); + if (name === "miftah_list_approvals") { + return this.enqueueApprovalTransition(async () => { + await this.expireApprovals(); + return textResult(JSON.stringify(this.approvals.list())); + }); + } + if (name === "miftah_approve") { + return this.enqueueApprovalTransition(async () => { + await this.expireApprovals(); + const approval = await this.withApprovalExpiryAudit( + () => this.approvals.approve(requiredString(args, "approval")), + (value) => this.approvals.revoke(value.id) + ); + try { + await this.writeApproval("approved", approval); + } catch (error) { + this.approvals.revoke(approval.id); + throw error; + } + return textResult("Approval granted. Retry the exact operation."); + }); + } + if (name === "miftah_deny") { + return this.enqueueApprovalTransition(async () => { + await this.expireApprovals(); + const approval = await this.withApprovalExpiryAudit( + () => this.approvals.deny(requiredString(args, "approval")), + (value) => this.approvals.revoke(value.id) + ); + try { + await this.writeApproval("denied", approval); + } catch (error) { + this.approvals.revoke(approval.id); + throw error; + } + return textResult("Approval denied."); + }); + } if (name === "miftah_list_upstream_tools") { const profile = args.profile === undefined ? this.profiles.current().activeProfile : requiredString(args, "profile"); audit.update({ name: profile, profile }); @@ -755,6 +818,178 @@ export class MiftahServer { }; } + private async requireApproval(binding: ApprovalBinding, context?: ApprovalRequestContext): Promise { + const supportsFormElicitation = + context !== undefined && this.server.getClientCapabilities()?.elicitation?.form !== undefined; + const resolution = await this.enqueueApprovalTransition(async (): Promise => { + await this.expireApprovals(); + const consumed = await this.withApprovalExpiryAudit( + () => this.approvals.consume(binding), + (value) => { + if (value !== undefined) this.approvals.revoke(value.id); + } + ); + if (consumed !== undefined) { + try { + await this.writeApproval("consumed", consumed); + } catch (error) { + this.approvals.revoke(consumed.id); + throw error; + } + return { kind: "consumed" }; + } + const requested = await this.withApprovalExpiryAudit( + () => + this.approvals.request( + binding, + supportsFormElicitation ? undefined : (bearer) => this.redactor.redactText(bearer) === bearer + ), + (value) => this.approvals.revoke(value.approval.id) + ); + if (requested.created) { + try { + await this.writeApproval("requested", requested.approval); + } catch (error) { + this.approvals.revoke(requested.approval.id); + throw error; + } + } + return supportsFormElicitation ? { kind: "form", token: requested.token } : { kind: "fallback", token: requested.token }; + }); + if (resolution.kind === "consumed") return; + if (resolution.kind === "fallback") { + throw new MiftahError( + "POLICY_CONFIRMATION_REQUIRED", + `POLICY_CONFIRMATION_REQUIRED: approval required for '${binding.displayName}'. Use miftah_approve with approval '${resolution.token}' then retry the exact operation.` + ); + } + if (context === undefined) throw new Error("Form approval requires an MCP request context."); + let result; + try { + result = await this.server.elicitInput( + { + mode: "form", + message: "Approve this exact operation?", + requestedSchema: { + type: "object", + properties: { approved: { type: "boolean" } }, + required: ["approved"] + } + }, + { relatedRequestId: context.requestId, signal: context.signal, timeout: 60_000 } + ); + } catch { + await this.finalizeNativeApproval(resolution.token, binding, false); + throw this.approvalNotAccepted(binding); + } + if (result.action === "accept" && result.content?.approved === true) { + await this.finalizeNativeApproval(resolution.token, binding, true); + return; + } + await this.finalizeNativeApproval(resolution.token, binding, false); + throw this.approvalNotAccepted(binding); + } + + private async finalizeNativeApproval(token: string, binding: ApprovalBinding, accepted: boolean): Promise { + await this.enqueueApprovalTransition(async () => { + await this.expireApprovals(); + if (accepted) { + const approval = await this.withApprovalExpiryAudit( + () => this.approvals.approveAndConsume(token, binding), + (value) => this.approvals.revoke(value.id) + ); + try { + await this.writeApproval("approved", approval); + await this.writeApproval("consumed", approval); + } catch (error) { + this.approvals.revoke(approval.id); + throw error; + } + return; + } + const approval = await this.withApprovalExpiryAudit( + () => this.approvals.deny(token), + (value) => this.approvals.revoke(value.id) + ); + try { + await this.writeApproval("denied", approval); + } catch (error) { + this.approvals.revoke(approval.id); + throw error; + } + }); + } + + private approvalNotAccepted(binding: ApprovalBinding): MiftahError { + return new MiftahError( + "POLICY_CONFIRMATION_REQUIRED", + `POLICY_CONFIRMATION_REQUIRED: approval was not accepted for '${binding.displayName}'` + ); + } + + private async expireApprovals(): Promise { + this.approvals.expire(); + await this.writeExpiredApprovalTransitions(); + } + + private async withApprovalExpiryAudit( + operation: () => Result, + rollbackOnAuditFailure?: (result: Result) => void + ): Promise { + let result: Result; + try { + result = operation(); + } catch (error) { + await this.writeExpiredApprovalTransitions(); + throw error; + } + try { + await this.writeExpiredApprovalTransitions(); + } catch (error) { + rollbackOnAuditFailure?.(result); + throw error; + } + return result; + } + + private enqueueApprovalTransition(operation: () => Promise): Promise { + const result = this.approvalTransitions.then(operation, operation); + this.approvalTransitions = result.then( + () => undefined, + () => undefined + ); + return result; + } + + private async writeExpiredApprovalTransitions(): Promise { + const expired = this.approvals.takeExpiredTransitions(); + for (let index = 0; index < expired.length; index += 1) { + try { + await this.writeApproval("expired", expired[index]!); + } catch (error) { + this.approvals.restoreExpiredTransitions(expired.slice(index)); + throw error; + } + } + } + + private async writeApproval( + action: "requested" | "approved" | "denied" | "expired" | "consumed", + approval: ApprovalSummary + ): Promise { + await this.auditTrail.writeApproval({ + approvalId: approval.id, + approvalSessionId: this.approvals.activeSessionId, + approvalAction: action, + sourceProfile: approval.sourceProfile, + profile: approval.profile, + upstream: approval.upstream, + operation: approval.operation, + name: approval.name, + expiresAt: approval.expiresAt + }); + } + private trustsToolAnnotations(upstreamName: string | undefined): boolean { if (this.config.upstream !== undefined) return this.config.upstream.trustToolAnnotations === true; return ( @@ -925,7 +1160,8 @@ export class MiftahServer { source: CapturedProfileState, upstreamName: string | undefined, params: ReadResourceRequest["params"], - audit: AuditScope + audit: AuditScope, + approvalContext?: ApprovalRequestContext ): Promise { return this.operationPipeline.execute( { @@ -935,6 +1171,7 @@ export class MiftahServer { policyName: "resources/read", name: params.uri, args: { uri: params.uri }, + ...(approvalContext === undefined ? {} : { approvalContext }), resolveTarget: async (profile) => { if (this.resourcePromptRegistry) return this.resolveAggregatedResource(profile, params); const auditUpstream = this.auditUpstreamName(upstreamName); @@ -955,7 +1192,8 @@ export class MiftahServer { source: CapturedProfileState, upstreamName: string | undefined, params: GetPromptRequest["params"], - audit: AuditScope + audit: AuditScope, + approvalContext?: ApprovalRequestContext ): Promise { return this.operationPipeline.execute( { @@ -965,6 +1203,7 @@ export class MiftahServer { policyName: "prompts/get", name: params.name, args: { ...(params.arguments ?? {}), name: params.name }, + ...(approvalContext === undefined ? {} : { approvalContext }), resolveTarget: async (profile) => { if (this.resourcePromptRegistry) return this.resolveAggregatedPrompt(profile, params); const auditUpstream = this.auditUpstreamName(upstreamName); diff --git a/src/mcp/server/operation-pipeline.ts b/src/mcp/server/operation-pipeline.ts index abe5ecde..004f0107 100644 --- a/src/mcp/server/operation-pipeline.ts +++ b/src/mcp/server/operation-pipeline.ts @@ -1,4 +1,5 @@ import type { AuditScope } from "../../audit/audit-trail.js"; +import type { ApprovalBinding } from "../../approvals/approval-store.js"; import { IdentityManager } from "../../identity/identity-manager.js"; import { PolicyEngine } from "../../policy/policy-engine.js"; import type { PolicyDecision } from "../../policy/policy-types.js"; @@ -19,6 +20,11 @@ export interface CapturedProfileState { readonly revision: number; } +export interface ApprovalRequestContext { + readonly requestId: string | number; + readonly signal: AbortSignal; +} + export interface ResolvedOperation { readonly upstreamName?: string; readonly identityUpstreamName?: string; @@ -37,6 +43,7 @@ export interface ProxiedOperation { readonly riskMetadata?: ToolRiskMetadata; /** Reads only already-cached target risk evidence; it must not discover or start an upstream. */ riskMetadataForProfile?(profile: string): ToolRiskMetadata | undefined; + readonly approvalContext?: ApprovalRequestContext; readonly requireExplicitRuleForDestructive?: boolean; resolveTarget(profile: string): Promise>; } @@ -51,6 +58,9 @@ interface PipelineOptions { readonly redactor: SecretRedactor; readonly routingContext: RoutingContextProvider; readonly identities: IdentityManager; + readonly approvals: { + requireApproval(binding: ApprovalBinding, context?: ApprovalRequestContext): Promise; + }; } /** @@ -96,6 +106,18 @@ export class OperationPipeline { name: this.auditName(operation, target.name), ...(target.upstreamName === undefined ? {} : { upstream: target.upstreamName }) }); + if (decision.action === "confirm") { + const binding: ApprovalBinding = { + sourceProfile: operation.source.activeProfile, + profile, + upstream: target.upstreamName ?? "default", + operation: operation.operation, + name: target.name, + displayName: this.auditName(operation, target.name), + arguments: operation.args + }; + await this.options.approvals.requireApproval(binding, operation.approvalContext); + } const session = await this.options.upstreams.get(profile, target.upstreamName); if (this.options.identities.requiresVerification(profile, target.identityUpstreamName, decision.risk)) { const identity = await this.options.identities.verify(profile, target.identityUpstreamName, session); @@ -130,12 +152,6 @@ export class OperationPipeline { `POLICY_BLOCKED: operation '${operation.policyName}' is blocked for profile '${profile}'` ); } - if (decision.action === "confirm") { - throw new MiftahError( - "POLICY_CONFIRMATION_REQUIRED", - `POLICY_CONFIRMATION_REQUIRED: operation '${operation.policyName}' requires confirmation for profile '${profile}'` - ); - } } private auditName(operation: ProxiedOperation, name: string): string { diff --git a/src/utils/errors.ts b/src/utils/errors.ts index 13c8a58e..db80bec8 100644 --- a/src/utils/errors.ts +++ b/src/utils/errors.ts @@ -41,6 +41,10 @@ export type MiftahErrorCode = | "ROUTING_BLOCKED" | "POLICY_BLOCKED" | "POLICY_CONFIRMATION_REQUIRED" + | "APPROVAL_INVALID" + | "APPROVAL_EXPIRED" + | "APPROVAL_NOT_PENDING" + | "APPROVAL_LIMIT_EXCEEDED" | "TOOL_COLLISION" | "TOOL_NOT_FOUND" | "TOOL_SCHEMA_MISMATCH" diff --git a/tests/approval-docs-contract.test.ts b/tests/approval-docs-contract.test.ts new file mode 100644 index 00000000..2de54b67 --- /dev/null +++ b/tests/approval-docs-contract.test.ts @@ -0,0 +1,23 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; + +function readRepositoryFile(path: string): string { + return readFileSync(new URL(`../${path}`, import.meta.url), "utf8"); +} + +describe("approval documentation contract", () => { + it("documents capability-bound fallback, native elicitation, and safe audit boundaries", () => { + const config = readRepositoryFile("docs/config.md"); + const security = readRepositoryFile("docs/security.md"); + const architecture = readRepositoryFile("docs/architecture.md"); + + expect(config).toContain("MCP approvals"); + expect(config).toContain("miftah_list_approvals"); + expect(config).toContain("miftah_approve"); + expect(config).toContain("miftah_deny"); + expect(config).toContain("form elicitation"); + expect(security).toContain("approval bearer"); + expect(architecture).toContain("approval lifecycle"); + expect(architecture).toContain("raw approval bearer or operation arguments"); + }); +}); diff --git a/tests/approval-fallback.test.ts b/tests/approval-fallback.test.ts new file mode 100644 index 00000000..4cda2209 --- /dev/null +++ b/tests/approval-fallback.test.ts @@ -0,0 +1,897 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { ElicitRequestSchema } from "@modelcontextprotocol/sdk/types.js"; +import { access, mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { validateConfig } from "../src/config/validate-config.js"; +import { ApprovalStore } from "../src/approvals/approval-store.js"; +import { MiftahError } from "../src/utils/errors.js"; +import { MiftahServer } from "../src/mcp/server/miftah-server.js"; +import { ProfileManager } from "../src/profiles/profile-manager.js"; +import { UpstreamProcessManager } from "../src/upstream/upstream-process-manager.js"; + +const fixture = join(dirname(fileURLToPath(import.meta.url)), "fixtures", "fake-upstream.mjs"); + +describe("approval fallback", () => { + it("invalidates pending approvals when an MCP connection begins", async () => { + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: {} } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const approvals = (wrapper as unknown as { approvals: ApprovalStore }).approvals; + const requested = approvals.request({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-session-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + expect(() => approvals.approve(requested.token)).toThrow(expect.objectContaining({ code: "APPROVAL_INVALID" })); + } finally { + await client.close(); + await wrapper.close(); + } + }); + + it("advertises management tools for listing and deciding pending approvals", async () => { + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: {} } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-fallback-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + const tools = await client.listTools(); + + expect(tools.tools.map((tool) => tool.name)).toEqual( + expect.arrayContaining(["miftah_list_approvals", "miftah_approve", "miftah_deny"]) + ); + } finally { + await client.close(); + await wrapper.close(); + } + }); + + it("returns a one-time fallback approval without forwarding a confirmation-required call", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-fallback-")); + const createCountPath = join(directory, "create-count"); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { + work: { + policy: "confirm", + env: { TEST_CREATE_ITEM_COUNT_PATH: createCountPath } + } + }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-fallback-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + const result = await client.callTool({ name: "create_item", arguments: { name: "first" } }); + + expect(result).toMatchObject({ + isError: true, + content: [ + { + type: "text", + text: expect.stringMatching( + /POLICY_CONFIRMATION_REQUIRED: approval required for 'create_item'\. Use miftah_approve with approval '[A-Za-z0-9_-]+' then retry the exact operation\./u + ) + } + ] + }); + await expect(access(createCountPath)).rejects.toThrow(); + } finally { + await client.close(); + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("issues a fallback bearer that remains usable after secret redaction", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-redaction-")); + const createCountPath = join(directory, "create-count"); + let tokenAttempt = 0; + const approvals = new ApprovalStore({ + createToken: () => (tokenAttempt++ === 0 ? "unsafe-bearer" : "safe-bearer") + }); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { + work: { + policy: "confirm", + env: { API_TOKEN: "unsafe", TEST_CREATE_ITEM_COUNT_PATH: createCountPath } + } + }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + (wrapper as unknown as { approvals: ApprovalStore }).approvals = approvals; + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-redaction-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + const requested = textContent(await client.callTool({ name: "create_item", arguments: { name: "first" } })); + expect(requested).toContain("approval 'safe-bearer'"); + expect(await client.callTool({ name: "miftah_approve", arguments: { approval: "safe-bearer" } })).toMatchObject({ + content: [{ type: "text", text: expect.stringContaining("Approval granted") }] + }); + expect(await client.callTool({ name: "create_item", arguments: { name: "first" } })).toMatchObject({ + content: [{ type: "text", text: "created:first" }] + }); + expect(await readFile(createCountPath, "utf8")).toBe("1\n"); + } finally { + await client.close(); + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("removes a newly-created approval when its required audit transition fails", async () => { + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const host = wrapper as unknown as { approvals: ApprovalStore; writeApproval(): Promise }; + host.writeApproval = async () => { + throw new MiftahError("AUDIT_WRITE_FAILED", "AUDIT_WRITE_FAILED: test sink rejected approval event"); + }; + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-audit-failure-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + expect(await client.callTool({ name: "create_item", arguments: { name: "first" } })).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("AUDIT_WRITE_FAILED") }] + }); + expect(host.approvals.list()).toEqual([]); + } finally { + await client.close(); + await wrapper.close(); + } + }); + + it("lists pending approvals safely and makes an explicit denial non-replayable", async () => { + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-deny-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + const requested = await client.callTool({ name: "create_item", arguments: { name: "first" } }); + const token = textContent(requested).match(/approval '([A-Za-z0-9_-]+)'/u)?.[1]; + if (!token) throw new Error("Expected a fallback approval token."); + + const listed = textContent(await client.callTool({ name: "miftah_list_approvals", arguments: {} })); + expect(listed).toContain('"status":"pending"'); + expect(listed).not.toContain(token); + expect(await client.callTool({ name: "miftah_deny", arguments: { approval: token } })).toMatchObject({ + content: [{ type: "text", text: "Approval denied." }] + }); + expect(JSON.parse(textContent(await client.callTool({ name: "miftah_list_approvals", arguments: {} })))).toEqual([]); + + const retried = await client.callTool({ name: "create_item", arguments: { name: "first" } }); + const replacement = textContent(retried).match(/approval '([A-Za-z0-9_-]+)'/u)?.[1]; + expect(replacement).toBeDefined(); + expect(replacement).not.toBe(token); + } finally { + await client.close(); + await wrapper.close(); + } + }); + + it("revokes an approval when recording its approval transition fails", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-approve-audit-failure-")); + const createCountPath = join(directory, "create-count"); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm", env: { TEST_CREATE_ITEM_COUNT_PATH: createCountPath } } }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const host = wrapper as unknown as { + approvals: ApprovalStore; + writeApproval(action: string, approval: unknown): Promise; + }; + const originalWriteApproval = host.writeApproval.bind(wrapper); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-approve-audit-failure-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + const requested = await client.callTool({ name: "create_item", arguments: { name: "first" } }); + const token = textContent(requested).match(/approval '([A-Za-z0-9_-]+)'/u)?.[1]; + if (!token) throw new Error("Expected a fallback approval token."); + host.writeApproval = async () => { + throw new MiftahError("AUDIT_WRITE_FAILED", "AUDIT_WRITE_FAILED: test sink rejected approval event"); + }; + + expect(await client.callTool({ name: "miftah_approve", arguments: { approval: token } })).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("AUDIT_WRITE_FAILED") }] + }); + host.writeApproval = originalWriteApproval; + + expect(await client.callTool({ name: "create_item", arguments: { name: "first" } })).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("POLICY_CONFIRMATION_REQUIRED") }] + }); + await expect(access(createCountPath)).rejects.toThrow(); + } finally { + await client.close(); + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("does not consume an approval while its approval audit transition is unresolved", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-audit-race-")); + const auditPath = join(directory, "audit.jsonl"); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } }, + audit: { path: auditPath } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const host = wrapper as unknown as { + approvals: ApprovalStore; + writeApproval(action: string, approval: unknown): Promise; + handleManagement( + name: string, + args: Record, + audit: unknown, + source: unknown + ): Promise; + requireApproval(binding: { + sourceProfile: string; + profile: string; + upstream: string; + operation: string; + name: string; + displayName: string; + arguments: Record; + }): Promise; + }; + const originalWriteApproval = host.writeApproval.bind(wrapper); + let beginApprovedAudit: () => void = () => undefined; + const approvedAuditStarted = new Promise((resolve) => { + beginApprovedAudit = resolve; + }); + let rejectApprovedAudit: (reason: unknown) => void = () => undefined; + const approvedAudit = new Promise((_, reject) => { + rejectApprovedAudit = reject; + }); + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }; + const requested = host.approvals.request(binding); + + try { + host.writeApproval = async (action, approval) => { + if (action === "approved") { + beginApprovedAudit(); + await approvedAudit; + } + await originalWriteApproval(action, approval); + }; + + const approving = host.handleManagement( + "miftah_approve", + { approval: requested.token }, + {}, + { activeProfile: "work", revision: 0 } + ); + await approvedAuditStarted; + const retried = host.requireApproval(binding); + rejectApprovedAudit(new MiftahError("AUDIT_WRITE_FAILED", "AUDIT_WRITE_FAILED: test sink rejected approval event")); + + await expect(approving).rejects.toThrow("AUDIT_WRITE_FAILED"); + await expect(retried).rejects.toThrow("POLICY_CONFIRMATION_REQUIRED"); + } finally { + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("does not disclose a duplicate fallback while its requested audit transition is unresolved", async () => { + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const host = wrapper as unknown as { + writeApproval(action: string, approval: unknown): Promise; + requireApproval(binding: { + sourceProfile: string; + profile: string; + upstream: string; + operation: string; + name: string; + displayName: string; + arguments: Record; + }): Promise; + }; + let beginRequestedAudit: () => void = () => undefined; + const requestedAuditStarted = new Promise((resolve) => { + beginRequestedAudit = resolve; + }); + let rejectRequestedAudit: (reason: unknown) => void = () => undefined; + const requestedAudit = new Promise((_, reject) => { + rejectRequestedAudit = reject; + }); + let requestedWrites = 0; + host.writeApproval = async (action) => { + if (action === "requested" && ++requestedWrites === 1) { + beginRequestedAudit(); + await requestedAudit; + } + }; + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }; + + try { + const first = host.requireApproval(binding); + await requestedAuditStarted; + const duplicate = host.requireApproval(binding); + let duplicateSettled = false; + void duplicate.then( + () => { + duplicateSettled = true; + }, + () => { + duplicateSettled = true; + } + ); + await new Promise((resolve) => setImmediate(resolve)); + expect(duplicateSettled).toBe(false); + rejectRequestedAudit(new MiftahError("AUDIT_WRITE_FAILED", "AUDIT_WRITE_FAILED: test sink rejected request event")); + + await expect(first).rejects.toThrow("AUDIT_WRITE_FAILED"); + await expect(duplicate).rejects.toThrow("POLICY_CONFIRMATION_REQUIRED"); + } finally { + await wrapper.close(); + } + }); + + it("consumes an approved fallback exactly once without auditing its bearer", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-consume-")); + const createCountPath = join(directory, "create-count"); + const auditPath = join(directory, "audit.jsonl"); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { + work: { + policy: "confirm", + env: { TEST_CREATE_ITEM_COUNT_PATH: createCountPath } + } + }, + policies: { confirm: { requireConfirmation: ["create_item"] } }, + audit: { path: auditPath, includeArguments: true } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-consume-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + const requested = await client.callTool({ name: "create_item", arguments: { name: "first" } }); + const requestText = textContent(requested); + const token = requestText.match(/approval '([A-Za-z0-9_-]+)'/u)?.[1]; + if (!token) throw new Error(`Expected fallback approval token, received: ${requestText}`); + + expect(await client.callTool({ name: "miftah_approve", arguments: { approval: token } })).toMatchObject({ + content: [{ type: "text", text: expect.stringContaining("Approval granted") }] + }); + expect(await client.callTool({ name: "create_item", arguments: { name: "first" } })).toMatchObject({ + content: [{ type: "text", text: "created:first" }] + }); + expect(await client.callTool({ name: "create_item", arguments: { name: "first" } })).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("POLICY_CONFIRMATION_REQUIRED") }] + }); + expect(await readFile(createCountPath, "utf8")).toBe("1\n"); + expect(await readFile(auditPath, "utf8")).not.toContain(token); + const approvalEvents = (await readFile(auditPath, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record) + .filter((event) => event.kind === "approval"); + expect(approvalEvents.map((event) => event.approvalAction)).toEqual([ + "requested", + "approved", + "consumed", + "requested" + ]); + expect(JSON.stringify(approvalEvents)).not.toContain(token); + expect(JSON.stringify(approvalEvents)).not.toContain('"name":"first"'); + } finally { + await client.close(); + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("audits an expired approved fallback before offering a fresh one", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-expiry-")); + const auditPath = join(directory, "audit.jsonl"); + let now = new Date("2026-07-12T00:00:00.000Z"); + const approvals = new ApprovalStore({ now: () => now, ttlMs: 1_000 }); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } }, + audit: { path: auditPath } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + (wrapper as unknown as { approvals: ApprovalStore }).approvals = approvals; + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "approval-expiry-client", version: "1.0.0" }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + const requested = await client.callTool({ name: "create_item", arguments: { name: "first" } }); + const token = textContent(requested).match(/approval '([A-Za-z0-9_-]+)'/u)?.[1]; + if (!token) throw new Error("Expected a fallback approval token."); + await client.callTool({ name: "miftah_approve", arguments: { approval: token } }); + + now = new Date("2026-07-12T00:00:01.000Z"); + + expect(await client.callTool({ name: "create_item", arguments: { name: "first" } })).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("POLICY_CONFIRMATION_REQUIRED") }] + }); + const approvalActions = (await readFile(auditPath, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record) + .filter((event) => event.kind === "approval") + .map((event) => event.approvalAction); + expect(approvalActions).toEqual(["requested", "approved", "expired", "requested"]); + } finally { + await client.close(); + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("audits expiry when an internal approval consume sweep crosses the TTL boundary", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-consume-expiry-race-")); + const auditPath = join(directory, "audit.jsonl"); + let raceRead = false; + let raceReadCount = 0; + const approvals = new ApprovalStore({ + now: () => { + if (!raceRead) return new Date("2026-07-12T00:00:00.000Z"); + raceReadCount += 1; + return new Date(raceReadCount === 1 ? "2026-07-12T00:00:00.999Z" : "2026-07-12T00:00:01.000Z"); + }, + ttlMs: 1_000 + }); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } }, + audit: { path: auditPath } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const host = wrapper as unknown as { + approvals: ApprovalStore; + requireApproval(binding: { + sourceProfile: string; + profile: string; + upstream: string; + operation: string; + name: string; + displayName: string; + arguments: Record; + }): Promise; + }; + host.approvals = approvals; + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }; + const requested = approvals.request(binding); + approvals.approve(requested.token); + raceRead = true; + + try { + await expect(host.requireApproval(binding)).rejects.toThrow("POLICY_CONFIRMATION_REQUIRED"); + + const approvalActions = (await readFile(auditPath, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record) + .filter((event) => event.kind === "approval") + .map((event) => event.approvalAction); + expect(approvalActions).toEqual(["expired", "requested"]); + } finally { + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("revokes a new approval when an inner expiry audit write fails", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-request-expiry-audit-failure-")); + let current = 0; + let raceTimes: number[] = []; + const approvals = new ApprovalStore({ + now: () => new Date(raceTimes.shift() ?? current), + ttlMs: 1_000 + }); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const host = wrapper as unknown as { + approvals: ApprovalStore; + writeApproval(action: string, approval: unknown): Promise; + requireApproval(binding: { + sourceProfile: string; + profile: string; + upstream: string; + operation: string; + name: string; + displayName: string; + arguments: Record; + }): Promise; + }; + host.approvals = approvals; + approvals.request({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "expired_item", + displayName: "expired_item", + arguments: {} + }); + current = 500; + raceTimes = [900, 999, 1_000]; + host.writeApproval = async (action) => { + if (action === "expired") { + throw new MiftahError("AUDIT_WRITE_FAILED", "AUDIT_WRITE_FAILED: test sink rejected expiry event"); + } + }; + + try { + await expect( + host.requireApproval({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }) + ).rejects.toThrow("AUDIT_WRITE_FAILED"); + expect(approvals.list()).toEqual([]); + } finally { + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("uses a boolean form elicitation when the client supports it", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-elicit-")); + const createCountPath = join(directory, "create-count"); + const secretArgument = "approval-form-secret"; + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { + work: { + policy: "confirm", + env: { TEST_CREATE_ITEM_COUNT_PATH: createCountPath } + } + }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client( + { name: "approval-elicit-client", version: "1.0.0" }, + { capabilities: { elicitation: { form: {} } } } + ); + let elicitationRequest: unknown; + client.setRequestHandler(ElicitRequestSchema, async (request) => { + elicitationRequest = request; + return { action: "accept", content: { approved: true } }; + }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + expect(wrapper.server.getClientCapabilities()).toMatchObject({ elicitation: { form: {} } }); + + const callResult = await client.callTool({ name: "create_item", arguments: { name: secretArgument } }); + expect(elicitationRequest).toBeDefined(); + expect(callResult).toMatchObject({ + content: [{ type: "text", text: `created:${secretArgument}` }] + }); + expect(JSON.stringify(elicitationRequest)).not.toContain(secretArgument); + expect(elicitationRequest).toMatchObject({ + params: { + mode: "form", + requestedSchema: { + properties: { approved: { type: "boolean" } }, + required: ["approved"] + } + } + }); + expect(await readFile(createCountPath, "utf8")).toBe("1\n"); + } finally { + await client.close(); + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("audits a native approval that expires while its form is open", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-elicit-expiry-")); + const auditPath = join(directory, "audit.jsonl"); + let now = new Date("2026-07-12T00:00:00.000Z"); + const approvals = new ApprovalStore({ now: () => now, ttlMs: 1_000 }); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } }, + audit: { path: auditPath } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + (wrapper as unknown as { approvals: ApprovalStore }).approvals = approvals; + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client( + { name: "approval-elicit-expiry-client", version: "1.0.0" }, + { capabilities: { elicitation: { form: {} } } } + ); + client.setRequestHandler(ElicitRequestSchema, async () => { + now = new Date("2026-07-12T00:00:01.000Z"); + return { action: "accept", content: { approved: true } }; + }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + expect(await client.callTool({ name: "create_item", arguments: { name: "first" } })).toMatchObject({ + isError: true, + content: [{ type: "text", text: expect.stringContaining("APPROVAL_EXPIRED") }] + }); + const approvalActions = (await readFile(auditPath, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record) + .filter((event) => event.kind === "approval") + .map((event) => event.approvalAction); + expect(approvalActions).toEqual(["requested", "expired"]); + } finally { + await client.close(); + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); + + it("uses the same generic form for confirmation-required resource and prompt operations", async () => { + const secretResourceUri = "account://current?token=resource-approval-secret"; + const secretPromptArgument = "prompt-approval-secret"; + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["resources/read", "prompts/get"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client( + { name: "approval-resource-prompt-elicit-client", version: "1.0.0" }, + { capabilities: { elicitation: { form: {} } } } + ); + const elicitationRequests: unknown[] = []; + client.setRequestHandler(ElicitRequestSchema, async (request) => { + elicitationRequests.push(request); + return { action: "accept", content: { approved: true } }; + }); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + expect(await client.readResource({ uri: secretResourceUri })).toMatchObject({ contents: [{ text: "unknown" }] }); + expect(await client.getPrompt({ name: "account_prompt", arguments: { value: secretPromptArgument } })).toMatchObject({ + messages: [{ content: { text: "unknown" } }] + }); + expect(elicitationRequests).toHaveLength(2); + expect(JSON.stringify(elicitationRequests)).not.toContain(secretResourceUri); + expect(JSON.stringify(elicitationRequests)).not.toContain(secretPromptArgument); + } finally { + await client.close(); + await wrapper.close(); + } + }); + + it("does not fall back to a bearer when a supported client declines the form", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-approval-decline-")); + const createCountPath = join(directory, "create-count"); + const auditPath = join(directory, "audit.jsonl"); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { + work: { + policy: "confirm", + env: { TEST_CREATE_ITEM_COUNT_PATH: createCountPath } + } + }, + policies: { confirm: { requireConfirmation: ["create_item"] } }, + audit: { path: auditPath } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client( + { name: "approval-decline-client", version: "1.0.0" }, + { capabilities: { elicitation: { form: {} } } } + ); + client.setRequestHandler(ElicitRequestSchema, async () => ({ action: "accept", content: { approved: false } })); + + try { + await Promise.all([wrapper.connect(serverTransport), client.connect(clientTransport)]); + + expect(await client.callTool({ name: "create_item", arguments: { name: "first" } })).toMatchObject({ + isError: true, + content: [ + { + type: "text", + text: "POLICY_CONFIRMATION_REQUIRED: approval was not accepted for 'create_item'" + } + ] + }); + await expect(access(createCountPath)).rejects.toThrow(); + const approvalActions = (await readFile(auditPath, "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record) + .filter((event) => event.kind === "approval") + .map((event) => event.approvalAction); + expect(approvalActions).toEqual(["requested", "denied"]); + } finally { + await client.close(); + await wrapper.close(); + await rm(directory, { recursive: true, force: true }); + } + }); +}); + +function textContent(result: unknown): string { + if (!isTextContentResult(result)) throw new Error("Expected a text result."); + const content = result.content.find((item) => item.type === "text")?.text; + if (content === undefined) throw new Error("Expected a text result."); + return content; +} + +function isTextContentResult(value: unknown): value is { content: readonly { type: string; text?: string }[] } { + return ( + typeof value === "object" && + value !== null && + "content" in value && + Array.isArray((value as { content?: unknown }).content) + ); +} diff --git a/tests/approval-store.test.ts b/tests/approval-store.test.ts new file mode 100644 index 00000000..6533bfd9 --- /dev/null +++ b/tests/approval-store.test.ts @@ -0,0 +1,246 @@ +import { describe, expect, it } from "vitest"; +import { ApprovalStore } from "../src/approvals/approval-store.js"; + +describe("approval store", () => { + it("does not consume an approved approval for a different normalized argument set", () => { + const store = new ApprovalStore({ + now: () => new Date("2026-07-12T00:00:00.000Z"), + createToken: () => "approval-test-token" + }); + store.beginSession(); + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call" as const, + name: "create_item", + displayName: "create_item", + arguments: { first: "one", second: "two" } + }; + + const requested = store.request(binding); + store.approve(requested.token); + + expect(store.consume({ ...binding, arguments: { first: "one", second: "changed" } })).toBeUndefined(); + expect(store.consume({ ...binding, arguments: { second: "two", first: "one" } })).toMatchObject({ + id: requested.approval.id, + status: "consumed" + }); + expect(JSON.stringify(store.list())).not.toContain("approval-test-token"); + }); + + it("keeps the first fallback bearer valid when the same pending operation is requested again", () => { + let token = 0; + const store = new ApprovalStore({ createToken: () => `approval-repeat-${++token}` }); + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call" as const, + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }; + + const first = store.request(binding); + const second = store.request(binding); + + expect(second).toMatchObject({ created: false }); + expect(store.approve(first.token)).toMatchObject({ id: first.approval.id, status: "approved" }); + expect(store.consume(binding)).toMatchObject({ id: first.approval.id, status: "consumed" }); + }); + + it("bounds bearer variants for one pending operation without retaining bearer values", () => { + let token = 0; + const store = new ApprovalStore({ createToken: () => `approval-bounded-${++token}` }); + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call" as const, + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }; + + for (let index = 0; index < 8; index += 1) store.request(binding); + + expect(() => store.request(binding)).toThrow(expect.objectContaining({ code: "APPROVAL_LIMIT_EXCEEDED" })); + expect(JSON.stringify(store.list())).not.toContain("approval-bounded-"); + }); + + it("retains only keyed digests instead of the bearer or sensitive arguments", () => { + const token = "approval-record-secret-token"; + const secretArgument = "approval-record-sensitive-argument"; + const store = new ApprovalStore({ createToken: () => token }); + store.request({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { value: secretArgument } + }); + const records = (store as unknown as { records: Map }).records; + const record = [...records.values()][0]; + + expect(record).toBeDefined(); + expect(JSON.stringify(record)).not.toContain(token); + expect(JSON.stringify(record)).not.toContain(secretArgument); + expect(record).not.toHaveProperty("arguments"); + }); + + it("expires a pending approval before its bearer can be approved", () => { + let now = new Date("2026-07-12T00:00:00.000Z"); + const store = new ApprovalStore({ + now: () => now, + ttlMs: 1_000, + createToken: () => "approval-expired-token" + }); + const requested = store.request({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }); + + now = new Date("2026-07-12T00:00:01.000Z"); + + expect(store.expire()).toEqual([expect.objectContaining({ id: requested.approval.id, status: "expired" })]); + expect(() => store.approve(requested.token)).toThrow(expect.objectContaining({ code: "APPROVAL_EXPIRED" })); + }); + + it("expires an approved approval before it can authorize the matching retry", () => { + let now = new Date("2026-07-12T00:00:00.000Z"); + const store = new ApprovalStore({ + now: () => now, + ttlMs: 1_000, + createToken: () => "approval-approved-expired-token" + }); + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }; + const requested = store.request(binding); + store.approve(requested.token); + + now = new Date("2026-07-12T00:00:01.000Z"); + + expect(store.expire()).toEqual([expect.objectContaining({ id: requested.approval.id, status: "expired" })]); + expect(store.consume(binding)).toBeUndefined(); + }); + + it("does not require a caller to sweep expiry before consuming an approval", () => { + let now = new Date("2026-07-12T00:00:00.000Z"); + const store = new ApprovalStore({ + now: () => now, + ttlMs: 1_000, + createToken: () => "approval-lazy-expired-token" + }); + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }; + const requested = store.request(binding); + store.approve(requested.token); + now = new Date("2026-07-12T00:00:01.000Z"); + + expect(store.consume(binding)).toBeUndefined(); + }); + + it("rejects a bearer from a previous connection session", () => { + let session = 0; + const store = new ApprovalStore({ + createToken: () => "approval-old-session-token", + createSessionId: () => `session-${++session}` + }); + const requested = store.request({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }); + + store.beginSession(); + + expect(() => store.approve(requested.token)).toThrow(expect.objectContaining({ code: "APPROVAL_INVALID" })); + }); + + it("rejects a replay after an explicit denial", () => { + const store = new ApprovalStore({ createToken: () => "approval-denied-token" }); + const requested = store.request({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }); + + expect(store.deny(requested.token)).toMatchObject({ id: requested.approval.id, status: "denied" }); + expect(() => store.approve(requested.token)).toThrow(expect.objectContaining({ code: "APPROVAL_NOT_PENDING" })); + }); + + it("consumes a matching approved operation only once under concurrent retries", async () => { + const store = new ApprovalStore({ createToken: () => "approval-concurrent-token" }); + const binding = { + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name: "first" } + }; + const requested = store.request(binding); + store.approve(requested.token); + + const consumed = await Promise.all([Promise.resolve().then(() => store.consume(binding)), Promise.resolve().then(() => store.consume(binding))]); + + expect(consumed.filter((approval) => approval !== undefined)).toEqual([ + expect.objectContaining({ id: requested.approval.id, status: "consumed" }) + ]); + }); + + it("bounds outstanding approvals and frees terminal records", () => { + let token = 0; + const store = new ApprovalStore({ + maxRecords: 2, + createToken: () => `approval-capacity-${++token}` + }); + const binding = (name: string) => ({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "create_item", + displayName: "create_item", + arguments: { name } + }); + + const first = store.request(binding("first")); + store.request(binding("second")); + + expect(() => store.request(binding("third"))).toThrow(expect.objectContaining({ code: "APPROVAL_LIMIT_EXCEEDED" })); + store.deny(first.token); + expect(store.request(binding("third"))).toMatchObject({ created: true }); + }); +}); diff --git a/tests/cli-exit-codes.test.ts b/tests/cli-exit-codes.test.ts index 6ee44cc3..9e344750 100644 --- a/tests/cli-exit-codes.test.ts +++ b/tests/cli-exit-codes.test.ts @@ -48,6 +48,10 @@ const expectedErrorExitCodes: Record = { ROUTING_BLOCKED: CLI_EXIT_CODES.policy, POLICY_BLOCKED: CLI_EXIT_CODES.policy, POLICY_CONFIRMATION_REQUIRED: CLI_EXIT_CODES.policy, + APPROVAL_INVALID: CLI_EXIT_CODES.policy, + APPROVAL_EXPIRED: CLI_EXIT_CODES.policy, + APPROVAL_NOT_PENDING: CLI_EXIT_CODES.policy, + APPROVAL_LIMIT_EXCEEDED: CLI_EXIT_CODES.policy, IDENTITY_NOT_CONFIGURED: CLI_EXIT_CODES.policy, IDENTITY_MISMATCH: CLI_EXIT_CODES.policy, IDENTITY_PROBE_UNSUPPORTED: CLI_EXIT_CODES.policy, diff --git a/tests/operation-pipeline.test.ts b/tests/operation-pipeline.test.ts index c74288c3..b25fb7a3 100644 --- a/tests/operation-pipeline.test.ts +++ b/tests/operation-pipeline.test.ts @@ -1249,7 +1249,8 @@ describe("operation pipeline routed risk", () => { } as unknown as UpstreamProcessManager, redactor: new SecretRedactor(), routingContext: async () => ({ context: {}, evidence: { cwd: "", fileRoots: [] }, profileHints: [] }), - identities: { requiresVerification: () => false } as unknown as IdentityManager + identities: { requiresVerification: () => false } as unknown as IdentityManager, + approvals: { requireApproval: async () => undefined } }); const audit = new AuditTrail("test").beginOperation({ operation: "tools/call", From 02b16836fadf9e5b20067ab6918f21ce988958e6 Mon Sep 17 00:00:00 2001 From: Mohammed Naji Date: Mon, 13 Jul 2026 11:31:24 +0400 Subject: [PATCH 2/2] fix(policy): preserve approval errors during expiry audit --- src/mcp/server/miftah-server.ts | 11 ++++-- tests/approval-fallback.test.ts | 60 +++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/mcp/server/miftah-server.ts b/src/mcp/server/miftah-server.ts index ff340482..3cfbc8de 100644 --- a/src/mcp/server/miftah-server.ts +++ b/src/mcp/server/miftah-server.ts @@ -36,7 +36,7 @@ import { IdentityManager } from "../../identity/identity-manager.js"; import type { IdentityStatus } from "../../identity/identity-types.js"; import { AuditLogger } from "../../audit/audit-logger.js"; import { AuditScope, AuditTrail, type AuditScopeResult } from "../../audit/audit-trail.js"; -import type { AuditStatus } from "../../audit/audit-types.js"; +import type { ApprovalAuditAction, AuditStatus } from "../../audit/audit-types.js"; import { UpstreamProcessManager, type UpstreamHealth, @@ -940,7 +940,12 @@ export class MiftahServer { try { result = operation(); } catch (error) { - await this.writeExpiredApprovalTransitions(); + try { + await this.writeExpiredApprovalTransitions(); + } catch { + // The transition is restored before this throws and the fail-closed audit logger retains its health failure. + // Preserve the original approval error because it is the actionable result of this operation. + } throw error; } try { @@ -974,7 +979,7 @@ export class MiftahServer { } private async writeApproval( - action: "requested" | "approved" | "denied" | "expired" | "consumed", + action: ApprovalAuditAction, approval: ApprovalSummary ): Promise { await this.auditTrail.writeApproval({ diff --git a/tests/approval-fallback.test.ts b/tests/approval-fallback.test.ts index 4cda2209..5802eebd 100644 --- a/tests/approval-fallback.test.ts +++ b/tests/approval-fallback.test.ts @@ -679,6 +679,66 @@ describe("approval fallback", () => { } }); + it("preserves an expiry error when recording its queued audit transition fails", async () => { + const times = [ + new Date("2026-07-12T00:00:00.000Z"), + new Date("2026-07-12T00:00:00.000Z"), + new Date("2026-07-12T00:00:00.999Z"), + new Date("2026-07-12T00:00:01.000Z") + ]; + const approvals = new ApprovalStore({ + now: () => times.shift() ?? new Date("2026-07-12T00:00:01.000Z"), + ttlMs: 1_000 + }); + const config = validateConfig({ + version: "1", + name: "accounts", + defaultProfile: "work", + upstream: { transport: "stdio", command: process.execPath, args: [fixture] }, + profiles: { work: { policy: "confirm" } }, + policies: { confirm: { requireConfirmation: ["create_item"] } } + }); + const manager = new UpstreamProcessManager(config.upstream!, config.profiles, { startupTimeoutMs: 5_000 }); + const wrapper = new MiftahServer(config, new ProfileManager(config), manager); + const host = wrapper as unknown as { + approvals: ApprovalStore; + writeApproval(action: string, approval: unknown): Promise; + handleManagement( + name: string, + args: Record, + audit: unknown, + source: unknown + ): Promise; + }; + host.approvals = approvals; + const requested = approvals.request({ + sourceProfile: "work", + profile: "work", + upstream: "default", + operation: "tools/call", + name: "expired_item", + displayName: "expired_item", + arguments: {} + }); + host.writeApproval = async (action) => { + if (action === "expired") { + throw new MiftahError("AUDIT_WRITE_FAILED", "AUDIT_WRITE_FAILED: test sink rejected expiry event"); + } + }; + + try { + await expect( + host.handleManagement("miftah_approve", { approval: requested.token }, {}, { activeProfile: "work", revision: 0 }) + ).rejects.toMatchObject({ + code: "APPROVAL_EXPIRED", + message: "APPROVAL_EXPIRED: approval token has expired" + }); + expect(approvals.takeExpiredTransitions()).toHaveLength(1); + } finally { + await wrapper.close(); + } + }); + it("uses a boolean form elicitation when the client supports it", async () => { const directory = await mkdtemp(join(tmpdir(), "miftah-approval-elicit-")); const createCountPath = join(directory, "create-count");