diff --git a/SPEC.md b/SPEC.md index 4dd5de6..c89e288 100644 --- a/SPEC.md +++ b/SPEC.md @@ -77,6 +77,7 @@ B1 agent ↔ broker API: authN with an agent token or an OAuth access token (§4 | Does NOT protect against | Why | |---|---| | Agent reading the field after fill (`input.value`, `Runtime.evaluate`, DOM snapshot, page JS) when the agent has JS/CDP on the same tab | The plaintext must exist in the renderer for the form to submit. 1Password's agent fill has the same property. Mitigations, which reduce exposure but do not remove it: `fill_and_submit`, clear-on-failure, password-type fields only, and an optional agent tool profile with no `evaluate` (OQ-3). | +| The model reading the login URL of a tab `kharon_open` created (`Target.getTargetInfo`, `location.href`, a harness snapshot of the page URL) | The tab is in the agent's own browser, so its CDP session can read the full URL. kharon does not put the path, query or fragment in the tool result, the audit log, or a log line at info or above. Whether the model sees the URL is the harness policy (OQ-3, REQ-API-012). | | Root on agent host | Can read Chromium memory and tunnel keys | | Malicious or XSS'd page on a correctly bound origin | Page receives its own credential by design | | Owner approving a bad request | The human is the oracle. kharon shows origin, item, and agent in the prompt. | @@ -218,6 +219,7 @@ Exposed as MCP (tools below) and HTTP `/v1/*`, with identical semantics. Auth: ` | `kharon_context` | `POST /v1/context` | `{status, browser_context_id?, detail?}` (REQ-ARCH-005) | | `kharon_list` | `GET /v1/items?origin=` | `[ItemMeta]` | | `kharon_search` | `GET /v1/items?q=&origin=` | `[ItemMeta]` | +| `kharon_open` | `POST /v1/open` | `{target_id, origin}` (REQ-API-012) | | `kharon_fill` | `POST /v1/fill` | `FillResult` | | `kharon_fill_totp` | `POST /v1/fill_totp` | `FillResult` | | `kharon_request_grant` | `POST /v1/grants` | `{grant_request_id, state, detail?}` | @@ -249,10 +251,11 @@ There is no read-secret, export, or reveal route, and no `include_secret` flag. | ID | Requirement | AC | |---|---|---| -| REQ-API-001 | MCP server (streamable HTTP) exposing the seven tools with JSON Schemas generated from Rust types (`schemars`). | `mcp-inspector` lists 7 tools. Schemas match the snapshot test. | +| REQ-API-001 | MCP server (streamable HTTP) exposing the eight tools with JSON Schemas generated from Rust types (`schemars`). | `mcp-inspector` lists 8 tools. Schemas match the snapshot test. | | REQ-API-002 | HTTP API with identical semantics and OpenAPI doc. | A contract test runs each case against both transports with identical results. | | REQ-API-003 | Agent token auth. Hash stored with Argon2id. Constant-time compare. OAuth access tokens are REQ-OAU-004. | Bad token → 401. The token store file has no plaintext token (grep). | | REQ-API-004 | `list`/`search` return `ItemMeta` only, filtered by `origin` if given. | Golden test: response keys ⊆ the ItemMeta schema. Canary absent. | +| REQ-API-012 | **Open a saved login URL (#351).** `kharon_open` / `POST /v1/open` takes an item id and opens that item's saved login URL in a new tab in the calling agent's browser context. The result is `{target_id, origin}` and nothing else: `origin` is the tab's live origin (scheme, host, port). The path, query and fragment are not in the result and are not written to a log line at info level or above, nor to the audit entry (`live_origin` is the origin only). The opened tab itself has the full URL, and an agent with CDP on that tab can read it; whether the model sees it is the harness policy (OQ-3, §2.4). The returned origin is the first committed https origin, which on a redirect may be an intermediate hop; the fill's grant-time live-origin check still decides. A deadline that drops the open closes the tab it created. `kharon_search` stays `ItemMeta` (REQ-API-004). A saved URI qualifies only when it is a full `https` URL the §6 matcher would allow as a page at that same URL. A bare host, a non-https URI, and match types `regex` and `never` do not. If none qualifies, the tool returns `no_login_url` and does not navigate. kharon does not guess a login page. The call does not approve a fill: `kharon_fill` afterwards still needs its grant, and the grant-time live-origin check still applies. The tab is created under the same context rules as a fill (`allow_default_context` for the single-agent default context, otherwise the agent's own context) and the new target belongs to that agent. `no_browser` and `target_not_owned` are the existing typed errors. A Connect with no live session is `no_browser` (REQ-OAU-007), after the scope gate. | Golden test: response keys are `target_id` and `origin`; a canary in the saved URI's path and query is absent from the result and the audit log. Real Chromium: open, then a fill that still needs a grant and then fills the opened tab; an item with no verifiable URL is `no_login_url` and creates no tab. | | REQ-API-005 | Secret types (`Secret`) do not implement `Serialize`/`Debug`/`Display`. | A compile-fail test (`trybuild`) shows serializing a `Secret` fails to compile. | | REQ-API-006 | Error `detail` strings are built from an enum, never interpolated with field values. | A lint/test asserts no `format!` in `detail` constructors takes `Secret`. Fuzz finds no canary in details. | | REQ-API-007 | `fill_totp` computes RFC 6238 (SHA1/256/512, digits, period from `otpauth://` or bare base32; `steam://` 5-char) and fills the code. The code is never returned. | RFC 6238 test vectors pass. Steam vector passes. Response has no digits field. The code is computed for the current time step; verification-side tolerance (±1 step) is the site's, so tests assert codes for T-1, T and T+1 match the vectors. At startup the broker compares system time with the Vaultwarden `Date` response header: skew above `clock_skew_warn` (default 30 s) → warning + audit `clock_skew`; above `clock_skew_refuse` (default 90 s) → `fill_totp` returns `error: clock_skew` until resolved. Tests: injected skew of 45 s → warning only; 120 s → `fill_totp` refused, password fills unaffected. | @@ -290,8 +293,8 @@ A customer connects a dashboard (an MCP client such as Muse's or Grok's) with a | REQ-OAU-003 | **Authorize and consent** (owner hostname). **Checks:** `GET /oauth/authorize` checks, in order, (1) the allow-listed client, (2) the CIMD, (3) an exact `redirect_uri` match, (4) `response_type=code`, (5) `code_challenge_method=S256`, (6) `resource` = this deploy's `/mcp` URL, and (7) the requested scopes ⊆ `scopes_supported` (absent means all). Failures at 1–3 render an error page and **never redirect**. Failures at 4–7 redirect with `error`, `state` and `iss`. **Pending authorization:** a valid request becomes a pending authorization, single use, 10 min: a sealed state token (#208) carried in the consent URL, authenticated with an HMAC under a key kharond makes at start, keeps only in memory, and replaces on a panic (REQ-OAU-005). Nothing is stored until the owner decides, so no table can be filled. Its hash is recorded as used when the owner approves or denies. Sign-in, if needed, returns to it. **Consent screen:** it shows `client_name`, the CIMD hostname, the redirect hostname, the scopes in plain words, and the fixed line "Connecting does not let it sign in anywhere on its own. Every sign-in still needs your approval in kharon." **Scopes granted:** the effective request is the requested scopes plus `kharon:read`, which every Connect gets (REQ-OAU-006), and an absent `scope` asks for all three. The owner can untick `kharon:fill` and `kharon:request` on the consent screen but can never add a scope. So the granted scopes are a subset of the effective request and always include `kharon:read`. Because they can differ from the requested ones, the token response always carries `scope` (RFC 6749 §5.1). **Approve:** requires the owner session plus a fresh passkey assertion (user verification) whose challenge commits to the pending authorization: `SHA-256(pending-id ‖ consent nonce ‖ 32 random bytes)`. **Code:** approving issues a code: 32 random bytes, 60 s, single use, in memory only, bound to the client, `redirect_uri`, `code_challenge`, `resource` and the granted scopes. The response includes `iss`. Deny redirects with `access_denied`, creates nothing, and burns the pending authorization. **Framing:** the pages send `frame-ancestors 'none'` and `X-Frame-Options: DENY`. | A consent approved without a fresh assertion, or with an assertion for another pending authorization, is refused. A pending authorization can't be consented twice or approved after a deny, and is gone after 10 min, a restart or a panic. The granted scopes never exceed the effective request. `scope=kharon:fill` is granted `kharon:read kharon:fill`, or `kharon:read` alone if the owner unticks `kharon:fill`, and the token response's `scope` says which. The authorization response's `iss` equals the issuer. A bad `response_type` redirects with `unsupported_response_type`. An unknown scope redirects with `invalid_scope`. A bad client or redirect never redirects. | | REQ-OAU-004† | **Tokens** (`POST /oauth/token`). **Code redemption:** `authorization_code` verifies PKCE S256 and needs `resource` exactly equal to the deploy's `/mcp` URL (anything else, `/connector` included, is refused). Redemption **creates the Connect identity**, then issues an access token `kh_at_<64 hex>` (1 h, audience `/mcp`, the granted scopes) and a refresh token `kh_rt_<64 hex>` (30 days idle, 90 days absolute from consent). The answer is `Cache-Control: no-store`. A second redemption of a code revokes the identity and everything issued from it. **Refresh:** a Connect has two refresh families, and `refresh_token` rotates only the family of the presented token. An MCP-family token names no `resource`, or the deploy's `/mcp` URL, and the new access token's audience is `/mcp`. A connector-family token names the deploy's `/connector` URL, and the new access token's audience is `connector` with scope `kharon:connector`. Any other `resource` for that family is `invalid_target`, and the presented token stays live. A retired refresh token presented again for the resource that family mints revokes the whole Connect, both families, and writes `oauth_refresh_reuse`. One exception: within 30 s of a rotation, one retry with the just-retired token rotates again inside that family and retires the superseded pair, both tokens. A second presentation is reuse. **Connector grant:** `grant_type=urn:kharon:oauth:grant-type:connector` spawns the connector family from a live MCP-family refresh token. Checks run in order. The `client_id` must be the token's client, or the answer is `invalid_grant` and it is not reuse. `resource` must be the deploy's `/connector` URL and `[connector]` must have a certificate, or the answer is `invalid_target` and the presented token is not retired. The token must be a live MCP-family refresh token: a connector-family refresh token, an access token, or an expired or revoked token is `invalid_grant` and nothing is retired. A retired MCP-family refresh token outside its 30 s grace is reuse of the whole Connect; inside that grace the answer is `invalid_grant`, the grace is not spent, and nothing is issued. The client must have declared the grant at consent, or the answer is `unauthorized_client`. A phase-1 identity with no declaration flag has not declared it. The flag is read from the live identity, so a revoked identity is not spawned. The identity's granted scopes must include `kharon:fill`, or the answer is `invalid_grant` and no family is issued. The response is `Cache-Control: no-store`: an access token of audience `connector`, scope exactly `kharon:connector`, `expires_in` 3600, and a new connector-family refresh token. The MCP refresh token stays live. One retry within 30 s of that spawn replaces the connector pair and writes no second audit entry. A further spawn is `invalid_grant` and does not end the Connect, including after that family's refresh token idles out: the customer re-Connects. `authorization_code` with `resource` equal to the `/connector` URL stays `invalid_target`, and the code is not spent. **Storage:** tokens are stored only as SHA-256 hashes, with the identities, in `data_dir/oauth/state.json` (mode 0600, atomic write). The audience is stored on the access token, and on the refresh token, in its own field (`mcp` or `connector`), not folded into scope or resource. A missing audience in an older state file means `/mcp`. Codes and pending authorizations are never written to disk. The file is loaded before any listener opens; with `[oauth]` set, an unparseable file is a startup error. A failed write fails the request with no tokens, and on a refresh the presented pair stays valid for a retry: the store restores the snapshot taken before the rotation. **Where tokens work:** `kh_at_` tokens whose stored audience is `mcp` are accepted on `POST /mcp` only, never on `/v1/*` or any owner surface. A connector-audience access token on `POST /mcp` is 401, checked before the scope gate. | Wrong `code_verifier` → `invalid_grant`. `resource=…/connector` → `invalid_target`. Redeeming a code twice revokes the identity. Refresh A gives A′; A again after 31 s revokes the Connect. A again within 30 s gives A″ and retires A′ (both tokens), and A a third time is reuse. A grep of `state.json` and the logs finds no token, refresh token or code. `kh_at_` on `GET /v1/status` → 401. An expired access token → 401. A corrupt `state.json` with `[oauth]` → startup error. A phase-1 `state.json` record with no audience field still authenticates on `POST /mcp`. A connector-audience access token on `POST /mcp` is 401, not 403 `insufficient_scope`. Spawn with a live MCP refresh token, `kharon:fill` and the recorded declaration returns scope `kharon:connector`; that access token is 401 on `POST /mcp`, and the MCP refresh token still rotates. A second spawn within 30 s replaces the connector pair; a third is `invalid_grant` and the second pair still works. A Connect without `kharon:fill`, or a spawn that presents the connector refresh token, is `invalid_grant` and that token is not retired. A client that did not declare the grant gets `unauthorized_client`, and its MCP refresh token still rotates. Refreshing one family leaves the other live. Each wrong-resource cell is `invalid_target` with the presented token still live. Reuse of a retired connector refresh token outside the grace writes `oauth_refresh_reuse` and refuses the MCP refresh token. `resource=…/connector` on `authorization_code` is `invalid_target`, and a following redemption with the `/mcp` URL still succeeds. | | REQ-OAU-005 | **Revocation.** **Ending a whole Connect:** Disconnect in the owner UI, `kharon revoke agent `, or `POST /oauth/revoke` (RFC 7009) with the Connect's refresh token each ends the whole Connect: the identity, all its tokens and its live grants (REQ-REV-001). It takes effect on the next request and survives a restart. **Ending one token:** `POST /oauth/revoke` with an access token ends only that token. **Panic** (REQ-REV-002) ends every Connect and clears every pending authorization (by replacing the key that seals them, #208) and unredeemed code. An ordinary lock leaves Connects alone. **Connections page (#233):** the owner UI lists each live Connect with its `client_name`, CIMD hostname, granted scopes, connected date and channel, and offers Disconnect and the REQ-RL-002 unsuspend from the page. Approvals, grants and the audit view name a Connect identity by its `client_name` and id (`client_name (c-…)`), never by the name alone — the name is a string the client chose. The page's unsuspend applies to a live Connect only (a config agent's REQ-RL-002 reset stays with the owner socket), and an unsuspend is audited with its surface's channel: `web_ui` from the page, `cli` from the socket. Socket actions on a Connect are audited on channel `cli` (D9), so anything that did not come from the owner's passkey is visible as such. The panic confirmation text and the deployment guide state that a panic means re-clicking Connect on every dashboard. | Disconnect then call `/mcp` within 10 ms → 401. A restart after Disconnect → the token is still refused. Revoking an access token leaves the refresh token working. After panic, every `kh_at_` gets 401, and a consent page opened before the panic can't be approved. After an idle lock, a Connect still answers `kharon_status`. The Connections page lists a live Connect with its name, host, scopes, date and channel; Disconnect from the page refuses its token on the next call and revokes its live grants. An approval row for a Connect's request shows the `client_name` and the `c-…` id. An unsuspend from the page writes `rate_limit`/`unsuspended` on channel `web_ui` and one from the socket on `cli`; the page refuses a config agent's id. A socket `revoke_agent` on a `c-…` id writes `oauth_disconnect` on channel `cli` and no `token_revoke`. | -| REQ-OAU-006 | **Scopes.** **The bundles:** `kharon:read` = `kharon_status`, `kharon_list`, `kharon_search`; `kharon:fill` = `kharon_context`, `kharon_fill`, `kharon_fill_totp`; `kharon:request` = `kharon_request_grant`. `kharon:read` is always granted, requested or not (REQ-OAU-003). `tools/list` returns only the tools the token's scopes allow. **Nothing approves:** no scope approves anything, now or later. Approval stays on the owner surfaces (REQ-APR-001/-004/-005/-006), and none of them accepts an OAuth token. An `Authorization` header whose credential is a `kh_at_` or `kh_rt_` token is 403 `forbidden` on every owner-UI route, the ntfy redeem routes included, before the route runs: a session cookie, an enrollment code and a live approval link are not consulted, and the link is not consumed. A redeem path whose token is itself a `kh_at_` or `kh_rt_` is 410, the same as an unknown approval link. The owner socket refuses a request that carries such a token before the op runs; when that token is the unlock password the answer is `unlock_failed`, the same as any other wrong password. A connector-audience token is still refused on every owner surface, with no new exemption. | A token with `kharon:read` only lists 3 tools. A `kh_at_` or `kh_rt_` token sent to every owner-UI route is 403 `forbidden`, including the connections and panic routes, and an enrollment bearer that is not an OAuth token still starts registration. Presenting the access token as the ntfy path, or as `Authorization` on a live approval link, does not approve, and the link still works afterwards. A socket request carrying the token is `forbidden` and does not run the op; an unlock password that is the token is `unlock_failed`. `scopes_supported` has no approval scope. | -| REQ-OAU-007 | **Connect browsers (#235 phase 2).** A `c-…` identity's browser is the live connector session its connector-audience token attached (REQ-OAU-009): the session is live only while that token's record is live — a record revoked (a refresh grace retry, `/oauth/revoke`) or expired ends it at once, socket open or not. `kharon_context`, `kharon_fill` and `kharon_fill_totp` answer `no_browser` with detail `this connection has no browser attached yet` (REQ-API-006) when the identity has no live, unexpired session. The MCP tool result's `error` is that typed name, not the `forbidden` class the error shares with other 403s. The check stays where phase 1 put it — after the scope gate (a read-only Connect calling `kharon_fill` is `insufficient_scope` first), before the lock, the rate buckets, the grant and the fill backend — and never falls back to a configured endpoint: config agents are not consulted, and a Connect session never satisfies a config agent's CDP lookup or the reverse. With a live session, context and fills ride it to the Connect's browser. **Endings:** Disconnect, `revoke agent`, `/oauth/revoke` of a refresh token, and code or refresh reuse end the Connect and shut its session with it; panic shuts every Connect session; an ordinary lock does not (the lock still closes the broker's CDP connection over the session, as for any agent). **Connections page:** shows whether a session is live for the identity, and since when — never a pin or a token. **Limits:** the `[policy]` rate limits, REQ-RL-002 suspension and its owner reset apply to `c-…` ids as to config agents. | A Connect with `kharon:fill` and no session: context, fill and fill-totp → `no_browser` (detail `this connection has no browser attached yet`), backend untouched; with a live session the context call returns its context id and a granted fill reaches the CDP stub. Disconnect and panic drop the session and `no_browser` returns; a lock leaves the session up. Revoking the session's access token drops it at once. Its list and search calls draw on `list_per_minute` like a config agent's, and 5 consecutive `origin_mismatch` suspend it until the owner resets it. | +| REQ-OAU-006 | **Scopes.** **The bundles:** `kharon:read` = `kharon_status`, `kharon_list`, `kharon_search`; `kharon:fill` = `kharon_context`, `kharon_open`, `kharon_fill`, `kharon_fill_totp`; `kharon:request` = `kharon_request_grant`. `kharon:read` is always granted, requested or not (REQ-OAU-003). `tools/list` returns only the tools the token's scopes allow. **Nothing approves:** no scope approves anything, now or later. Approval stays on the owner surfaces (REQ-APR-001/-004/-005/-006), and none of them accepts an OAuth token. An `Authorization` header whose credential is a `kh_at_` or `kh_rt_` token is 403 `forbidden` on every owner-UI route, the ntfy redeem routes included, before the route runs: a session cookie, an enrollment code and a live approval link are not consulted, and the link is not consumed. A redeem path whose token is itself a `kh_at_` or `kh_rt_` is 410, the same as an unknown approval link. The owner socket refuses a request that carries such a token before the op runs; when that token is the unlock password the answer is `unlock_failed`, the same as any other wrong password. A connector-audience token is still refused on every owner surface, with no new exemption. | A token with `kharon:read` only lists 3 tools. A `kh_at_` or `kh_rt_` token sent to every owner-UI route is 403 `forbidden`, including the connections and panic routes, and an enrollment bearer that is not an OAuth token still starts registration. Presenting the access token as the ntfy path, or as `Authorization` on a live approval link, does not approve, and the link still works afterwards. A socket request carrying the token is `forbidden` and does not run the op; an unlock password that is the token is `unlock_failed`. `scopes_supported` has no approval scope. | +| REQ-OAU-007 | **Connect browsers (#235 phase 2).** A `c-…` identity's browser is the live connector session its connector-audience token attached (REQ-OAU-009): the session is live only while that token's record is live — a record revoked (a refresh grace retry, `/oauth/revoke`) or expired ends it at once, socket open or not. `kharon_context`, `kharon_open`, `kharon_fill` and `kharon_fill_totp` answer `no_browser` with detail `this connection has no browser attached yet` (REQ-API-006) when the identity has no live, unexpired session. The MCP tool result's `error` is that typed name, not the `forbidden` class the error shares with other 403s. The check stays where phase 1 put it — after the scope gate (a read-only Connect calling `kharon_fill` is `insufficient_scope` first), before the lock, the rate buckets, the grant and the fill backend — and never falls back to a configured endpoint: config agents are not consulted, and a Connect session never satisfies a config agent's CDP lookup or the reverse. With a live session, context and fills ride it to the Connect's browser. **Endings:** Disconnect, `revoke agent`, `/oauth/revoke` of a refresh token, and code or refresh reuse end the Connect and shut its session with it; panic shuts every Connect session; an ordinary lock does not (the lock still closes the broker's CDP connection over the session, as for any agent). **Connections page:** shows whether a session is live for the identity, and since when — never a pin or a token. **Limits:** the `[policy]` rate limits, REQ-RL-002 suspension and its owner reset apply to `c-…` ids as to config agents. | A Connect with `kharon:fill` and no session: context, open, fill and fill-totp → `no_browser` (detail `this connection has no browser attached yet`), backend untouched; with a live session the context call returns its context id and a granted fill reaches the CDP stub. Disconnect and panic drop the session and `no_browser` returns; a lock leaves the session up. Revoking the session's access token drops it at once. Its list and search calls draw on `list_per_minute` like a config agent's, and 5 consecutive `origin_mismatch` suspend it until the owner resets it. | | REQ-OAU-008 | **Abuse limits.** `/oauth/authorize`, `/oauth/token` and `/oauth/revoke` are unauthenticated and on the internet. They are throttled per trusted source, keyed by #200's `CF-Connecting-IP` helper, which keys throttling and audit but never gates auth. There is no global bucket. `/oauth/token` and `/oauth/revoke` are on the owner UI's named exemption list (#208): there is no `Origin` rule, and they need an Access bypass when Access is on. Checking a `kh_at_` token costs a hash lookup, never an Argon2id permit. | A flood from one source is throttled while another source completes a Connect. `/oauth/authorize` is throttled per source, not globally: one source past the limit is 429 while another source's authorize still redirects. The token endpoint answers a request with no `Origin` header. | | REQ-OAU-009 | **Connector hello (#235).** On wire v1 (`WIRE_VERSION` stays 1, no new status byte) the broker dispatches on the hello token's prefix after the inner TLS and the hello parse, before any Argon2id permit. `kh_at_` is a SHA-256 lookup in the OAuth store and never reaches the tunnel verifier. `kh_rt_` is `AUTH_UNAUTHORIZED` with no lookup. Anything else takes the tunnel path, unchanged. A `kh_at_` reaches `AUTH_OK` only when, in this order, it is a live access token (else detail `unauthorized`), its audience is `connector` (else `audience`), its identity is the hello's agent id (else `identity`), and it carries `kharon:connector` (else `scope`). A refusal never touches another session. Without `[oauth]` every `kh_at_` hello is refused, still without a permit. **Expiry:** the session carries the access token's stored `expires_at`. It is dropped then, with no grace, and past it the session is absent to every lookup even before the drop. The drop is a detach log line, not an audit entry. | A connector `kh_at_` with its own `c-…` id attaches over the WebSocket and raw TLS, and a fill over it reaches the CDP stub. With both Argon2id permits held, `kh_at_` and `kh_rt_` hellos are still answered at once. An `/mcp` token in the hello is `audience`. `kh_rt_` is `unauthorized` with no lookup. The right token under another id is `identity` and evicts nobody. A session is dropped at its token's expiry and is absent past it before any timer runs. | diff --git a/crates/kharond/src/api/core.rs b/crates/kharond/src/api/core.rs index 976f130..b350844 100644 --- a/crates/kharond/src/api/core.rs +++ b/crates/kharond/src/api/core.rs @@ -58,13 +58,16 @@ use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; use super::approval::{ApprovalAction, ApprovalTokenStore, TokenGone}; use super::error::{ApiError, Detail}; -use super::fill::{FillBackend, FillOperation, FillPolicy, FillRequest, FillResult, FillStatus}; +use super::fill::{ + FillBackend, FillOperation, FillPolicy, FillRequest, FillResult, FillStatus, OpenError, +}; use super::grant::{ Channel, Grant, GrantAction, GrantError, GrantPolicy, GrantRequest, GrantRequestArgs, GrantRequestBody, GrantScope, GrantStore, GrantTerms, GrantView, RequestState, }; use super::meta::{ItemMeta, matches_origin, matches_query}; use super::notify::ApprovalNotifier; +use super::open::{OpenResult, verifiable_login_url}; use super::rate::{FillBacking, RateDenied, RateLimiter, RatePolicy}; use super::rollback::RollbackGuard; use super::token::TokenStore; @@ -307,6 +310,8 @@ pub enum Outcome { Context(ContextResult), /// `kharon_request_grant` result (any state, including refusals). GrantRequest(GrantRequestBody), + /// `kharon_open` result: target id and live origin only. + Open(OpenResult), } impl Outcome { @@ -318,6 +323,7 @@ impl Outcome { Self::Fill(r) => serde_json::to_value(r), Self::Context(r) => serde_json::to_value(r), Self::GrantRequest(r) => serde_json::to_value(r), + Self::Open(r) => serde_json::to_value(r), }; v.expect("invariant: API bodies serialize") } @@ -2640,6 +2646,159 @@ impl Broker { Ok(Outcome::Context(body)) } + /// Open the item's saved login URL in a new tab in `agent`'s + /// browser context (REQ-API-012). Returns the target id and the + /// tab's live origin. Does not approve a fill, and does not reset + /// the idle timer. + /// + /// Refusals before any browser command (`no_login_url`, unknown + /// item, locked, `no_browser`) write one `open` outcome and do not + /// navigate. A call that reaches the browser is two transitions: + /// `open_dispatch` before the CDP write, then one `open` outcome + /// whose `live_origin` is the origin only. + pub async fn open( + &self, + agent: &AgentId, + item_id: String, + received: Instant, + ) -> Result { + self.open_from(agent, item_id, received, None).await + } + + /// [`open`](Self::open) admitted by a network transport. + pub async fn open_from( + &self, + agent: &AgentId, + item_id: String, + received: Instant, + client_ip: Option, + ) -> Result { + self.require_tool(agent, "kharon_open")?; + self.require_browser(agent)?; + let deadline = received + self.fill_policy.deadline; + let request_id = new_request_id(); + let base = |e: Event| { + stamp( + Entry::new(e) + .agent_id(agent.id.clone()) + .item_id(item_id.clone()) + .request_id(request_id.clone()), + &client_ip, + ) + }; + let url = { + let mut lock = self.lock.lock().unwrap_or_else(|p| p.into_inner()); + let session = match lock.require_unlocked() { + Ok(session) => session, + Err(_) => { + drop(lock); + self.append(base(Event::Open).result("locked"))?; + return Err(ApiError::LOCKED); + } + }; + let item = match session.vault().get(&item_id) { + Ok(item) => item, + Err(_) => { + drop(lock); + self.append(base(Event::Open).result("not_found"))?; + return Err(ApiError::UNKNOWN_ITEM); + } + }; + match verifiable_login_url(item) { + Some(url) => url, + None => { + drop(lock); + self.append(base(Event::Open).result("no_login_url"))?; + return Err(ApiError::NO_LOGIN_URL); + } + } + }; + let generation = { + // Read under the gate's mutex, as for a fill (#66). + let _lock = self.lock.lock().unwrap_or_else(|p| p.into_inner()); + match &self.fill_backend { + Some(b) if b.has_agent(agent.as_str()) => Some((Arc::clone(b), b.generation())), + _ => None, + } + }; + // The URL is held only to hand to the browser. It is not an + // audit field and not a log line (REQ-API-012). + let opened = match generation { + None => Err(OpenError::Unavailable), + Some(_) if Instant::now() >= deadline => Err(OpenError::Cdp), + Some((backend, generation)) => { + self.append(base(Event::OpenDispatch).result("dispatched"))?; + let mut guard = ContextGuard { + audit: &self.audit, + abort_entry: Some( + base(Event::Open) + .result("aborted") + .detail_code("handler_dropped"), + ), + }; + let allow_default = self.fill_policy.allow_default_context; + let open = + backend.open_in_generation(agent.as_str(), &url, allow_default, generation); + let r = match tokio::time::timeout_at(deadline, open).await { + Ok(r) => r, + Err(_) => Err(OpenError::Cdp), + }; + guard.abort_entry = None; + // A timeout is distinguished from a browser failure by + // the clock, not by the URL. + if Instant::now() >= deadline && r.is_err() { + Err(OpenError::Unavailable) + } else { + r + } + } + }; + // Drop the URL before the outcome is built so a later format + // of this frame cannot print it. `opened` does not borrow it. + drop(url); + match opened { + Ok(tab) => { + self.append( + base(Event::Open) + .result("ok") + .live_origin(tab.origin.clone()), + )?; + Ok(Outcome::Open(OpenResult { + target_id: tab.target_id, + origin: tab.origin, + })) + } + Err(OpenError::TargetNotOwned) => { + self.append(base(Event::Open).result("target_not_owned"))?; + Err(ApiError::TARGET_NOT_OWNED) + } + Err(OpenError::Unavailable) if Instant::now() >= deadline => { + self.append( + base(Event::Open) + .result("timeout") + .detail_code("deadline_expired"), + )?; + Err(ApiError::DEADLINE) + } + Err(OpenError::Unavailable) => { + self.append(base(Event::Open).result("error").detail_code("cdp_error"))?; + Err(ApiError::BROWSER_FAILED) + } + Err(OpenError::Cdp) if Instant::now() >= deadline => { + self.append( + base(Event::Open) + .result("timeout") + .detail_code("deadline_expired"), + )?; + Err(ApiError::DEADLINE) + } + Err(OpenError::Cdp) => { + self.append(base(Event::Open).result("error").detail_code("cdp_error"))?; + Err(ApiError::BROWSER_FAILED) + } + } + } + /// SPEC §8 (REQ-CRY-009, issue #100): if the unlocked vault is /// older than [`crate::sync::MAX_SYNC_INTERVAL`], fetch a fresh /// `/api/sync` (outside the mutex, within the fill deadline) and diff --git a/crates/kharond/src/api/error.rs b/crates/kharond/src/api/error.rs index 2afb9e7..0c970b2 100644 --- a/crates/kharond/src/api/error.rs +++ b/crates/kharond/src/api/error.rs @@ -164,6 +164,22 @@ pub enum Detail { /// context/fill cannot run (REQ-OAU-007 phase 1; #232). The /// typed error's name is `no_browser`; this is its plain message. NoBrowser, + /// The item has no saved URI that is a full `https` URL the + /// origin matcher would allow (REQ-API-012). The typed error's + /// name is `no_login_url`. + NoLoginUrl, + /// The tab is not in the calling agent's browser context + /// (REQ-ARCH-005). The typed error's name is `target_not_owned`. + TargetNotOwned, + /// `item_id` is not an in-scope vault item. + UnknownItem, + /// `kharon_open` did not finish inside the fill deadline. + Deadline, + /// A browser command failed. The text is fixed: a CDP message can + /// echo the URL the broker just sent (REQ-API-012). + BrowserFailed, + /// `kharon_open` arguments do not match the schema. + InvalidOpenRequest, } impl Detail { @@ -201,11 +217,17 @@ impl Detail { Self::RateLimited => "rate limited; retry later or ask the owner to unsuspend", Self::InsufficientScope => "token does not have the scope this tool needs", Self::NoBrowser => "this connection has no browser attached yet", + Self::NoLoginUrl => "this item has no verifiable https login URL", + Self::TargetNotOwned => "target is not in this agent's browser context", + Self::UnknownItem => "no such item", + Self::Deadline => "the deadline expired", + Self::BrowserFailed => "the browser command failed", + Self::InvalidOpenRequest => "open request does not match the schema", } } /// Every detail (for the REQ-API-006 tests). - pub const ALL: [Self; 31] = [ + pub const ALL: [Self; 37] = [ Self::MissingToken, Self::InvalidToken, Self::ToolNotAllowed, @@ -237,6 +259,12 @@ impl Detail { Self::RateLimited, Self::InsufficientScope, Self::NoBrowser, + Self::NoLoginUrl, + Self::TargetNotOwned, + Self::UnknownItem, + Self::Deadline, + Self::BrowserFailed, + Self::InvalidOpenRequest, ]; } @@ -272,6 +300,19 @@ impl ApiError { /// ([`Self::tool_error`]); [`Self::body`] keeps the `forbidden` /// class, which this error shares with other 403s. pub const NO_BROWSER: Self = Self::new(ErrorCode::Forbidden, Detail::NoBrowser); + /// 403, the item has no verifiable https login URL (REQ-API-012). + /// MCP tool results report `no_login_url`. + pub const NO_LOGIN_URL: Self = Self::new(ErrorCode::Forbidden, Detail::NoLoginUrl); + /// 403, the tab is not in this agent's browser context. + /// MCP tool results report `target_not_owned`. + pub const TARGET_NOT_OWNED: Self = Self::new(ErrorCode::Forbidden, Detail::TargetNotOwned); + /// 404, `item_id` is not an in-scope item. + pub const UNKNOWN_ITEM: Self = Self::new(ErrorCode::NotFound, Detail::UnknownItem); + /// 400, `kharon_open` passed the fill deadline. MCP reports `timeout`. + pub const DEADLINE: Self = Self::new(ErrorCode::BadRequest, Detail::Deadline); + /// 400, a browser command failed. The detail does not carry the + /// browser's message (REQ-API-012). MCP reports `cdp_error`. + pub const BROWSER_FAILED: Self = Self::new(ErrorCode::BadRequest, Detail::BrowserFailed); /// 423. pub const LOCKED: Self = Self::new(ErrorCode::Locked, Detail::Locked); /// 500, REQ-AUD-003 fail-closed. @@ -308,6 +349,10 @@ impl ApiError { pub const fn tool_error(self) -> &'static str { match (self.code, self.detail) { (ErrorCode::Forbidden, Detail::NoBrowser) => "no_browser", + (ErrorCode::Forbidden, Detail::NoLoginUrl) => "no_login_url", + (ErrorCode::Forbidden, Detail::TargetNotOwned) => "target_not_owned", + (ErrorCode::BadRequest, Detail::Deadline) => "timeout", + (ErrorCode::BadRequest, Detail::BrowserFailed) => "cdp_error", _ => self.code.as_str(), } } diff --git a/crates/kharond/src/api/fill.rs b/crates/kharond/src/api/fill.rs index 97869b5..b978ee3 100644 --- a/crates/kharond/src/api/fill.rs +++ b/crates/kharond/src/api/fill.rs @@ -295,7 +295,7 @@ fn from_json Deserialize<'de>>(json: &[u8]) -> Result { } /// `8-4-4-4-12` hex digits; returned lowercase (vault ids are). -fn canonical_uuid(id: &str) -> Result { +pub(crate) fn canonical_uuid(id: &str) -> Result { let ok = id.len() == ITEM_ID_LEN && id.bytes().enumerate().all(|(i, b)| match i { 8 | 13 | 18 | 23 => b == b'-', @@ -434,6 +434,30 @@ pub type ContextFuture<'a> = Pin = Pin> + Send + 'a>>; +/// A tab `kharon_open` created (REQ-API-012). `origin` is the live +/// origin only: scheme, host and port. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OpenedTab { + /// CDP target id of the new tab. + pub target_id: String, + /// Live origin (`https://host[:port]`). + pub origin: String, +} + +/// Why opening a tab failed, with no URL in the value (REQ-API-012). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OpenError { + /// The new tab is not in the agent's context. + TargetNotOwned, + /// This backend has no browser for the agent. + Unavailable, + /// A browser command failed. The browser's message is dropped. + Cdp, +} + +/// A boxed open future (REQ-API-012). +pub type OpenFuture<'a> = Pin> + Send + 'a>>; + /// Why a backend without browser contexts refuses a context request. const NO_CONTEXTS: &str = "backend has no browser contexts"; @@ -525,6 +549,20 @@ pub trait FillBackend: Send + Sync { let _ = (agent_id, target_id, allow_default); Box::pin(async { None }) } + + /// Open `url` in a new tab in the agent's context (REQ-API-012). + /// The returned origin is the tab's live origin. `url` must not be + /// logged. The default backend cannot open a tab. + fn open_in_generation<'a>( + &'a self, + agent_id: &'a str, + url: &'a str, + allow_default: bool, + generation: u64, + ) -> OpenFuture<'a> { + let _ = (agent_id, url, allow_default, generation); + Box::pin(async { Err(OpenError::Unavailable) }) + } } /// The production backend: the CDP [`FillEngine`], one [`AgentContext`] @@ -595,6 +633,29 @@ impl FillBackend for CdpFillBackend { .ok() }) } + + fn open_in_generation<'a>( + &'a self, + agent_id: &'a str, + url: &'a str, + allow_default: bool, + generation: u64, + ) -> OpenFuture<'a> { + let _ = generation; + Box::pin(async move { + let Some((engine, ctx)) = self.agents.get(agent_id) else { + return Err(OpenError::TargetNotOwned); + }; + match engine.open_login(url, ctx, allow_default).await { + Ok((target_id, origin)) => Ok(OpenedTab { target_id, origin }), + Err(crate::cdp::OwnershipError::TargetNotOwned) + | Err(crate::cdp::OwnershipError::DefaultContextRefused) => { + Err(OpenError::TargetNotOwned) + } + Err(_) => Err(OpenError::Cdp), + } + }) + } } /// The daemon's backend: one configured CDP endpoint per agent @@ -1102,6 +1163,45 @@ impl FillBackend for ConnectingCdpBackend { }) } + /// Same lazy connect as a fill, then one new tab (REQ-API-012). + fn open_in_generation<'a>( + &'a self, + agent_id: &'a str, + url: &'a str, + allow_default: bool, + generation: u64, + ) -> OpenFuture<'a> { + Box::pin(async move { + let Some(agent) = self.agent_for(agent_id) else { + return Err(OpenError::TargetNotOwned); + }; + let c = match agent + .engine( + agent_id, + self.connect_timeout, + self.teardown_timeout, + generation, + &self.generation, + ) + .await + { + Ok(c) => c, + Err(_) => return Err(OpenError::Cdp), + }; + if self.generation() != generation { + return Err(OpenError::Cdp); + } + match c.engine.open_login(url, &c.ctx, allow_default).await { + Ok((target_id, origin)) => Ok(OpenedTab { target_id, origin }), + Err(crate::cdp::OwnershipError::TargetNotOwned) + | Err(crate::cdp::OwnershipError::DefaultContextRefused) => { + Err(OpenError::TargetNotOwned) + } + Err(_) => Err(OpenError::Cdp), + } + }) + } + /// The published copy only: never waits on a connect in flight. A /// context from a locked generation or on a connection that ended /// is reported as none, even before its teardown has run. diff --git a/crates/kharond/src/api/http.rs b/crates/kharond/src/api/http.rs index 710cbe9..0db61d0 100644 --- a/crates/kharond/src/api/http.rs +++ b/crates/kharond/src/api/http.rs @@ -13,6 +13,7 @@ //! | `GET /v1/items?q=[&origin=]` | bearer | search, `[ItemMeta]` | //! | `POST /v1/fill` | bearer | `FillRequest` → `FillResult` (`submit: true` is `fill_and_submit`) | //! | `POST /v1/fill_totp` | bearer | `FillTotpRequest` → `FillResult` | +//! | `POST /v1/open` | bearer | `{item_id}` → `{target_id, origin}` (REQ-API-012) | //! | `POST /v1/context` | bearer | empty or `{}` → `ContextResult` (the agent's `browserContextId`, #65) | //! | `POST /v1/grants` | bearer | `GrantRequest` → `GrantRequestBody` (`{grant_request_id, state}`, #20) | //! | `GET /v1/openapi.json` | none | the OpenAPI document | @@ -61,6 +62,7 @@ use super::error::{ApiError, Detail, ErrorCode}; use super::fill::{FillOperation, parse_fill}; use super::grant::{ApprovalPrompt, parse_grant}; use super::mcp::{MAX_BODY_BYTES, is_json}; +use super::open::parse_open; use super::transport::ClientIp; use crate::lock::Clock; @@ -318,6 +320,8 @@ enum Route { OpenApi, } +/// `POST /v1/open` (REQ-API-012). +pub const OPEN_PATH: &str = "/v1/open"; /// `POST /v1/fill`. pub const FILL_PATH: &str = "/v1/fill"; /// `POST /v1/fill_totp`. @@ -345,6 +349,7 @@ where "/v1/status" => Route::Status, "/v1/items" => Route::Items, "/v1/openapi.json" => Route::OpenApi, + OPEN_PATH => return handle_open(state, req, received).await, FILL_PATH => return handle_fill(state, req, FillOperation::Fill, received).await, FILL_TOTP_PATH => { return handle_fill(state, req, FillOperation::FillTotp, received).await; @@ -435,6 +440,56 @@ where } } +async fn handle_open(state: Arc>, req: Request, received: Instant) -> Response +where + S: VaultView + 'static, + C: Clock + Send + 'static, +{ + if req.method() != Method::POST { + return method_not_allowed("POST"); + } + if req.headers().contains_key(header::ORIGIN) { + return error(ApiError::new( + ErrorCode::Forbidden, + Detail::BrowserOriginRefused, + )); + } + let token = bearer_token(&req); + let (parts, body) = req.into_parts(); + let agent = match authenticate(&state, token).await { + Ok(a) => a, + Err(e) => return error(e), + }; + if !is_json(&parts.headers) { + return error(ApiError::bad_request(Detail::UnsupportedContentType)); + } + let client_ip = parts.extensions.get::().map(|c| c.0); + drop(parts); + let Ok(bytes) = to_bytes(body, MAX_BODY_BYTES).await else { + return error(ApiError::BODY_TOO_LARGE); + }; + let item_id = match parse_open(&bytes) { + Ok(id) => id, + Err(e) => return error(e), + }; + drop(bytes); + match state + .broker + .open_from(&agent, item_id, received, client_ip) + .await + { + Ok(o) => json_response(StatusCode::OK, o.body().to_string()), + // Typed names (`no_login_url`, `target_not_owned`, `no_browser`, + // `timeout`, `cdp_error`) on both transports. The HTTP status + // stays the error's class. + Err(e) => { + let status = StatusCode::from_u16(e.code.http_status()) + .expect("invariant: ErrorCode maps to valid statuses"); + json_response(status, e.tool_body().to_string()) + } + } +} + async fn handle_context( state: Arc>, req: Request, diff --git a/crates/kharond/src/api/mcp.rs b/crates/kharond/src/api/mcp.rs index bcb52f2..fe8cb39 100644 --- a/crates/kharond/src/api/mcp.rs +++ b/crates/kharond/src/api/mcp.rs @@ -16,6 +16,7 @@ //! | `kharon_status` | `GET /v1/status` | //! | `kharon_list` | `GET /v1/items[?origin=]` | //! | `kharon_search` | `GET /v1/items?q=[&origin=]` | +//! | `kharon_open` | `POST /v1/open` | //! | `kharon_fill` | `POST /v1/fill` | //! | `kharon_fill_totp` | `POST /v1/fill_totp` | //! | `kharon_context` | `POST /v1/context` (#65) | @@ -150,9 +151,11 @@ const CACHE_TTL_MS: u64 = 3_600_000; const INSTRUCTIONS: &str = "kharon credentials broker. No tool ever returns a secret: \ kharon_list and kharon_search return item metadata, and kharon_fill / kharon_fill_totp type the \ item's username, password or current TOTP code into a tab in your own browser context and \ -report only which fields were filled. kharon_context returns your own browserContextId: open the \ -tabs you want filled in it. The live page origin decides, never your claim. Every call is \ -audited."; +report only which fields were filled. kharon_open opens the item's saved login URL in a new tab \ +in that context and returns only the tab id and the live origin. kharon does not return or log \ +the path, query or fragment; the tab itself has the full URL, and whether you see it depends on \ +your harness. kharon_context returns your own browserContextId. The live page origin \ +decides, never your claim. Every call is audited."; // ---------------------------------------------------------------- tools @@ -199,6 +202,8 @@ pub enum Tool { List, /// `kharon_search`. Search, + /// `kharon_open` (REQ-API-012). + Open, /// `kharon_fill` (#18). Fill, /// `kharon_fill_totp` (#19). @@ -211,10 +216,11 @@ pub enum Tool { impl Tool { /// Every tool, in `tools/list` order. - pub const ALL: [Self; 7] = [ + pub const ALL: [Self; 8] = [ Self::Status, Self::List, Self::Search, + Self::Open, Self::Fill, Self::FillTotp, Self::Context, @@ -227,6 +233,7 @@ impl Tool { Self::Status => "kharon_status", Self::List => "kharon_list", Self::Search => "kharon_search", + Self::Open => "kharon_open", Self::Fill => "kharon_fill", Self::FillTotp => "kharon_fill_totp", Self::Context => "kharon_context", @@ -247,7 +254,7 @@ impl Tool { Self::Status => Some(Operation::Status), Self::List => Some(Operation::List), Self::Search => Some(Operation::Search), - Self::Fill | Self::FillTotp | Self::Context | Self::RequestGrant => None, + Self::Fill | Self::FillTotp | Self::Context | Self::RequestGrant | Self::Open => None, } } @@ -257,7 +264,12 @@ impl Tool { match self { Self::Fill => Some(FillOperation::Fill), Self::FillTotp => Some(FillOperation::FillTotp), - Self::Status | Self::List | Self::Search | Self::Context | Self::RequestGrant => None, + Self::Status + | Self::List + | Self::Search + | Self::Open + | Self::Context + | Self::RequestGrant => None, } } @@ -267,6 +279,7 @@ impl Tool { Self::Status | Self::Context => &[], Self::List => &["origin"], Self::Search => &["q", "origin"], + Self::Open => &["item_id"], Self::Fill | Self::FillTotp => &["item_id", "target", "fields", "submit", "grant_id"], Self::RequestGrant => &["item_id", "target", "action"], } @@ -277,6 +290,7 @@ impl Tool { Self::Status => "Broker status", Self::List => "List items", Self::Search => "Search items", + Self::Open => "Open an item's login URL", Self::Fill => "Fill a login form", Self::FillTotp => "Fill a TOTP code", Self::Context => "Your browser context", @@ -300,6 +314,15 @@ impl Tool { "Item metadata (never secrets) whose name or URI host contains q, optionally \ filtered by origin. Audited. Same body as GET /v1/items?q=." } + Self::Open => { + "Open the item's saved login URL in a new tab in your own browser context. \ + Returns only the new tab's target_id and its live origin (scheme, host, port). \ + kharon does not return or log the path, query or fragment. The tab itself has \ + the full URL. Refuses with no_login_url, and \ + does not navigate, when the item has no saved URI that is a full https URL the \ + origin matcher would allow. Does not approve a fill: kharon_fill still needs \ + its grant. Requires unlock. Audited. Same body as POST /v1/open." + } Self::Fill => { "Type the item's username and/or password into the tab cdp_target_id in your \ own browser context; with submit: true, submit the form once every field \ @@ -344,6 +367,7 @@ impl Tool { Self::Status => generator.into_root_schema_for::(), Self::List => generator.into_root_schema_for::(), Self::Search => generator.into_root_schema_for::(), + Self::Open => generator.into_root_schema_for::(), Self::Fill => generator.into_root_schema_for::(), Self::FillTotp => generator.into_root_schema_for::(), Self::Context => generator.into_root_schema_for::(), @@ -845,7 +869,15 @@ where Err(e) => Err(e), } } - _ => unreachable!("only context and request_grant have no operation"), + Tool::Open => { + match fill_arguments(call.arguments).and_then(super::open::parse_open) { + Ok(item_id) => { + broker.open_from(agent, item_id, received, client_ip).await + } + Err(e) => Err(e), + } + } + _ => unreachable!("only context, open and request_grant have no operation"), }, }; match outcome { diff --git a/crates/kharond/src/api/mod.rs b/crates/kharond/src/api/mod.rs index 3638238..b02d2d9 100644 --- a/crates/kharond/src/api/mod.rs +++ b/crates/kharond/src/api/mod.rs @@ -40,6 +40,7 @@ pub mod meta; pub mod notify; pub mod oauth; pub mod oauth_store; +pub mod open; pub mod public; pub mod rate; pub mod revocation; @@ -67,6 +68,7 @@ pub use grant::{ }; pub use meta::ItemMeta; pub use notify::{ApprovalNotifier, NtfyApprovalNotifier}; +pub use open::{OpenResult, parse_open}; pub use rate::{RateDenied, RateLimiter, RatePolicy}; pub use rollback::{RollbackGuard, RollbackReason}; pub use token::{ParamFloor, TokenStore}; diff --git a/crates/kharond/src/api/oauth.rs b/crates/kharond/src/api/oauth.rs index 14e9983..1c51d13 100644 --- a/crates/kharond/src/api/oauth.rs +++ b/crates/kharond/src/api/oauth.rs @@ -78,7 +78,12 @@ pub const SCOPE_TOOLS: [(&str, &[&str]); 3] = [ ), ( "kharon:fill", - &["kharon_context", "kharon_fill", "kharon_fill_totp"], + &[ + "kharon_context", + "kharon_open", + "kharon_fill", + "kharon_fill_totp", + ], ), ("kharon:request", &["kharon_request_grant"]), ]; diff --git a/crates/kharond/src/api/open.rs b/crates/kharond/src/api/open.rs new file mode 100644 index 0000000..0693971 --- /dev/null +++ b/crates/kharond/src/api/open.rs @@ -0,0 +1,145 @@ +//! `kharon_open` / `POST /v1/open` (REQ-API-012, #351). +//! +//! The agent names an item. The broker opens that item's saved login +//! URL in a new tab in the agent's own browser context and returns +//! only the tab's target id and live origin. kharon does not return +//! or log the path, query or fragment. The opened tab has the full +//! URL; whether the model sees it is the harness policy (SPEC OQ-3). +//! +//! A saved URI counts only when it is a full `https` URL the SPEC §6 +//! matcher would allow as a page at that same URL. A bare host, a +//! non-https URI, and the `regex` and `never` match types do not. +//! With none, the call is `no_login_url` and nothing is navigated. +//! kharon does not guess a login page. +//! +//! Opening a tab does not approve a fill. The fill that follows still +//! needs its grant, and the grant-time live-origin check still runs. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use super::error::{ApiError, Detail}; +use super::fill::canonical_uuid; +use crate::origin::OriginMatcher; +use crate::sync::Item; + +/// `kharon_open` arguments. +#[derive(Debug, Clone, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct OpenArgs { + /// The item whose saved login URL to open. + pub item_id: String, +} + +/// `kharon_open` success body. Exactly these two fields: the new tab +/// and its live origin (scheme, host, port). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)] +pub struct OpenResult { + /// CDP target id of the new tab. It belongs to the calling agent. + pub target_id: String, + /// The tab's live origin, `https://host[:port]`. + pub origin: String, +} + +/// The first saved URI that is a full https URL the origin matcher +/// would allow at that URL, with userinfo removed. `None` when nothing +/// qualifies. The returned string still has the path, query and +/// fragment: it is the navigation target, not a tool result, and must +/// not be logged. +pub fn verifiable_login_url(item: &Item) -> Option { + item.uris().iter().find_map(|u| { + let matcher = OriginMatcher::new(&u.uri, u.match_type).ok()?; + if !matcher.verifiable_https_login() { + return None; + } + Some(matcher.navigation_url()) + }) +} + +/// Validate `kharon_open` arguments. The body is the HTTP body and the +/// MCP arguments object. +pub fn parse_open(json: &[u8]) -> Result { + if json.iter().all(u8::is_ascii_whitespace) { + return Err(ApiError::bad_request(Detail::InvalidOpenRequest)); + } + let args: OpenArgs = serde_json::from_slice(json).map_err(|e| match e.classify() { + serde_json::error::Category::Data => ApiError::bad_request(Detail::InvalidOpenRequest), + _ => ApiError::bad_request(Detail::InvalidJsonBody), + })?; + canonical_uuid(&args.item_id) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sync::ItemUri; + + fn item(uris: Vec<(&str, Option)>) -> Item { + Item::from_parts( + "aaaaaaaa-0000-4000-8000-0000000000b1".into(), + "n".into(), + None, + uris.into_iter() + .map(|(uri, match_type)| ItemUri { + uri: uri.to_owned(), + match_type, + }) + .collect(), + None, + None, + None, + ) + } + + #[test] + fn https_url_is_the_navigation_target_and_userinfo_is_stripped() { + let url = verifiable_login_url(&item(vec![( + "https://user:secret@login.example.com/KHARON_OPEN_PATH_CANARY?q=KHARON_OPEN_QUERY_CANARY#KHARON_OPEN_FRAG_CANARY", + None, + )])) + .unwrap(); + assert!(url.starts_with("https://login.example.com/KHARON_OPEN_PATH_CANARY?")); + assert!(url.contains("KHARON_OPEN_QUERY_CANARY")); + assert!(url.contains("KHARON_OPEN_FRAG_CANARY")); + assert!(!url.contains("secret")); + assert!(!url.contains("user")); + } + + #[test] + fn bare_host_regex_http_and_never_do_not_qualify() { + assert!(verifiable_login_url(&item(vec![("login.example.com", None)])).is_none()); + assert!( + verifiable_login_url(&item(vec![( + "https://login.example.com/KHARON_OPEN_PATH_CANARY?q=KHARON_OPEN_QUERY_CANARY", + Some(4), + )])) + .is_none() + ); + assert!( + verifiable_login_url(&item(vec![( + "http://login.example.com/KHARON_OPEN_PATH_CANARY", + None, + )])) + .is_none() + ); + assert!( + verifiable_login_url(&item(vec![("https://login.example.com/login", Some(5),)])) + .is_none() + ); + } + + #[test] + fn the_first_verifiable_uri_wins() { + let url = verifiable_login_url(&item(vec![ + ("login.example.com", None), + ( + "https://login.example.com/first?q=KHARON_OPEN_QUERY_CANARY", + Some(3), + ), + ("https://other.example.com/second", None), + ])) + .unwrap(); + assert!(url.contains("/first")); + assert!(!url.contains("/second")); + } +} diff --git a/crates/kharond/src/api/public.rs b/crates/kharond/src/api/public.rs index ef4e16b..2b6d71a 100644 --- a/crates/kharond/src/api/public.rs +++ b/crates/kharond/src/api/public.rs @@ -548,6 +548,7 @@ mod tests { (Method::GET, "/v1/items"), (Method::GET, "/v1/openapi.json"), (Method::POST, "/v1/fill"), + (Method::POST, "/v1/open"), (Method::POST, "/v1/grants"), (Method::GET, "/owner/session"), (Method::GET, "/owner/approve/x"), diff --git a/crates/kharond/src/api/surface.rs b/crates/kharond/src/api/surface.rs index a51261e..b67109c 100644 --- a/crates/kharond/src/api/surface.rs +++ b/crates/kharond/src/api/surface.rs @@ -26,12 +26,14 @@ use super::fill::FillResult; use super::grant::GrantRequestBody; use super::mcp::Tool; use super::meta::ItemMeta; +use super::open::OpenResult; /// The HTTP route serving the same operation as `tool`: `(method, path)`. pub const fn http_route(tool: Tool) -> (&'static str, &'static str) { match tool { Tool::Status => ("GET", "/v1/status"), Tool::List | Tool::Search => ("GET", "/v1/items"), + Tool::Open => ("POST", super::http::OPEN_PATH), Tool::Fill => ("POST", super::http::FILL_PATH), Tool::FillTotp => ("POST", super::http::FILL_TOTP_PATH), Tool::Context => ("POST", super::http::CONTEXT_PATH), @@ -45,6 +47,7 @@ pub fn response_schema(tool: Tool) -> Schema { match tool { Tool::Status => schema_of::(), Tool::List | Tool::Search => schema_of::>(), + Tool::Open => schema_of::(), Tool::Fill | Tool::FillTotp => schema_of::(), Tool::Context => schema_of::(), Tool::RequestGrant => schema_of::(), diff --git a/crates/kharond/src/audit/entry.rs b/crates/kharond/src/audit/entry.rs index 7840cae..48b38c3 100644 --- a/crates/kharond/src/audit/entry.rs +++ b/crates/kharond/src/audit/entry.rs @@ -66,6 +66,15 @@ pub enum Event { /// (`cdp_error`, `fill_unavailable`), `locked`, or `aborted` /// (`handler_dropped`, best effort from a drop guard). Context, + /// REQ-API-012: `kharon_open` is about to create a tab and navigate + /// it. Appended before any CDP write. Carries the request id and + /// item id, never the URL. + OpenDispatch, + /// REQ-API-012: the outcome of `kharon_open`. `live_origin` on an + /// `ok` result is the origin only (scheme, host, port). Result + /// `no_login_url`, `not_found` and `locked` are written with no + /// preceding dispatch, because the browser was not touched. + Open, /// REQ-API-007: the system clock differs from the Vaultwarden /// server's `Date` by more than `clock_skew_warn` (result `warn` or /// `refuse`), or a previous skew was resolved (result `resolved`). @@ -168,6 +177,8 @@ impl Event { Event::FillAborted => "fill_aborted", Event::ContextOpen => "context_open", Event::Context => "context", + Event::OpenDispatch => "open_dispatch", + Event::Open => "open", Event::ClockSkew => "clock_skew", Event::LogTruncated => "log_truncated", Event::ConnectorAuthFail => "connector_auth_fail", @@ -220,6 +231,8 @@ impl<'de> Deserialize<'de> for Event { "fill_aborted" => Event::FillAborted, "context_open" => Event::ContextOpen, "context" => Event::Context, + "open_dispatch" => Event::OpenDispatch, + "open" => Event::Open, "clock_skew" => Event::ClockSkew, "log_truncated" => Event::LogTruncated, "connector_auth_fail" => Event::ConnectorAuthFail, diff --git a/crates/kharond/src/audit/verify.rs b/crates/kharond/src/audit/verify.rs index abf6e12..38e9d86 100644 --- a/crates/kharond/src/audit/verify.rs +++ b/crates/kharond/src/audit/verify.rs @@ -146,7 +146,7 @@ pub(crate) fn read_chain(path: &Path) -> Result { let mut hashes: Vec = Vec::new(); let mut log_id: Option = None; // request_id → (dispatch seq, outcome seen, is context_open). - let mut dispatches: HashMap = HashMap::new(); + let mut dispatches: HashMap = HashMap::new(); let mut duplicate: Option = None; let mut tail: VecDeque = VecDeque::with_capacity(TAIL_KEEP); for (i, line) in data.lines().enumerate() { @@ -203,8 +203,12 @@ pub(crate) fn read_chain(path: &Path) -> Result { if let Some(rid) = &entry.request_id { match entry.event { - Event::FillDispatch | Event::ContextOpen => { - let kind = entry.event == Event::ContextOpen; + Event::FillDispatch | Event::ContextOpen | Event::OpenDispatch => { + let kind = match entry.event { + Event::ContextOpen => 1u8, + Event::OpenDispatch => 2u8, + _ => 0u8, + }; dispatches .entry(rid.clone()) .or_insert((entry.seq, false, kind)); @@ -213,8 +217,13 @@ pub(crate) fn read_chain(path: &Path) -> Result { | Event::FillTotp | Event::FillTimeout | Event::FillAborted - | Event::Context => { - let kind = entry.event == Event::Context; + | Event::Context + | Event::Open => { + let kind = match entry.event { + Event::Context => 1u8, + Event::Open => 2u8, + _ => 0u8, + }; if let Some((_, seen, k)) = dispatches.get_mut(rid) && *k == kind { diff --git a/crates/kharond/src/cdp/browser.rs b/crates/kharond/src/cdp/browser.rs index 74873e6..08ede81 100644 --- a/crates/kharond/src/cdp/browser.rs +++ b/crates/kharond/src/cdp/browser.rs @@ -367,6 +367,182 @@ impl Browser { .iter() .any(|created| created == id) } + + /// Open `url` in a new tab in the agent's context and return the + /// target id plus the tab's live https origin (REQ-API-012). + /// + /// `allow_default` creates the tab in the browser's default context + /// (the single-agent escape hatch, the same one fills accept). + /// Otherwise the tab is created in `agent_ctx`. The new target is + /// checked with [`Self::check_ownership`] before navigation; a tab + /// that would not belong to the agent is closed and not navigated. + /// + /// `url` is sent only as the `Page.navigate` parameter. It is not + /// logged, and it is not copied into the error text: a browser + /// message can echo it (REQ-API-012). The returned origin is + /// scheme, host and port. + pub async fn open_login_tab( + &self, + agent_ctx: &AgentContext, + allow_default: bool, + url: &str, + ) -> Result<(String, String), OwnershipError> { + let mut params = json!({ "url": "about:blank" }); + if !allow_default { + params["browserContextId"] = json!(agent_ctx.browser_context_id()); + } + let created = self + .client + .request("Target.createTarget", params) + .await + .map_err(|_| OwnershipError::Cdp("create_target_failed".into()))?; + let target_id = created + .get("targetId") + .and_then(Value::as_str) + .ok_or_else(|| OwnershipError::Cdp("create_target_failed".into()))? + .to_string(); + // Armed until the open succeeds. A drop (the fill deadline + // cancelling this future mid-navigate) closes the tab, so a + // timeout does not leave the full URL open in the agent's + // context (REQ-API-012). + let mut guard = TabGuard::arm(self.client.clone(), target_id.clone()); + if let Err(e) = self + .check_ownership(&target_id, agent_ctx, allow_default) + .await + { + self.close_guard(&mut guard).await; + return Err(e); + } + let attached = self.client.attach(&target_id).await; + let session = match attached { + Ok(session) => session, + Err(_) => { + self.close_guard(&mut guard).await; + return Err(OwnershipError::Cdp("navigate_failed".into())); + } + }; + let navigated = session + .request("Page.navigate", json!({ "url": url })) + .await; + session.detach().await; + if navigated.is_err() { + self.close_guard(&mut guard).await; + return Err(OwnershipError::Cdp("navigate_failed".into())); + } + match self.wait_https_origin(&target_id).await { + Ok(origin) => { + guard.disarm(); + Ok((target_id, origin)) + } + Err(e) => { + self.close_guard(&mut guard).await; + Err(e) + } + } + } + + /// Close the guarded tab and disarm, so `Drop` does not close it + /// again. If this future is cancelled mid-close, `Drop` still + /// closes. + async fn close_guard(&self, guard: &mut TabGuard) { + let Some(id) = guard.target_id.clone() else { + return; + }; + let _ = self + .client + .request("Target.closeTarget", json!({ "targetId": id })) + .await; + guard.disarm(); + } + + /// Poll the target until its live URL has an https origin, or the + /// navigation has clearly failed. The URL itself is never returned. + async fn wait_https_origin(&self, target_id: &str) -> Result { + let started = tokio::time::Instant::now(); + loop { + let info = self + .target_info(target_id) + .await + .map_err(|_| OwnershipError::Cdp("navigate_failed".into()))?; + if let Some(origin) = https_origin_only(&info.url) { + return Ok(origin); + } + if !is_blank_url(&info.url) { + return Err(OwnershipError::Cdp("navigate_failed".into())); + } + if started.elapsed() > std::time::Duration::from_secs(8) { + return Err(OwnershipError::Cdp("navigate_failed".into())); + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + } +} + +/// Closes `target_id` if this open is dropped before it succeeds. +/// +/// The broker bounds `kharon_open` with `timeout_at`, which drops the +/// future. Without this, a deadline during `Page.navigate` or the +/// origin poll would leave the tab at the full login URL (REQ-API-012). +struct TabGuard { + client: CdpClient, + target_id: Option, +} + +impl TabGuard { + fn arm(client: CdpClient, target_id: String) -> Self { + Self { + client, + target_id: Some(target_id), + } + } + + fn disarm(&mut self) { + self.target_id = None; + } +} + +impl Drop for TabGuard { + fn drop(&mut self) { + let Some(target_id) = self.target_id.take() else { + return; + }; + let client = self.client.clone(); + if let Ok(handle) = tokio::runtime::Handle::try_current() { + handle.spawn(async move { + let _ = client + .request("Target.closeTarget", json!({ "targetId": target_id })) + .await; + }); + } + } +} + +/// `about:blank` and the empty URL, which a new tab reports before +/// navigation commits. +fn is_blank_url(href: &str) -> bool { + href.is_empty() || href == "about:blank" || href.starts_with("about:blank#") +} + +/// Scheme, host and port of an https URL. `None` when `href` is not +/// https, or when the origin serialization still carries a path, +/// query, fragment or userinfo. +fn https_origin_only(href: &str) -> Option { + let url = url::Url::parse(href).ok()?; + if url.scheme() != "https" { + return None; + } + let origin = url.origin().ascii_serialization(); + if origin == "null" || origin.contains('?') || origin.contains('#') || origin.contains('@') { + return None; + } + let parsed = url::Url::parse(&origin).ok()?; + if parsed.path() != "/" && !parsed.path().is_empty() { + return None; + } + if parsed.query().is_some() || parsed.fragment().is_some() { + return None; + } + Some(origin) } /// `allow_default` admits a target the broker has classified as the @@ -387,7 +563,7 @@ mod tests { use super::*; use std::collections::HashMap; use std::sync::Arc; - use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use futures_util::{SinkExt, StreamExt}; use tokio::net::TcpListener; @@ -850,4 +1026,72 @@ mod tests { .unwrap(); assert_eq!(info.browser_context_id.as_deref(), Some("ctx-plain")); } + + /// A navigate that never replies, dropped by the fill deadline, + /// still closes the tab (REQ-API-012). + #[tokio::test] + async fn req_api_012_dropped_navigate_closes_the_tab() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let closed = Arc::new(AtomicBool::new(false)); + let methods = Arc::new(Mutex::new(Vec::::new())); + let closed_peer = Arc::clone(&closed); + let methods_peer = Arc::clone(&methods); + tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut ws = accept_async(stream).await.unwrap(); + while let Some(Ok(tokio_tungstenite::tungstenite::Message::Text(text))) = + ws.next().await + { + let msg: Value = serde_json::from_str(&text).unwrap(); + let method = msg["method"].as_str().unwrap_or("").to_string(); + methods_peer.lock().unwrap().push(method.clone()); + if method == "Page.navigate" { + continue; + } + if method == "Target.closeTarget" { + closed_peer.store(true, Ordering::SeqCst); + } + let result = match method.as_str() { + "Target.createBrowserContext" => json!({ "browserContextId": "ctx-A" }), + "Target.createTarget" => json!({ "targetId": "tab-1" }), + "Target.getTargetInfo" => { + target_info_json("tab-1", Some("ctx-A"), "about:blank") + } + "Target.attachToTarget" => json!({ "sessionId": "sess-1" }), + _ => json!({}), + }; + let reply = json!({ "id": msg["id"], "result": result }); + ws.send(tokio_tungstenite::tungstenite::Message::Text( + reply.to_string(), + )) + .await + .unwrap(); + } + }); + let endpoint = super::super::endpoint::CdpEndpoint::validate( + &format!("ws://{addr}/devtools/browser"), + super::super::endpoint::Tunnel::Direct, + None, + ) + .unwrap(); + let browser = Browser::new(CdpClient::connect(&endpoint).await.unwrap()); + let ctx = browser.create_agent_context("agent-A").await.unwrap(); + let open = browser.open_login_tab( + &ctx, + false, + "https://login.example.com/KHARON_OPEN_PATH_CANARY?q=1", + ); + let timed = tokio::time::timeout(std::time::Duration::from_millis(300), open).await; + assert!(timed.is_err(), "a stalled navigate must still be pending"); + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2); + while !closed.load(Ordering::SeqCst) { + assert!( + tokio::time::Instant::now() < deadline, + "dropped navigate did not close the tab: {:?}", + methods.lock().unwrap() + ); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + } } diff --git a/crates/kharond/src/cdp/fill.rs b/crates/kharond/src/cdp/fill.rs index 73ae0a8..822ab2a 100644 --- a/crates/kharond/src/cdp/fill.rs +++ b/crates/kharond/src/cdp/fill.rs @@ -302,6 +302,19 @@ impl FillEngine { self.browser.client().is_closed() } + /// Open `url` in a new tab and return `(target_id, live origin)`. + /// The URL is not copied into the error (REQ-API-012). + pub async fn open_login( + &self, + url: &str, + agent_ctx: &AgentContext, + allow_default: bool, + ) -> Result<(String, String), OwnershipError> { + self.browser + .open_login_tab(agent_ctx, allow_default, url) + .await + } + /// The live serialized origin of `target_id` (REQ-APR-007, #20): /// the ownership check a fill runs in its step 1, and nothing /// else — no attach, no page code. Grant requests observe through diff --git a/crates/kharond/src/origin.rs b/crates/kharond/src/origin.rs index 7e041be..e548b7c 100644 --- a/crates/kharond/src/origin.rs +++ b/crates/kharond/src/origin.rs @@ -312,6 +312,29 @@ impl OriginMatcher { Decision::refuse(MismatchReason::HrefMismatch) } } + + /// Whether this saved URI is a full `https` URL the matcher would + /// allow as a page at that same URL (REQ-API-012). + /// + /// Regex, never, and any non-https scheme are not. A bare host never + /// reaches here: [`Self::new`] rejects it. `allow_http` is not + /// consulted: `kharon_open` does not navigate to `http`. + pub fn verifiable_https_login(&self) -> bool { + self.url.scheme() == "https" + && self + .decide(self.url.as_str(), &OriginConfig { allow_http: false }) + .allowed + } + + /// The URL `kharon_open` navigates to: the saved URL with userinfo + /// removed. Path, query and fragment stay. Callers must not log + /// this string (REQ-API-012). + pub fn navigation_url(&self) -> String { + let mut url = self.url.clone(); + let _ = url.set_username(""); + let _ = url.set_password(None); + url.to_string() + } } /// How a host participates in a `Domain` comparison. Derived once by diff --git a/crates/kharond/src/sync/vault.rs b/crates/kharond/src/sync/vault.rs index 1a34533..81b1b81 100644 --- a/crates/kharond/src/sync/vault.rs +++ b/crates/kharond/src/sync/vault.rs @@ -167,6 +167,15 @@ impl Item { self.revision = revision; } + /// Clone this item with different login URIs. Secrets and the + /// rest of the metadata are preserved (tests retarget a fixture + /// item at a loopback page). + pub fn with_uris(&self, uris: Vec) -> Self { + let mut item = self.clone(); + item.uris = uris; + item + } + /// Clone this item with a different `revisionDate` (REQ-REV-004 /// tests): secrets and metadata are preserved. pub fn with_revision(&self, revision: Option) -> Self { diff --git a/crates/kharond/tests/api_support/mod.rs b/crates/kharond/tests/api_support/mod.rs index 7fc43e3..06e91a0 100644 --- a/crates/kharond/tests/api_support/mod.rs +++ b/crates/kharond/tests/api_support/mod.rs @@ -15,7 +15,7 @@ use std::time::Duration; use argon2::Argon2; use kharon_bwcrypto::Kdf; -use kharond::api::fill::{ContextFuture, FillFuture, ObserveFuture}; +use kharond::api::fill::{ContextFuture, FillFuture, ObserveFuture, OpenFuture, OpenedTab}; use kharond::api::grant::{Channel, GrantAction, GrantScope, GrantTerms}; use kharond::api::token::{ParamFloor, TokenStore, generate_with}; use kharond::api::{AuditSink, Broker, FillBackend, VaultView}; @@ -640,6 +640,9 @@ pub struct FakeFill { /// Answers to give, one per fill, before falling back to `answer` /// (REQ-APR-008 tests refuse a fill, then fill on the same grant). pub script: Arc>>, + /// URLs `kharon_open` handed this backend. The tool result must not + /// echo them (REQ-API-012). + pub opened: Arc>>, } impl FakeFill { @@ -651,6 +654,7 @@ impl FakeFill { context_calls: Arc::default(), locks: Arc::default(), script: Arc::default(), + opened: Arc::default(), } } @@ -770,6 +774,25 @@ impl FillBackend for FakeFill { fn on_lock(&self) { *self.locks.lock().unwrap() += 1; } + + fn open_in_generation<'a>( + &'a self, + _agent_id: &'a str, + url: &'a str, + _allow_default: bool, + _generation: u64, + ) -> OpenFuture<'a> { + self.opened.lock().unwrap().push(url.to_owned()); + let origin = url::Url::parse(url) + .map(|u| u.origin().ascii_serialization()) + .unwrap_or_else(|_| "null".to_owned()); + Box::pin(async move { + Ok(OpenedTab { + target_id: "tab-open".to_owned(), + origin, + }) + }) + } } /// `POST ` with a JSON `body` and an optional bearer token. diff --git a/crates/kharond/tests/public_ingress.rs b/crates/kharond/tests/public_ingress.rs index bf92953..1e78cf5 100644 --- a/crates/kharond/tests/public_ingress.rs +++ b/crates/kharond/tests/public_ingress.rs @@ -38,6 +38,7 @@ const REFUSED: &[(&str, &str)] = &[ ("POST", "/v1/fill"), ("POST", "/v1/fill_totp"), ("POST", "/v1/context"), + ("POST", "/v1/open"), ("POST", "/v1/grants"), ("GET", "/owner/session"), ("POST", "/owner/unlock"), @@ -98,7 +99,7 @@ async fn public_ingress_serves_mcp_like_the_api_listener() { let r = mcp_request(addr, Some(&h.alpha), "tools/list", "{}").await; assert_eq!(r.status, 200, "{}", r.body); - assert_eq!(r.json()["result"]["tools"].as_array().unwrap().len(), 7); + assert_eq!(r.json()["result"]["tools"].as_array().unwrap().len(), 8); let r = mcp_call(addr, Some(&h.alpha), "kharon_status", "{}").await; assert_eq!(r.status, 200, "{}", r.body); diff --git a/crates/kharond/tests/req_api_001_mcp.rs b/crates/kharond/tests/req_api_001_mcp.rs index cc8028b..58d5a9b 100644 --- a/crates/kharond/tests/req_api_001_mcp.rs +++ b/crates/kharond/tests/req_api_001_mcp.rs @@ -4,7 +4,7 @@ //! test. (Semantics are REQ-API-002's contract test, which runs every //! case over MCP too.) //! -//! All seven tools exist: `kharon_request_grant` landed with #20 +//! All eight tools exist: `kharon_request_grant` landed with #20 //! and is in [`Tool::ALL`] and the snapshot. mod api_support; @@ -205,6 +205,7 @@ async fn req_api_001_tools_list_serves_the_generated_tools() { "kharon_status", "kharon_list", "kharon_search", + "kharon_open", "kharon_fill", "kharon_fill_totp", "kharon_context", diff --git a/crates/kharond/tests/req_api_002_contract.rs b/crates/kharond/tests/req_api_002_contract.rs index ae3b727..a5b16ac 100644 --- a/crates/kharond/tests/req_api_002_contract.rs +++ b/crates/kharond/tests/req_api_002_contract.rs @@ -575,6 +575,7 @@ async fn req_api_002_openapi_document_matches_the_routes() { "/v1/fill", "/v1/fill_totp", "/v1/context", + "/v1/open", "/v1/grants", "/v1/openapi.json" ]) @@ -628,8 +629,8 @@ async fn req_api_002_openapi_document_matches_the_routes() { assert_eq!(r.status, 405); assert_eq!(r.header("allow"), Some("GET")); assert_eq!(r.header("cache-control"), Some("no-store")); - // The fill routes and /v1/context are POST-only. - for p in ["/v1/fill", "/v1/fill_totp", "/v1/context"] { + // The fill routes, /v1/open and /v1/context are POST-only. + for p in ["/v1/fill", "/v1/fill_totp", "/v1/open", "/v1/context"] { let r = get(addr, p, Some(&h.alpha)).await; assert_eq!(r.status, 405, "{p}"); assert_eq!(r.header("allow"), Some("POST"), "{p}"); diff --git a/crates/kharond/tests/req_api_012_open.rs b/crates/kharond/tests/req_api_012_open.rs new file mode 100644 index 0000000..971f662 --- /dev/null +++ b/crates/kharond/tests/req_api_012_open.rs @@ -0,0 +1,235 @@ +//! REQ-API-012: `kharon_open` returns only `target_id` and the live +//! origin. A canary in the saved URI's path, query and fragment is +//! absent from the tool result and from the audit log. `kharon_search` +//! stays metadata (REQ-API-004). + +mod api_support; + +use std::collections::BTreeSet; +use std::sync::Arc; + +use api_support::*; +use kharond::api::fill::FillPolicy; +use kharond::api::http::OPENAPI_JSON; +use kharond::api::{Broker, OpenResult}; +use kharond::lock::{LockController, LockPolicy, StaticHardening}; +use kharond::origin::OriginConfig; +use kharond::sync::{ItemUri, SyncReport, Vault}; +use serde_json::Value; + +const PATH_CANARY: &str = "KHARON_OPEN_PATH_CANARY"; +const QUERY_CANARY: &str = "KHARON_OPEN_QUERY_CANARY"; +const FRAG_CANARY: &str = "KHARON_OPEN_FRAG_CANARY"; + +fn schema(name: &str) -> (BTreeSet, BTreeSet) { + let doc: Value = serde_json::from_str(OPENAPI_JSON).unwrap(); + let s = &doc["components"]["schemas"][name]; + assert_eq!( + s["additionalProperties"], + Value::Bool(false), + "{name} is closed" + ); + let props = s["properties"] + .as_object() + .unwrap() + .keys() + .cloned() + .collect(); + let required = s["required"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_owned()) + .collect(); + (props, required) +} + +fn keys(v: &Value) -> BTreeSet { + v.as_object().unwrap().keys().cloned().collect() +} + +fn assert_no_url_canary(text: &str) { + assert!(!text.contains(PATH_CANARY), "path canary leaked: {text}"); + assert!(!text.contains(QUERY_CANARY), "query canary leaked: {text}"); + assert!( + !text.contains(FRAG_CANARY), + "fragment canary leaked: {text}" + ); + assert!(!text.contains("user:secret"), "userinfo leaked: {text}"); +} + +struct Rig { + broker: Arc, + alpha: String, + audit: RecordingAudit, + fake: FakeFill, +} + +impl Rig { + fn new() -> Self { + let (session, vault) = fixture(); + let uri = format!( + "https://user:secret@app.example.com/{PATH_CANARY}?q={QUERY_CANARY}#{FRAG_CANARY}" + ); + let item = vault.get(ITEM_B).unwrap().with_uris(vec![ItemUri { + uri, + match_type: None, + }]); + let vault = Vault::with_report(vec![item], SyncReport::default()); + let (alpha, hash) = kharond::api::token::generate_with(&cheap_argon(), "alpha"); + let tokens = + kharond::api::token::TokenStore::with_floor([("alpha", hash.as_str())], &CHEAP_FLOOR) + .unwrap(); + let clock = Arc::new(kharond::lock::ManualClock::new()); + let mut lock = LockController::new( + LockPolicy::default(), + clock, + Box::new(StaticHardening::all_ok()), + ); + lock.unlock(|| Ok::<_, ()>(TestSession(Arc::new(vault), session.clone()))) + .unwrap(); + let audit = RecordingAudit::default(); + let fake = FakeFill::new(FakeAnswer::Filled); + let broker = Broker::new( + tokens, + lock, + Box::new(audit.clone()), + OriginConfig::default(), + ) + .with_fill_policy(FillPolicy::default()) + .with_fill_backend(Box::new(fake.clone())); + Self { + broker: Arc::new(broker), + alpha: alpha.expose_secret().clone(), + audit, + fake, + } + } +} + +#[test] +fn req_api_012_open_result_type_is_the_schema() { + let full = OpenResult { + target_id: "t".into(), + origin: "https://app.example.com".into(), + }; + let v = serde_json::to_value(&full).unwrap(); + assert_eq!(keys(&v), schema("OpenResult").0); + assert_eq!(v["origin"], "https://app.example.com"); +} + +#[tokio::test] +async fn req_api_012_golden_response_is_target_and_origin_and_canary_is_absent() { + let (props, required) = schema("OpenResult"); + assert_eq!( + props, + BTreeSet::from(["target_id".to_owned(), "origin".to_owned()]) + ); + let rig = Rig::new(); + let addr = serve_http(rig.broker.clone()).await; + let body = format!(r#"{{"item_id":"{ITEM_B}"}}"#); + + let http = post_json(addr, "/v1/open", Some(&rig.alpha), &body).await; + assert_eq!(http.status, 200, "{}", http.body); + assert_no_url_canary(&http.body); + assert_no_canary(&http.body); + let http_json = http.json(); + let k = keys(&http_json); + assert_eq!(k, props, "extra or missing keys {k:?}"); + assert!(required.is_subset(&k)); + assert_eq!(http_json["target_id"], "tab-open"); + assert_eq!(http_json["origin"], "https://app.example.com"); + + let mcp = mcp_call(addr, Some(&rig.alpha), "kharon_open", &body).await; + assert_eq!(mcp.status, 200, "{}", mcp.body); + let v = mcp.json(); + assert_eq!(v["result"]["isError"], false, "{v}"); + let text = v["result"]["content"][0]["text"].as_str().unwrap(); + assert_eq!(text, http.body.trim()); + assert_no_url_canary(text); + assert_no_url_canary(&mcp.body); + + // The broker did navigate to the saved URL. Only the result hides it. + let opened = rig.fake.opened.lock().unwrap().clone(); + assert_eq!(opened.len(), 2, "http and mcp each open a tab"); + for url in &opened { + assert!(url.contains(PATH_CANARY), "{url}"); + assert!(url.contains(QUERY_CANARY), "{url}"); + assert!(url.contains(FRAG_CANARY), "{url}"); + assert!(!url.contains("secret"), "{url}"); + } + + let audit = serde_json::to_string(&*rig.audit.entries.lock().unwrap()).unwrap(); + assert_no_url_canary(&audit); + assert!(audit.contains("\"event\":\"open\"") || audit.contains("open")); + + // REQ-API-004 is unchanged: search still returns the host only. + let listed = get(addr, "/v1/items?q=fixture", Some(&rig.alpha)).await; + assert_eq!(listed.status, 200, "{}", listed.body); + assert_no_url_canary(&listed.body); + let item = &listed.json()[0]; + assert_eq!(item["uris"][0]["host"], "app.example.com"); + assert!(item["uris"][0].get("path").is_none()); +} + +#[tokio::test] +async fn req_api_012_no_login_url_does_not_open() { + let (session, vault) = fixture(); + let item = vault.get(ITEM_A).unwrap().with_uris(vec![ + ItemUri { + uri: format!("login.example.com/{PATH_CANARY}?q={QUERY_CANARY}"), + match_type: None, + }, + ItemUri { + uri: format!("https://login.example.com/{PATH_CANARY}?q={QUERY_CANARY}"), + match_type: Some(4), + }, + ItemUri { + uri: format!("http://login.example.com/{PATH_CANARY}"), + match_type: None, + }, + ]); + let vault = Vault::with_report(vec![item], SyncReport::default()); + let (alpha, hash) = kharond::api::token::generate_with(&cheap_argon(), "alpha"); + let tokens = + kharond::api::token::TokenStore::with_floor([("alpha", hash.as_str())], &CHEAP_FLOOR) + .unwrap(); + let clock = Arc::new(kharond::lock::ManualClock::new()); + let mut lock = LockController::new( + LockPolicy::default(), + clock, + Box::new(StaticHardening::all_ok()), + ); + lock.unlock(|| Ok::<_, ()>(TestSession(Arc::new(vault), session.clone()))) + .unwrap(); + let audit = RecordingAudit::default(); + let fake = FakeFill::new(FakeAnswer::Filled); + let broker = Arc::new( + Broker::new( + tokens, + lock, + Box::new(audit.clone()), + OriginConfig::default(), + ) + .with_fill_backend(Box::new(fake.clone())), + ); + let alpha = alpha.expose_secret().clone(); + let addr = serve_http(broker).await; + let body = format!(r#"{{"item_id":"{ITEM_A}"}}"#); + let http = post_json(addr, "/v1/open", Some(&alpha), &body).await; + assert_eq!(http.status, 403, "{}", http.body); + assert_eq!(http.json()["error"], "no_login_url"); + assert_no_url_canary(&http.body); + let mcp = mcp_call(addr, Some(&alpha), "kharon_open", &body).await; + let v = mcp.json(); + assert_eq!(v["result"]["isError"], true, "{v}"); + let text = v["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("\"error\":\"no_login_url\""), "{text}"); + assert_no_url_canary(text); + assert!( + fake.opened.lock().unwrap().is_empty(), + "refused open navigated" + ); + let audit = serde_json::to_string(&*audit.entries.lock().unwrap()).unwrap(); + assert_no_url_canary(&audit); +} diff --git a/crates/kharond/tests/req_api_012_open_chromium.rs b/crates/kharond/tests/req_api_012_open_chromium.rs new file mode 100644 index 0000000..5f4673c --- /dev/null +++ b/crates/kharond/tests/req_api_012_open_chromium.rs @@ -0,0 +1,439 @@ +//! REQ-API-012 on real Chromium: `kharon_open` navigates the saved +//! login URL, a following fill still needs its grant, and an item +//! with no verifiable URL is `no_login_url` with no new tab. +//! +//! Skips when no Chromium binary is found (as +//! `req_arch_005_default_context_tab_on_real_chromium` does). +//! `KHARON_CHROMIUM` names one, and `KHARON_REQUIRE_CHROMIUM=1` turns +//! the skip into a failure. The Chromium flags are for this +//! throwaway test browser only. + +mod api_support; + +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use api_support::{ + CHEAP_FLOOR, ITEM_A, ITEM_B, RecordingAudit, TestSession, cheap_argon, fixture, mcp_call, + post_json, serve_http, +}; +use base64ct::{Base64, Encoding}; +use kharond::api::fill::FillPolicy; +use kharond::api::token::{TokenStore, generate_with}; +use kharond::api::{Broker, Channel, GrantScope, GrantTerms}; +use kharond::cdp::{CdpClient, CdpEndpoint, Tunnel}; +use kharond::config::GrantKind; +use kharond::lock::{LockController, LockPolicy, StaticHardening}; +use kharond::origin::OriginConfig; +use kharond::sync::{ItemUri, SecretField, SyncReport, Vault}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +const PATH_CANARY: &str = "KHARON_OPEN_PATH_CANARY"; +const QUERY_CANARY: &str = "KHARON_OPEN_QUERY_CANARY"; +const FRAG_CANARY: &str = "KHARON_OPEN_FRAG_CANARY"; + +const PAGE: &str = r#" +kharon open + +
+ + + +
+ + +"#; + +fn chromium_bin() -> Option { + if let Ok(p) = std::env::var("KHARON_CHROMIUM") { + return Some(PathBuf::from(p)); + } + [ + "/usr/bin/google-chrome", + "/usr/bin/google-chrome-stable", + "/usr/local/bin/google-chrome", + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + ] + .into_iter() + .map(PathBuf::from) + .find(|p| p.exists()) +} + +fn chromium_or_skip(test: &str) -> Option { + let bin = chromium_bin(); + if bin.is_none() { + if std::env::var_os("KHARON_REQUIRE_CHROMIUM").is_some() { + panic!("KHARON_REQUIRE_CHROMIUM is set but no Chromium binary was found"); + } + eprintln!("SKIP {test}: no Chromium binary"); + } + bin +} + +struct Chromium { + child: Child, + ws: String, + _profile: tempfile::TempDir, +} + +impl Drop for Chromium { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn launch_chromium(bin: &Path, host: &str, spki: &str) -> Chromium { + let profile = tempfile::tempdir().unwrap(); + let mut child = Command::new(bin) + .args([ + "--headless=new", + "--no-sandbox", + "--disable-gpu", + "--disable-dev-shm-usage", + "--no-first-run", + "--no-default-browser-check", + "--disable-background-networking", + "--password-store=basic", + "--no-proxy-server", + "--remote-debugging-address=127.0.0.1", + "--remote-debugging-port=0", + ]) + .arg(format!("--user-data-dir={}", profile.path().display())) + .arg(format!("--host-resolver-rules=MAP {host} 127.0.0.1")) + .arg(format!("--ignore-certificate-errors-spki-list={spki}")) + .arg("about:blank") + .env_remove("HTTPS_PROXY") + .env_remove("https_proxy") + .env_remove("HTTP_PROXY") + .env_remove("http_proxy") + .env_remove("ALL_PROXY") + .env_remove("all_proxy") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .unwrap_or_else(|e| panic!("cannot launch Chromium at {}: {e}", bin.display())); + let port_file = profile.path().join("DevToolsActivePort"); + let deadline = Instant::now() + Duration::from_secs(30); + let ws = loop { + if let Ok(text) = std::fs::read_to_string(&port_file) { + let mut lines = text.lines(); + if let (Some(port), Some(path)) = (lines.next(), lines.next()) { + break format!("ws://127.0.0.1:{port}{path}"); + } + } + if let Ok(Some(status)) = child.try_wait() { + panic!("Chromium exited {status} before DevTools opened"); + } + assert!(Instant::now() < deadline, "Chromium never opened DevTools"); + std::thread::sleep(Duration::from_millis(50)); + }; + Chromium { + child, + ws, + _profile: profile, + } +} + +async fn serve_page(host: &str) -> (u16, String) { + let ck = rcgen::generate_simple_self_signed(vec![host.to_string()]).unwrap(); + let spki = Base64::encode_string(&Sha256::digest(ck.key_pair.public_key_der())); + let cert = ck.cert.der().clone(); + let key = rustls_pki_types::PrivateKeyDer::Pkcs8(ck.key_pair.serialize_der().into()); + let tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::aws_lc_rs::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![cert], key) + .unwrap(); + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls)); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + loop { + let Ok((tcp, _)) = listener.accept().await else { + return; + }; + let acceptor = acceptor.clone(); + tokio::spawn(async move { + let Ok(mut s) = acceptor.accept(tcp).await else { + return; + }; + let mut buf = Vec::new(); + let mut chunk = [0u8; 2048]; + while !buf.windows(4).any(|w| w == b"\r\n\r\n") { + match s.read(&mut chunk).await { + Ok(0) | Err(_) => return, + Ok(n) => buf.extend_from_slice(&chunk[..n]), + } + } + let reply = format!( + "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{PAGE}", + PAGE.len() + ); + let _ = s.write_all(reply.as_bytes()).await; + }); + } + }); + (port, spki) +} + +fn no_canary(text: &str) { + assert!(!text.contains(PATH_CANARY), "path canary leaked: {text}"); + assert!(!text.contains(QUERY_CANARY), "query canary leaked: {text}"); + assert!( + !text.contains(FRAG_CANARY), + "fragment canary leaked: {text}" + ); +} + +async fn page_targets(ws: &str) -> usize { + let endpoint = CdpEndpoint::validate(ws, Tunnel::Direct, None).unwrap(); + let client = CdpClient::connect(&endpoint).await.unwrap(); + let listed = client + .request("Target.getTargets", json!({})) + .await + .unwrap(); + listed["targetInfos"] + .as_array() + .unwrap() + .iter() + .filter(|t| t["type"] == "page") + .count() +} + +async fn wait_for_form(ws: &str, target: &str) { + let endpoint = CdpEndpoint::validate(ws, Tunnel::Direct, None).unwrap(); + let client = CdpClient::connect(&endpoint).await.unwrap(); + let session = client.attach(target).await.unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let ready = session + .request( + "Runtime.evaluate", + json!({ + "expression": "!!document.getElementById('username')", + "returnByValue": true, + }), + ) + .await + .unwrap(); + if ready["result"]["value"] == json!(true) { + session.detach().await; + return; + } + assert!(Instant::now() < deadline, "login form did not appear"); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +async fn eval_fields(ws: &str, target: &str) -> (String, String) { + let endpoint = CdpEndpoint::validate(ws, Tunnel::Direct, None).unwrap(); + let client = CdpClient::connect(&endpoint).await.unwrap(); + let session = client.attach(target).await.unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let ready = session + .request( + "Runtime.evaluate", + json!({ + "expression": "!!document.getElementById('username')", + "returnByValue": true, + }), + ) + .await + .unwrap(); + if ready["result"]["value"] == json!(true) { + break; + } + assert!(Instant::now() < deadline, "login form did not appear"); + tokio::time::sleep(Duration::from_millis(50)).await; + } + let got = session + .request( + "Runtime.evaluate", + json!({ + "expression": "JSON.stringify([document.getElementById('username').value, document.getElementById('password').value])", + "returnByValue": true, + }), + ) + .await + .unwrap(); + session.detach().await; + let text = got["result"]["value"].as_str().unwrap(); + let v: Value = serde_json::from_str(text).unwrap(); + ( + v[0].as_str().unwrap().to_owned(), + v[1].as_str().unwrap().to_owned(), + ) +} + +fn broker_for( + ws: &str, + uris: Vec, + item_id: &str, +) -> ( + Arc>>, + String, + RecordingAudit, +) { + let (session, vault) = fixture(); + let item = vault.get(item_id).unwrap().with_uris(uris); + let vault = Vault::with_report(vec![item], SyncReport::default()); + let (alpha, hash) = generate_with(&cheap_argon(), "alpha"); + let tokens = TokenStore::with_floor([("alpha", hash.as_str())], &CHEAP_FLOOR).unwrap(); + let endpoint = CdpEndpoint::validate(ws, Tunnel::Direct, None).unwrap(); + let backend = kharond::api::ConnectingCdpBackend::new([("alpha", endpoint)]); + let clock = Arc::new(kharond::lock::ManualClock::new()); + let mut lock = LockController::new( + LockPolicy::default(), + clock, + Box::new(StaticHardening::all_ok()), + ); + lock.unlock(|| Ok::<_, ()>(TestSession(Arc::new(vault), session.clone()))) + .unwrap(); + let audit = RecordingAudit::default(); + let broker = Broker::new( + tokens, + lock, + Box::new(audit.clone()), + OriginConfig::default(), + ) + .with_fill_policy(FillPolicy { + deadline: Duration::from_secs(45), + allow_default_context: false, + cross_origin_iframe_hosts: Vec::new(), + }) + .with_fill_backend(Box::new(backend)); + (Arc::new(broker), alpha.expose_secret().clone(), audit) +} + +#[tokio::test] +async fn req_api_012_open_then_fill_on_real_chromium() { + let Some(bin) = chromium_or_skip("req_api_012_open_then_fill_on_real_chromium") else { + return; + }; + let host = "app.example.com"; + let (port, spki) = serve_page(host).await; + let chromium = launch_chromium(&bin, host, &spki); + let saved = format!("https://{host}:{port}/{PATH_CANARY}?q={QUERY_CANARY}#{FRAG_CANARY}"); + let (broker, alpha, audit) = broker_for( + &chromium.ws, + vec![ItemUri { + uri: saved, + match_type: None, + }], + ITEM_B, + ); + let addr = serve_http(broker.clone()).await; + let body = format!(r#"{{"item_id":"{ITEM_B}"}}"#); + let opened = post_json(addr, "/v1/open", Some(&alpha), &body).await; + assert_eq!(opened.status, 200, "{}", opened.body); + no_canary(&opened.body); + let opened = opened.json(); + let target = opened["target_id"].as_str().unwrap().to_owned(); + let origin = opened["origin"].as_str().unwrap().to_owned(); + assert_eq!(origin, format!("https://{host}:{port}")); + assert!(!origin.contains(PATH_CANARY)); + let audit_text = serde_json::to_string(&*audit.entries.lock().unwrap()).unwrap(); + no_canary(&audit_text); + + let (session, base) = fixture(); + let username = base.get(ITEM_B).unwrap().username().unwrap().to_owned(); + let password = session + .decrypt_secret(base, ITEM_B, SecretField::Password) + .unwrap(); + let password = String::from_utf8(password.to_vec()).unwrap(); + + wait_for_form(&chromium.ws, &target).await; + let fill = json!({ + "item_id": ITEM_B, + "target": {"cdp_target_id": target, "expected_origin": origin}, + "fields": [{"kind": "username"}, {"kind": "password"}], + }); + let first = post_json(addr, "/v1/fill", Some(&alpha), &fill.to_string()).await; + assert_eq!(first.status, 200, "{}", first.body); + assert_eq!(first.json()["status"], "pending_approval", "{}", first.body); + let request_id = first.json()["grant_request_id"] + .as_str() + .unwrap() + .to_owned(); + broker + .approve_grant_request( + &request_id, + &GrantTerms { + scope: GrantScope::Item(ITEM_B.to_owned()), + kind: GrantKind::PerOrigin, + ttl: Some(Duration::from_secs(3600)), + max_uses: Some(2), + }, + Channel::Cli, + ) + .unwrap(); + let second = post_json(addr, "/v1/fill", Some(&alpha), &fill.to_string()).await; + assert_eq!(second.status, 200, "{}", second.body); + assert_eq!(second.json()["status"], "filled", "{}", second.body); + no_canary(&second.body); + + let (got_user, got_pass) = eval_fields(&chromium.ws, &target).await; + assert!( + got_user == username && got_pass == password, + "the opened tab was not filled" + ); +} + +#[tokio::test] +async fn req_api_012_no_login_url_does_not_navigate_on_real_chromium() { + let Some(bin) = chromium_or_skip("req_api_012_no_login_url_does_not_navigate_on_real_chromium") + else { + return; + }; + let host = "login.example.com"; + let (port, spki) = serve_page(host).await; + let _ = port; + let chromium = launch_chromium(&bin, host, &spki); + let before = page_targets(&chromium.ws).await; + let (broker, alpha, audit) = broker_for( + &chromium.ws, + vec![ + ItemUri { + uri: format!("{host}/{PATH_CANARY}?q={QUERY_CANARY}"), + match_type: None, + }, + ItemUri { + uri: format!("https://{host}/{PATH_CANARY}?q={QUERY_CANARY}#{FRAG_CANARY}"), + match_type: Some(4), + }, + ], + ITEM_A, + ); + let addr = serve_http(broker).await; + let body = format!(r#"{{"item_id":"{ITEM_A}"}}"#); + let refused = mcp_call(addr, Some(&alpha), "kharon_open", &body).await; + assert_eq!(refused.status, 200, "{}", refused.body); + let v = refused.json(); + assert_eq!(v["result"]["isError"], true, "{v}"); + let text = v["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("\"error\":\"no_login_url\""), "{text}"); + no_canary(text); + no_canary(&refused.body); + let audit_text = serde_json::to_string(&*audit.entries.lock().unwrap()).unwrap(); + no_canary(&audit_text); + assert!( + !audit_text.contains("open_dispatch"), + "a refusal must not reach the browser: {audit_text}" + ); + let after = page_targets(&chromium.ws).await; + assert_eq!(before, after, "no_login_url created a tab"); +} diff --git a/crates/kharond/tests/req_api_200_allowlist.rs b/crates/kharond/tests/req_api_200_allowlist.rs index dc17bc1..a410f0b 100644 --- a/crates/kharond/tests/req_api_200_allowlist.rs +++ b/crates/kharond/tests/req_api_200_allowlist.rs @@ -35,7 +35,7 @@ async fn allow_list_filters_tools_list_and_refuses_calls() { // Beta (unrestricted) sees the full registry. let r = mcp_request(addr, Some(&h.beta), "tools/list", "{}").await; - assert_eq!(tool_names(&r.json()).len(), 7); + assert_eq!(tool_names(&r.json()).len(), 8); // Alpha calling outside its list: a tool error, 403 shape. let r = mcp_call(addr, Some(&h.alpha), "kharon_list", "{}").await; @@ -96,11 +96,13 @@ async fn allow_list_refuses_every_other_tool_on_both_transports() { r#"{{"item_id":"{ITEM_A}","target":{{"cdp_target_id":"tab-1","expected_origin":"https://login.example.com"}}}}"# ); - // /mcp: each of the five remaining tools, with valid arguments + let open = format!(r#"{{"item_id":"{ITEM_A}"}}"#); + // /mcp: each of the remaining tools, with valid arguments // (argument parsing precedes the broker, so only a valid call // reaches the allow-list check). for (tool, args) in [ ("kharon_search", r#"{"q":"example"}"#), + ("kharon_open", open.as_str()), ("kharon_fill", &fill), ("kharon_fill_totp", &totp), ("kharon_context", "{}"), @@ -114,6 +116,7 @@ async fn allow_list_refuses_every_other_tool_on_both_transports() { // /v1 alike (REQ-API-011's AC): the same restricted token is // refused 403 with the allow-list detail on every other route. for (path, body) in [ + ("/v1/open", open.as_str()), ("/v1/fill", fill.as_str()), ("/v1/fill_totp", totp.as_str()), ("/v1/context", "{}"), diff --git a/crates/kharond/tests/req_apr_grants.rs b/crates/kharond/tests/req_apr_grants.rs index 344f735..1a7d565 100644 --- a/crates/kharond/tests/req_apr_grants.rs +++ b/crates/kharond/tests/req_apr_grants.rs @@ -802,7 +802,7 @@ async fn req_apr_request_grant_transports_agree() { // Seven tools now (REQ-API-001's count with #20's tool). let list = api_support::mcp_request(addr, Some(&h.alpha), "tools/list", "{}").await; let tools = list.json()["result"]["tools"].as_array().unwrap().clone(); - assert_eq!(tools.len(), 7); + assert_eq!(tools.len(), 8); assert!(tools.iter().any(|t| t["name"] == "kharon_request_grant")); } diff --git a/crates/kharond/tests/req_goal_001_surface.rs b/crates/kharond/tests/req_goal_001_surface.rs index 31ecfad..bb9278f 100644 --- a/crates/kharond/tests/req_goal_001_surface.rs +++ b/crates/kharond/tests/req_goal_001_surface.rs @@ -101,6 +101,11 @@ const REVIEWED_STRINGS: &[(&str, &str)] = &[ "a CDP id the broker created", ), ("ContextResult.detail", "fixed detail-code literal"), + ("OpenResult.target_id", "a CDP target id the broker created"), + ( + "OpenResult.origin", + "live origin: scheme, host and port only", + ), ("ErrorBody.error", "fixed ErrorCode literal"), ("ErrorBody.detail", "fixed Detail literal"), ]; diff --git a/crates/kharond/tests/req_mem_004_idle_activity.rs b/crates/kharond/tests/req_mem_004_idle_activity.rs index 121a13f..b2aeedf 100644 --- a/crates/kharond/tests/req_mem_004_idle_activity.rs +++ b/crates/kharond/tests/req_mem_004_idle_activity.rs @@ -3,8 +3,7 @@ //! //! Activity is an owner unlock, a fill, or the approval that issues //! a grant. Agent calls — status, list, search, `kharon_context`, -//! `kharon_request_grant` — do not move the timer. Tab navigation -//! never reaches the broker, so it has no way to move it either. +//! `kharon_open`, `kharon_request_grant` — do not move the timer. //! A live (unconsumed, unexpired) grant defers the idle lock until //! that grant is consumed or its own TTL elapses. Owner lock and //! panic are not deferred. @@ -122,6 +121,11 @@ impl Rig { .context(&agent, Instant::now()) .await .expect("context"); + // Opening a tab is not idle activity (REQ-API-012). + self.broker + .open(&agent, ITEM_A.to_owned(), Instant::now()) + .await + .expect("open"); let args = GrantRequestArgs { item_id: ITEM_A.to_owned(), target_id: "tab-1".into(), diff --git a/crates/kharond/tests/req_oau_006_007_scopes.rs b/crates/kharond/tests/req_oau_006_007_scopes.rs index eb294ba..bf79705 100644 --- a/crates/kharond/tests/req_oau_006_007_scopes.rs +++ b/crates/kharond/tests/req_oau_006_007_scopes.rs @@ -210,7 +210,7 @@ async fn tools_list_returns_only_the_tokens_scope_tools() { // the full registry. for token in [&full, &h.alpha] { let r = mcp_request(addr, Some(token), "tools/list", "{}").await; - assert_eq!(tool_names(&r.json()).len(), 7, "{}", r.body); + assert_eq!(tool_names(&r.json()).len(), 8, "{}", r.body); } } diff --git a/crates/kharond/tests/req_oau_007_live_session.rs b/crates/kharond/tests/req_oau_007_live_session.rs index d3001f2..61dfbd9 100644 --- a/crates/kharond/tests/req_oau_007_live_session.rs +++ b/crates/kharond/tests/req_oau_007_live_session.rs @@ -296,6 +296,17 @@ async fn fills_ride_the_live_session_and_disconnect_ends_it() { // reached the stub (no configured endpoint is a fallback). assert_eq!(context(&lr).await, Err(ApiError::NO_BROWSER)); assert_eq!(fill(&lr).await, Err(ApiError::NO_BROWSER)); + assert_eq!( + lr.h.broker + .open_from( + &lr.agent, + ITEM_A.to_owned(), + tokio::time::Instant::now(), + None, + ) + .await, + Err(ApiError::NO_BROWSER) + ); let totp = FillRequest { operation: FillOperation::FillTotp, fields: vec![(FieldKind::Totp, None)], @@ -323,6 +334,13 @@ async fn fills_ride_the_live_session_and_disconnect_ends_it() { &mcp_fill_args("totp"), ) .await; + assert_mcp_no_browser( + addr, + &lr.mcp_access, + "kharon_open", + &format!(r#"{{"item_id":"{ITEM_A}"}}"#), + ) + .await; assert!(lr.rig.received.lock().unwrap().is_empty()); let rows = lr.h.broker.connections(); assert_eq!(rows.len(), 1); diff --git a/docs/agent-runtime-setup.md b/docs/agent-runtime-setup.md index d6e892d..780a28b 100644 --- a/docs/agent-runtime-setup.md +++ b/docs/agent-runtime-setup.md @@ -286,6 +286,17 @@ set `hermes_home` or `HERMES_HOME` for the connector process. `kharon_context` returns `ok` with a live session on the owner's Connections page. +### Finding the login page + +Agents call `kharon_open` with the item id. kharon opens that item's +saved login URL in a new tab in the agent's browser and returns the +tab id and the live origin. kharon does not return or log the path, +query or fragment. The opened tab has the full URL, and whether the +model sees it is the harness policy (SPEC OQ-3). `kharon_search` +still returns only the host. On a build that does not have +`kharon_open`, put the login URL in the prompt. A fill after +`kharon_open` still needs the owner's grant. + **Assumption (tab rule, pending #334).** Which tab a fill uses follows the same rule proposed for OpenClaw, as an explicit assumption until #334 decides it on a real profile: the fill @@ -363,6 +374,21 @@ a browser you started on a fixed port. Point `user_data_dir` at that profile if you want discovery there; otherwise it stays outside this install. +## OpenClaw + +OpenClaw's managed-profile install is the connector install on this +page pointed at the profile's loopback CDP port. The full profile +notes are on the roadmap. The login page is the same rule as Hermes. + +Agents call `kharon_open` with the item id. kharon opens that item's +saved login URL in a new tab in the agent's browser and returns the +tab id and the live origin. kharon does not return or log the path, +query or fragment. The opened tab has the full URL, and whether the +model sees it is the harness policy (SPEC OQ-3). `kharon_search` +still returns only the host. On a build that does not have +`kharon_open`, put the login URL in the prompt. A fill after +`kharon_open` still needs the owner's grant. + ## Handing over the secrets The tunnel credential and the agent token are each printed once, on diff --git a/docs/api/mcp-tools.json b/docs/api/mcp-tools.json index f48794b..0eb3675 100644 --- a/docs/api/mcp-tools.json +++ b/docs/api/mcp-tools.json @@ -82,6 +82,32 @@ "name": "kharon_search", "title": "Search items" }, + { + "annotations": { + "destructiveHint": false, + "idempotentHint": false, + "openWorldHint": true, + "readOnlyHint": false + }, + "description": "Open the item's saved login URL in a new tab in your own browser context. Returns only the new tab's target_id and its live origin (scheme, host, port). kharon does not return or log the path, query or fragment. The tab itself has the full URL. Refuses with no_login_url, and does not navigate, when the item has no saved URI that is a full https URL the origin matcher would allow. Does not approve a fill: kharon_fill still needs its grant. Requires unlock. Audited. Same body as POST /v1/open.", + "inputSchema": { + "additionalProperties": false, + "description": "`kharon_open` arguments.", + "properties": { + "item_id": { + "description": "The item whose saved login URL to open.", + "type": "string" + } + }, + "required": [ + "item_id" + ], + "title": "OpenArgs", + "type": "object" + }, + "name": "kharon_open", + "title": "Open an item's login URL" + }, { "annotations": { "destructiveHint": false, diff --git a/docs/api/openapi.json b/docs/api/openapi.json index 8b57cb3..5dee998 100644 --- a/docs/api/openapi.json +++ b/docs/api/openapi.json @@ -187,6 +187,63 @@ } } }, + "/v1/open": { + "post": { + "operationId": "kharon_open", + "summary": "Open the item's saved login URL in a new tab in the caller's browser context (REQ-API-012). Returns only the new tab's target id and its live origin. The path, query and fragment are not returned. Refuses with no_login_url, and does not navigate, when the item has no saved URI that is a full https URL the origin matcher would allow. Does not approve a fill. Requires unlock. Bounded by the fill deadline.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": false, + "required": ["item_id"], + "properties": { + "item_id": { + "type": "string", + "description": "Item id (UUID)." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "The new tab and its live origin", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OpenResult" + } + } + } + }, + "400": { + "$ref": "#/components/responses/Error" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Error" + }, + "404": { + "$ref": "#/components/responses/Error" + }, + "405": { + "$ref": "#/components/responses/Error" + }, + "423": { + "$ref": "#/components/responses/Error" + }, + "500": { + "$ref": "#/components/responses/Error" + } + } + } + }, "/v1/context": { "post": { "operationId": "kharon_context", @@ -862,6 +919,22 @@ } } }, + "OpenResult": { + "type": "object", + "additionalProperties": false, + "required": ["target_id", "origin"], + "description": "REQ-API-012. target_id is the new tab. origin is the tab's live origin (scheme, host, port) and never a path, query or fragment.", + "properties": { + "target_id": { + "type": "string", + "description": "CDP target id of the new tab. It belongs to the calling agent." + }, + "origin": { + "type": "string", + "description": "Live origin, https://host[:port]." + } + } + }, "ContextRequest": { "type": "object", "additionalProperties": false, diff --git a/docs/deployment.md b/docs/deployment.md index f409431..aef9923 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -2221,14 +2221,22 @@ kharond answers a method other than POST with HTTP 405 (`deploy/checks/edge-checks.sh`, and the curl in [Verifying](#verifying)). While the broker is locked, `kharon_status` still answers and reports that. `kharon_list`, -`kharon_search`, `kharon_fill`, `kharon_fill_totp`, `kharon_context` +`kharon_search`, `kharon_open`, `kharon_fill`, `kharon_fill_totp`, +`kharon_context` and `kharon_request_grant` are HTTP 423 `{"error":"locked","detail":"broker is locked; owner unlock required"}`. The server accepts protocol versions `2026-07-28`, `2025-11-25` and `2025-06-18`, and issues no session id. Tool names and JSON Schemas -are [`docs/api/mcp-tools.json`](api/mcp-tools.json) (seven tools: -`kharon_status`, `kharon_list`, `kharon_search`, `kharon_fill`, -`kharon_fill_totp`, `kharon_context`, `kharon_request_grant`). No -tool returns a secret. Apply the +are [`docs/api/mcp-tools.json`](api/mcp-tools.json) (eight tools: +`kharon_status`, `kharon_list`, `kharon_search`, `kharon_open`, +`kharon_fill`, `kharon_fill_totp`, `kharon_context`, +`kharon_request_grant`). No +tool returns a secret. An agent opens a vault item's login page with +`kharon_open`: kharon navigates a new tab in that agent's browser to +the saved URL and returns the tab id and the live origin. kharon does +not return or log the path, query or fragment. The opened tab has the +full URL, and whether the model sees it is the harness policy +(SPEC OQ-3). On a build that does not have `kharon_open`, put the +login URL in the prompt. `kharon_search` returns the host only. Apply the [agent harness policy](#agent-harness-policy-spec-oq-3).