From 661c4405defebfa0297637ca1e6e3c2d76c70159 Mon Sep 17 00:00:00 2001 From: CrysisDeu <32421101+CrysisDeu@users.noreply.github.com> Date: Wed, 23 Sep 2026 01:49:53 +0000 Subject: [PATCH 1/2] fix(connections): name the rejected OAuth endpoint on the mint rejection card The MCP OAuth chat banner names the sanitized endpoint of a URL the credential gate rejects, but the connections mint surface still reported only the opaque code mint_url_rejected and the warm premint gate only a slug. Without the host+path the user cannot know what to write into oauth_endpoints.json, so the failure reads as unfixable. The endpoint is surfaced on a NON-LOG channel. security gains sanitized_oauth_endpoint_display(url): the copy-ready contract layered on the diagnostic (host, path) pair. It returns one "host/path" string only when the pair would also be accepted by the oauth_endpoints.json loader and honoured by the gate -- host matches _OAUTH_EXTENSION_HOST_RE (so localhost, IP literals and a capped host are refused), path passes _valid_oauth_extension_path and is neither the redaction tag nor capped, scheme is https with no explicit port -- and None otherwise. mint.py stores it as MintState["rejected_endpoint"] beside reason == "mint_url_rejected"; pending_mint_for and GET /api/connections/mint carry it to the Connections card, which renders a new mint_failure_url_rejected_endpoint string and falls back to the unnamed message on None. The warning log and the audit line stay slug-only by decision, so the credential-disclosure scanners have no logger sink to flag and no suppression or barrier model is needed. sanitized_oauth_endpoint itself now marks a capped host with the same trailing ellipsis the capped path already carries, so a chopped host can no longer read as a whole hostname. warm._credential_bearing_slugs keeps its release semantics: a refused slug's claim is released, the card asks for a cold mint, and that mint names the endpoint through the surface above. Documented in docs/system-specs/modules/security.md. Tests: the display helper's signature table (nameable / unnameable, one row per rule), the mint view naming and its four unnameable controls, the log-and-audit exclusion, the wire arrival and omission, and the warm hand-off coherence. A capture harness renders the named and fallback card states from the built SPA. Closes #7765 --- docs/system-specs/modules/security.md | 2 +- src/kiro_crew/connections/mint.py | 30 +++- src/kiro_crew/connections/warm.py | 12 +- .../dashboard/handlers/connections.py | 7 + src/kiro_crew/security/__init__.py | 54 +++++- src/kiro_crew/security/_exports.py | 1 + test/test_connections_handoff.py | 57 ++++++ test/test_connections_mint.py | 143 ++++++++++++++- test/test_connections_warm.py | 42 ++++- test/test_security.py | 167 +++++++++++++++++- ...ure-connections-mint-rejected-endpoint.mjs | 128 ++++++++++++++ website/src/api/client.ts | 5 + website/src/i18n/locales/bn.json | 1 + website/src/i18n/locales/de.json | 1 + website/src/i18n/locales/en-XA.json | 1 + website/src/i18n/locales/en.manual.json | 1 + website/src/i18n/locales/es.json | 1 + website/src/i18n/locales/fr.json | 1 + website/src/i18n/locales/hi.json | 1 + website/src/i18n/locales/it.json | 1 + website/src/i18n/locales/ja.json | 1 + website/src/i18n/locales/ko.json | 1 + website/src/i18n/locales/pt.json | 1 + website/src/i18n/locales/ru.json | 1 + website/src/i18n/locales/zh-CN.json | 1 + .../src/pages/connections/ConnectionsPage.tsx | 13 +- 26 files changed, 658 insertions(+), 16 deletions(-) create mode 100644 website/scripts/capture-connections-mint-rejected-endpoint.mjs diff --git a/docs/system-specs/modules/security.md b/docs/system-specs/modules/security.md index baf11fcb4697..0e4af3d6f961 100644 --- a/docs/system-specs/modules/security.md +++ b/docs/system-specs/modules/security.md @@ -573,7 +573,7 @@ contracts and retain their existing lexical descriptor checks. - **Decision-seam consent (keystone leaf `decisions_consent.json`)** — the switch that lets the decision seam send message text and skill descriptions to the external Jev provider (see [decisions.md](decisions.md)) is `~/.kiro/crew/decisions_consent.json`, on `_CREW_SECRET_LEAVES` (agent file tools refuse read and write), `sandbox._CREW_READONLY_LEAVES` (mounted read-only in every mode) and the absent-ceiling pre-create list. Same class and same reasoning as `aws_service_consent.json`: consent to send the operator's data to a paid external service is an authorization, and `config.json` is a `VISIBLE`, hot-applied leaf, so a `decisions.enabled` there would be flippable by a prompt-injected agent shell through any redirect and take effect on the next message. `DecisionsConfig` therefore carries no `enabled` field and the config PATCH refuses the path. Consent is bound to a destination: the keystone records the `provider.endpoint` the config named when the owner consented, and `consent.permits()` sends only while the configured endpoint still equals it — `provider.endpoint` lives in the same agent-writable `config.json`, so a bare yes/no would let the same injected shell redirect consented messages to its own server. Reads fail soft to `{}` → not consented, with a strict `is True` identity test; the only writer is the owner-only, browser-called `PUT /api/decisions/consent` handler, which refuses app tokens and allow-listed non-owner users on the read as well as the write, audits every grant/revocation to SEL, and leaves a corrupt file byte-identical rather than resetting it. - **Browsing has no keystone capability toggle, deliberately (see [browser.md](browser.md)); its executable is a READONLY keystone leaf.** `/playwright-cli` holds the product-managed entrypoint and npm package tree. It is on `_CREW_SECRET_LEAVES` for agent file tools and `_CREW_READONLY_LEAVES` for every OS sandbox: in-sandbox browser commands can read and execute it, while a write that would choose the binary the unsandboxed gateway executes fails at the kernel boundary. The empty directory is absent-equivalent and belongs to `_CREW_PRECREATE_READONLY_DIR_LEAVES`, so the first sandbox cannot win an absent-target race before the first install. It is also the sole `_CREW_NOFOLLOW_READONLY_DIR_LEAVES` member: a resolving symlink, or one that wins the `mkdir` race, refuses the spawn because the bind mount would seal its target while leaving the executable name replaceable. Gateway resolution checks this absolute leaf first, then fixed system directories whose resolved launcher hierarchy the gateway user cannot write. The in-product installer also creates and no-follow pins the real directory before passing it to npm; links, Windows reparse points and create/open identity races abort before any package write, and the Windows pin blocks rename for the duration of npm. It never resolves from `PATH`, `~/.local/bin`, an active project or the workspace; legacy user-local launchers remain on disk and are ignored. The launcher is identity only for gateway-owned calls on every OS: the managed installer atomically stages the native Node executable as `gateway-node` on POSIX or `node.exe` on Windows, and the gateway runs it with the attributed package's contained `playwright-cli.js`. A fixed-system copy is usable only with a Node and package entry whose complete hierarchies also pass the non-writable-system check. Thus a POSIX `env node` shebang cannot select an agent-writable version-manager binary, and owner URL bytes never cross a Windows command-processor boundary. Binary presence is still NOT an approval signal. Every agent invocation follows the ordinary shell approval ladder, and only an explicit trusted pattern, session trust or auto-approve grant may skip the prompt. Because browsing is a shell command, it is governed on the `commands` plane and an `mcp`-scope deny does not reach it. -- **Operator OAuth consent-endpoint extension (keystone leaf `oauth_endpoints.json`)** — the security module's OAuth banner-safety contract (`security.oauth_url_contains_credential`, and `_exfil_url_warning` under `allow_oauth_entropy=True`) exempts standard front-channel params (`state`, PKCE, …) from the base64-blob/query-length heuristics only at an exact-match `(host, path)` in the code-owned `_OAUTH_AUTHORIZATION_ENDPOINTS`. `~/.kiro/crew/oauth_endpoints.json` (`{"additional_authorization_endpoints": [{"host", "path"}]}`) is the operator's escape hatch for identity providers outside that launch set (Okta orgs, Auth0, self-hosted OIDC, tenant-scoped Entra paths): `security._load_operator_oauth_endpoints()` unions strictly validated entries with the builtin set at check time (`_approved_oauth_authorization_endpoint`, memoized on the file's stat so a hand-edit takes effect on the next check without a restart). **Enforcement point:** the dashboard's live MCP OAuth banner validates URLs with this same gate — `_emit_mcp_oauth_request` in `chat_runner.py` calls `security.oauth_url_contains_credential` directly — so an operator endpoint entry governs the banner path as well as every other consumer wired to the contract gate. Each entry widens a trust boundary, so the file is on `_CREW_SECRET_LEAVES` (full read+write keystone block on both the tool path and every shell form) — an agent must not be able to author its own exemption — and there is deliberately no dashboard writer; the operator hand-edits it out-of-band. Every read fails soft to the EMPTY set (missing/unreadable/corrupt/non-object file, mirroring `computer_use.enable_state.load_state`), invalid entries are skipped individually with a warning (no wildcards, schemes, ports, userinfo, percent-escapes, IP literals, `..`, whitespace, or backslashes; hosts are lowercase-normalized DNS names with a letter TLD, paths exact and case-sensitive), and the entry list is truncated at 50 before validation so a mangled file cannot amplify. HTTPS-only / no-explicit-port / exact-match stay enforced by the gate logic and are NOT relaxable via the file, and the exemption grants exactly what the builtin set grants — fixed-credential patterns, heavy percent-encoding, userinfo, fragments, backslashes, and unknown-param heuristics remain unconditional. The markerless bare-secret entropy heuristic follows the same exact endpoint/parameter scope instead of scanning entropy-bearing recognized parameter values first; parameter names, unknown parameters, and non-query components remain in its scan target. That exemption is additionally bounded to the shapes the protocol itself can emit (`_oauth_entropy_value_is_protocol_shaped`, judged on EVERY decoded form: it percent-decodes until the text stops changing, bounded by `_MAX_URL_DECODE_PASSES`, and refuses a value still decodable at the bound, so `%252F` cannot launder the standard alphabet past a single decode): base64url emits `-`/`_` and never `+`/`/`, and an S256 `code_challenge` is base64url of a 32-byte digest, so it is exactly 43 characters. A base64-standard-alphabet run — the shape of an AWS secret key — therefore cannot ride `state`, `nonce`, or `code_challenge` into the blanked set. The residual is narrower but real: a markerless 40-character credential that happens to be alphanumeric is indistinguishable from ordinary base64url state entropy and is accepted only at this boundary; general output redactors retain the heuristic. An approval that came from an operator entry (not the builtin set) emits a best-effort `oauth_endpoint_extension_used` SEL event, deduped per process per endpoint. **Rejections name the endpoint, never the values:** `security.sanitized_oauth_endpoint(url)` returns the lowercase host + path of a rejected authorization URL (query/fragment/port/userinfo are never included; both components are scanned at every percent-decode layer up to the gate's own `_MAX_URL_DECODE_PASSES` budget — a credential-bearing or budget-exhausting path self-redacts to the shared tag, a credential-bearing host makes the helper return `None`, a non-ASCII host is surfaced in IDNA A-label form; both components are length-capped; unparseable URLs return `None`). The banner path (`_emit_mcp_oauth_request`) surfaces that pair in the rejection text — which also spells the `{"additional_authorization_endpoints": [{"host", "path"}]}` entry shape — and inside the `error` meta field the dashboard's failed banner actually renders; no additional meta keys are emitted because no shipped surface reads any. So the user can tell WHICH endpoint tripped the scanner and what to write into `oauth_endpoints.json`, without the rejection ever echoing state/PKCE material (#7578). +- **Operator OAuth consent-endpoint extension (keystone leaf `oauth_endpoints.json`)** — the security module's OAuth banner-safety contract (`security.oauth_url_contains_credential`, and `_exfil_url_warning` under `allow_oauth_entropy=True`) exempts standard front-channel params (`state`, PKCE, …) from the base64-blob/query-length heuristics only at an exact-match `(host, path)` in the code-owned `_OAUTH_AUTHORIZATION_ENDPOINTS`. `~/.kiro/crew/oauth_endpoints.json` (`{"additional_authorization_endpoints": [{"host", "path"}]}`) is the operator's escape hatch for identity providers outside that launch set (Okta orgs, Auth0, self-hosted OIDC, tenant-scoped Entra paths): `security._load_operator_oauth_endpoints()` unions strictly validated entries with the builtin set at check time (`_approved_oauth_authorization_endpoint`, memoized on the file's stat so a hand-edit takes effect on the next check without a restart). **Enforcement point:** the dashboard's live MCP OAuth banner validates URLs with this same gate — `_emit_mcp_oauth_request` in `chat_runner.py` calls `security.oauth_url_contains_credential` directly — so an operator endpoint entry governs the banner path as well as every other consumer wired to the contract gate. Each entry widens a trust boundary, so the file is on `_CREW_SECRET_LEAVES` (full read+write keystone block on both the tool path and every shell form) — an agent must not be able to author its own exemption — and there is deliberately no dashboard writer; the operator hand-edits it out-of-band. Every read fails soft to the EMPTY set (missing/unreadable/corrupt/non-object file, mirroring `computer_use.enable_state.load_state`), invalid entries are skipped individually with a warning (no wildcards, schemes, ports, userinfo, percent-escapes, IP literals, `..`, whitespace, or backslashes; hosts are lowercase-normalized DNS names with a letter TLD, paths exact and case-sensitive), and the entry list is truncated at 50 before validation so a mangled file cannot amplify. HTTPS-only / no-explicit-port / exact-match stay enforced by the gate logic and are NOT relaxable via the file, and the exemption grants exactly what the builtin set grants — fixed-credential patterns, heavy percent-encoding, userinfo, fragments, backslashes, and unknown-param heuristics remain unconditional. The markerless bare-secret entropy heuristic follows the same exact endpoint/parameter scope instead of scanning entropy-bearing recognized parameter values first; parameter names, unknown parameters, and non-query components remain in its scan target. That exemption is additionally bounded to the shapes the protocol itself can emit (`_oauth_entropy_value_is_protocol_shaped`, judged on EVERY decoded form: it percent-decodes until the text stops changing, bounded by `_MAX_URL_DECODE_PASSES`, and refuses a value still decodable at the bound, so `%252F` cannot launder the standard alphabet past a single decode): base64url emits `-`/`_` and never `+`/`/`, and an S256 `code_challenge` is base64url of a 32-byte digest, so it is exactly 43 characters. A base64-standard-alphabet run — the shape of an AWS secret key — therefore cannot ride `state`, `nonce`, or `code_challenge` into the blanked set. The residual is narrower but real: a markerless 40-character credential that happens to be alphanumeric is indistinguishable from ordinary base64url state entropy and is accepted only at this boundary; general output redactors retain the heuristic. An approval that came from an operator entry (not the builtin set) emits a best-effort `oauth_endpoint_extension_used` SEL event, deduped per process per endpoint. **Rejections name the endpoint, never the values:** `security.sanitized_oauth_endpoint(url)` returns the lowercase host + path of a rejected authorization URL (query/fragment/port/userinfo are never included; both components are scanned at every percent-decode layer up to the gate's own `_MAX_URL_DECODE_PASSES` budget — a credential-bearing or budget-exhausting path self-redacts to the shared tag, a credential-bearing host makes the helper return `None`, a non-ASCII host is surfaced in IDNA A-label form; both components are length-capped and a capped component ends in `…`; unparseable URLs return `None`). The banner path (`_emit_mcp_oauth_request`) surfaces that pair in the rejection text — which also spells the `{"additional_authorization_endpoints": [{"host", "path"}]}` entry shape — and inside the `error` meta field the dashboard's failed banner actually renders; no additional meta keys are emitted because no shipped surface reads any. So the user can tell WHICH endpoint tripped the scanner and what to write into `oauth_endpoints.json`, without the rejection ever echoing state/PKCE material (#7578). **Connections mint/warm rejection surfaces name the endpoint on the card, never in a log.** The cold mint (`connections/mint.py`, terminal `mint_url_rejected`) calls `security.sanitized_oauth_endpoint_display(url)` — the copy-ready contract layered on the diagnostic pair: it returns one `host/path` string only when the pair would also be ACCEPTED by the `oauth_endpoints.json` loader and honoured by the gate (host matches `_OAUTH_EXTENSION_HOST_RE`, so `localhost`, IP literals and a `…`-capped host are refused; path passes `_valid_oauth_extension_path` and is neither the redaction tag nor `…`-capped; scheme is `https` with no explicit port), and `None` otherwise — and stores the result as `MintState["rejected_endpoint"]`, which rides `pending_mint_for` and the `GET /api/connections/mint` payload to the Connections card (`mint_failure_url_rejected_endpoint`; the unnamed `mint_failure_url_rejected` copy stays the fallback on `None`). The warning log and the `_log_mint_outcome` audit line stay slug-only by decision: routing URL-derived text through the logger is what the credential-disclosure scanners (Semgrep `python-logger-credential-disclosure`, CodeQL `py/clear-text-logging-sensitive-data`) flag, and a card field is not a logger sink, so no inline suppression or barrier model is needed. The warm premint gate (`warm._credential_bearing_slugs`) does not name the endpoint itself: a refused slug's claim is RELEASED (never a failed row — `test_a_url_carrying_a_credential_is_refused_rather_than_stored`), the card then asks for a cold mint, and that mint re-hits the same URL and names the endpoint through the surface above, so the warm refusal is actionable without a second channel (#7765). **Privacy-safe OAuth rejection diagnostics.** `security.diagnose_oauth_url_credential()` returns `None` for an accepted URL or an `OAuthUrlCredentialDiagnostic` for the first rejecting sub-check. The record carries only a stable `rule`, a URL-component category, an optional code-owned standard query-parameter name, and a shape profile: total length plus counts of ASCII uppercase, ASCII lowercase, digits, percent signs, URL punctuation, and all other characters. `oauth_url_contains_credential()` retains its boolean caller contract and logs that same bounded signature when it rejects. The diagnostic path does not change a rule, add a bypass, retry, or retain a URL. The URL and parameter value are never returned, logged, persisted, hashed, sampled, or represented by a prefix/suffix; malformed, credential-shaped, and unrecognized parameter names are omitted rather than echoed. This is sufficient for a controlled mint loop to distinguish standard OAuth entropy false positives (for example, `credential_scan_bare_secret_raw` on `state` versus `exfil_query_length`) without creating a second credential-bearing sink. An entropy-bearing recognized parameter value at an approved endpoint produces no diagnostic on entropy alone, while the same shape in an unknown parameter retains the stable `credential_scan_bare_secret_raw` rejection signature. diff --git a/src/kiro_crew/connections/mint.py b/src/kiro_crew/connections/mint.py index 91e6bc956369..735503e02bf2 100644 --- a/src/kiro_crew/connections/mint.py +++ b/src/kiro_crew/connections/mint.py @@ -66,7 +66,10 @@ from kiro_crew.loop_lock import LoopBoundLock from kiro_crew.mcp_grant import grant_fingerprint, grant_observed from kiro_crew.mcp_utils import mcp_server_alias -from kiro_crew.security import oauth_url_contains_credential +from kiro_crew.security import ( + oauth_url_contains_credential, + sanitized_oauth_endpoint_display, +) from kiro_crew.sel import sel from kiro_crew.session_pid import register_protected_pid, unregister_protected_pid @@ -103,6 +106,13 @@ class MintState(TypedDict, total=False): state: str # minting | waiting | granted | failed | expired oauth_url: str reason: str + # Copy-ready "host/path" of the authorization URL the credential gate + # refused; set only beside reason == "mint_url_rejected", and only when + # security.sanitized_oauth_endpoint_display could produce a string the + # oauth_endpoints.json loader would accept. It rides the card view and the + # mint-state payload ONLY: the log and audit lines stay slug-only, so no + # URL-derived text reaches a logger sink. + rejected_endpoint: str started: float token: str # row identity; see _new_mint_token client: Any @@ -917,14 +927,26 @@ async def start_oauth_mint( if attempt + 1 < _MINT_URL_REJECTION_ATTEMPTS: continue + # Named on the CARD, never in the log: without the host+path the + # user cannot know what to write into oauth_endpoints.json, so the + # failure reads as unfixable. The display helper owns the + # copy-ready contract (None for a host-borne credential, userinfo, + # a redacted or capped component, a non-https or ported URL, or a + # shape the extension loader would refuse), so the card falls back + # to its unnamed message rather than showing a remedy that cannot + # work. Pure parse-and-match, so no thread hop is needed. + rejected_endpoint = sanitized_oauth_endpoint_display(oauth_url) async with _mints_lock: if _mints.get(slug, {}).get("token") == my_token: - _mints[slug] = { + failed: MintState = { "state": "failed", "reason": "mint_url_rejected", "started": time.monotonic(), "token": my_token, } + if rejected_endpoint is not None: + failed["rejected_endpoint"] = rejected_endpoint + _mints[slug] = failed await asyncio.to_thread(_log_mint_outcome, slug, "error", "reason=mint_url_rejected") return @@ -1139,4 +1161,8 @@ def pending_mint_for(slug: str) -> MintState | None: view["oauth_url"] = entry["oauth_url"] if entry.get("reason"): view["reason"] = entry["reason"] + if entry.get("rejected_endpoint"): + # Rides only beside reason == "mint_url_rejected"; see the field's note + # on MintState for why this channel and not the logger. + view["rejected_endpoint"] = entry["rejected_endpoint"] return view diff --git a/src/kiro_crew/connections/warm.py b/src/kiro_crew/connections/warm.py index 16f3f0e76921..792e470d9664 100644 --- a/src/kiro_crew/connections/warm.py +++ b/src/kiro_crew/connections/warm.py @@ -2540,7 +2540,12 @@ def _credential_bearing_slugs(urls: dict[str, str]) -> set[str]: The gate is :func:`~kiro_crew.security.oauth_url_contains_credential` -- the same predicate the cold mint and the chat consent banner apply -- and it is synchronous because it can consult the operator's on-disk OAuth-endpoint extension, an unbounded - stat on a network mount. Never returns or logs the value it judged. + stat on a network mount. Never returns or logs the value it judged, and it does not + name the endpoint either: a refused slug's claim is RELEASED (see + ``_absorb_warm_requests``), the card then asks for a cold mint, and that mint hits the + same URL and names the endpoint through ``mint.py``'s ``mint_url_rejected`` card view. + The warm surface stays slug-only by design -- a screened premint is not a terminal + failure, and the logger is not a channel for URL-derived text. """ return {slug for slug, url in urls.items() if url and oauth_url_contains_credential(url)} @@ -2579,7 +2584,10 @@ async def _absorb_warm_requests(result: _WarmMintResult, claims: dict[str, str]) url = resolved.get(slug, "") if not url or slug in tainted: # Released either way, not failed: the card asks for a fresh mint rather - # than sitting on a claim nothing will ever fill. + # than sitting on a claim nothing will ever fill. For a tainted slug + # that fresh (cold) mint is also where the user learns WHICH endpoint + # was refused -- mint.py names it on its rejection card -- so the + # release, not a failed row, is what makes the warm refusal actionable. unfulfilled[slug] = token continue entry.update( diff --git a/src/kiro_crew/dashboard/handlers/connections.py b/src/kiro_crew/dashboard/handlers/connections.py index 051520ebb85b..39e8cfcc2801 100644 --- a/src/kiro_crew/dashboard/handlers/connections.py +++ b/src/kiro_crew/dashboard/handlers/connections.py @@ -448,6 +448,13 @@ async def api_connections_mint_state(request: web.Request) -> web.Response: payload["oauth_url"] = view["oauth_url"] if view.get("reason"): payload["reason"] = view["reason"] + if view.get("rejected_endpoint"): + # Rides only beside reason == "mint_url_rejected". Already reduced to a + # copy-ready host+path by security.sanitized_oauth_endpoint_display + # (query, fragment, port and userinfo never reach the view), so it is + # safe to cross the wire; the card renders it in place of the unnamed + # rejection message. + payload["rejected_endpoint"] = view["rejected_endpoint"] return web.json_response(payload) diff --git a/src/kiro_crew/security/__init__.py b/src/kiro_crew/security/__init__.py index b8399ee4508f..3b3d89beeb8a 100644 --- a/src/kiro_crew/security/__init__.py +++ b/src/kiro_crew/security/__init__.py @@ -701,7 +701,8 @@ def sanitized_oauth_endpoint(url: str) -> tuple[str, str] | None: and a credential-bearing HOSTNAME makes the whole helper return ``None`` — a host is an identity, so a redacted host would name nothing; * both components are length-capped, so a pathological URL cannot bloat a - banner or a log line. + banner or a log line; a capped component ends in ``…`` so a reader can + tell a chopped name from a whole one. Returns ``None`` when the URL does not parse to a hostname, so callers fall back to their existing unnamed message. Deliberately independent of WHY the @@ -752,7 +753,10 @@ def sanitized_oauth_endpoint(url: str) -> tuple[str, str] | None: # transformed form and refuse to name it. if _oauth_component_is_unsafe(host): return None - host = host[:_SANITIZED_OAUTH_HOST_MAX_LEN] + if len(host) > _SANITIZED_OAUTH_HOST_MAX_LEN: + # Marked like the path below: a silently chopped host reads as a whole + # hostname that nothing on disk will ever match. + host = host[:_SANITIZED_OAUTH_HOST_MAX_LEN] + "…" path = parsed.path or "/" if _oauth_component_is_unsafe(path): path = _REDACTED_CREDENTIAL_TAG @@ -761,6 +765,52 @@ def sanitized_oauth_endpoint(url: str) -> tuple[str, str] | None: return host, path +def sanitized_oauth_endpoint_display(url: str) -> str | None: + """A rejected endpoint as one copy-ready ``host/path`` string, or ``None``. + + :func:`sanitized_oauth_endpoint` answers a diagnostic ``(host, path)`` pair + and, by contract, may hand back a component that is NOT pasteable: the + shared redaction tag for a credential-bearing path, or a ``…``-capped host + or path. A surface whose whole point is "write THIS into + ``oauth_endpoints.json``" must not join those into text that reads as + actionable and is not. + + So this helper returns a string only when the pair would also be accepted + by the extension file's own loader and honoured by the gate that reads it: + + * the host matches ``_OAUTH_EXTENSION_HOST_RE`` (lowercase DNS name with a + letter TLD — so ``localhost``, IP literals and a capped host are refused); + * the path passes ``_valid_oauth_extension_path`` (leading ``/``, no + ``; ? # % \\ ..`` or whitespace) and is neither redacted nor capped; + * the URL is ``https`` with no explicit port, because the gate grants the + endpoint carve-out only under those two conditions and an entry for an + ``http`` or ``:8443`` endpoint would be refused again after the user + added it. + + Callers fall back to their unnamed message on ``None``. The function is a + pure parse-and-match: it never re-runs the credential verdict and never + touches the operator file, so it is safe to call inline. + """ + endpoint = sanitized_oauth_endpoint(url) + if endpoint is None: + return None + host, path = endpoint + # A capped host needs no check of its own: the host rule below ends in a + # letter TLD, which a trailing "…" can never satisfy. + if path == _REDACTED_CREDENTIAL_TAG or path.endswith("…"): + return None + if not _OAUTH_EXTENSION_HOST_RE.fullmatch(host) or not _valid_oauth_extension_path(path): + return None + try: + parsed = urlparse(url) + port = parsed.port + except ValueError: + return None + if parsed.scheme.lower() != "https" or port is not None: + return None + return f"{host}{path}" + + # ── Binary File MIME Allowlist ── # Files whose UTF-8 decode fails are accepted by file_send / outbox only when # their guessed MIME type is in this allowlist. Deny-by-default; expand only diff --git a/src/kiro_crew/security/_exports.py b/src/kiro_crew/security/_exports.py index a2c19f2c39e1..2793d8e07476 100644 --- a/src/kiro_crew/security/_exports.py +++ b/src/kiro_crew/security/_exports.py @@ -553,6 +553,7 @@ "resource_limit_spec", "sandbox_credential_targets", "sanitized_oauth_endpoint", + "sanitized_oauth_endpoint_display", "scan_exfiltration_urls", "scan_history", "scan_memory", diff --git a/test/test_connections_handoff.py b/test/test_connections_handoff.py index 697378e80fc1..27103dee1534 100644 --- a/test/test_connections_handoff.py +++ b/test/test_connections_handoff.py @@ -716,3 +716,60 @@ async def test_the_premint_then_connect_round_trip_serves_the_warm_url( # payload deliberately does not carry the flag: no card consumes it, and the # authorization verdict is the status feed's job. assert not _mints["notion"].get("shared") + + +# ── part 4: the rejected-endpoint wire contract ── +# +# The mint-state handler re-projects the view through an explicit key allowlist, so a +# field the in-process view carries is invisible to the card unless the handler names +# it. These assert ARRIVAL at the JSON boundary, not storage. + + +@pytest.mark.asyncio +async def test_a_rejected_mint_names_the_endpoint_on_the_wire(): + _row( + state="failed", + url=None, + shared=False, + generation=0, + activation=0, + token="tok-1", + ) + _mints["notion"]["reason"] = "mint_url_rejected" + _mints["notion"]["rejected_endpoint"] = "auth.example.com/authorize" + client = await _client() + try: + body = await (await client.get("/api/connections/mint?slug=notion")).json() + finally: + await client.close() + + assert body["state"] == "failed" + assert body["reason"] == "mint_url_rejected" + assert body["rejected_endpoint"] == "auth.example.com/authorize" + # Host+path only ever crosses the wire: no scheme, no query, no fragment. + assert set(body) == {"slug", "state", "token", "reason", "rejected_endpoint"} + + +@pytest.mark.asyncio +async def test_a_rejection_without_a_named_endpoint_omits_the_field_on_the_wire(): + """Control: when the helper could not name the endpoint the view carries no + rejected_endpoint, so the payload must not invent one -- the card then falls + back to its unnamed message.""" + _row( + state="failed", + url=None, + shared=False, + generation=0, + activation=0, + token="tok-2", + ) + _mints["notion"]["reason"] = "mint_url_rejected" + client = await _client() + try: + body = await (await client.get("/api/connections/mint?slug=notion")).json() + finally: + await client.close() + + assert body["state"] == "failed" + assert body["reason"] == "mint_url_rejected" + assert "rejected_endpoint" not in body diff --git a/test/test_connections_mint.py b/test/test_connections_mint.py index 96e2e00519b2..38f6538430bc 100644 --- a/test/test_connections_mint.py +++ b/test/test_connections_mint.py @@ -1003,13 +1003,154 @@ def __init__(self, **kwargs: Any) -> None: view = mint.pending_mint_for("notion") assert view is not None assert view["token"] == token - assert _state_only(view) == {"state": "failed", "reason": "mint_url_rejected"} + # The card learns WHICH endpoint the gate refused (host+path only), so the + # user knows what to write into oauth_endpoints.json. The credential lived + # in the query, which the display helper never echoes. + assert _state_only(view) == { + "state": "failed", + "reason": "mint_url_rejected", + "rejected_endpoint": "auth.example.com/authorize", + } assert len(_FakeClient.instances) == 2 assert [client.shutdowns for client in _FakeClient.instances] == [1, 1] assert protected_pids == set() assert logged == ["error reason=mint_url_rejected"] assert "AKIAIOSFODNN7EXAMPLE" not in caplog.text assert "AKIAIOSFODNN7EXAMPLE" not in json.dumps(logged) + # The endpoint rides ONLY the card view: neither the warning log nor the + # audit line may carry any URL-derived text, or the credential-disclosure + # scanners would be right to flag them. + assert "auth.example.com" not in caplog.text + assert "auth.example.com" not in json.dumps(logged) + assert tainted not in caplog.text + assert tainted not in json.dumps(view) + + +async def _reject_twice( + monkeypatch: pytest.MonkeyPatch, caplog, tainted: str +) -> tuple[dict | None, list[str]]: + """Drive a mint whose every attempt yields *tainted* to its terminal rejection.""" + + class _Tainted(_FakeClient): + def __init__(self, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.requests = [{"serverName": "notion", "oauthUrl": tainted}] + + attempts = iter([_Tainted, _Tainted]) + monkeypatch.setattr(mint, "_acp_client_factory", lambda: next(attempts)) + logged: list[str] = [] + monkeypatch.setattr( + mint, + "_log_mint_outcome", + lambda slug, outcome, detail: logged.append(f"{outcome} {detail}"), + ) + token, prior = await mint.reserve_mint_row("notion") + with caplog.at_level("WARNING"): + await mint.start_oauth_mint("notion", _URL, token, prior) + return mint.pending_mint_for("notion"), logged + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "tainted", + [ + # The credential IS the host label: a redacted host would name nothing. + "https://AKIAIOSFODNN7EXAMPLE.example.com/authorize?client_id=abc", + # The credential is a PATH segment: the diagnostic pair carries the + # redaction tag, which is not a path a user could type. + "https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize", + # Nameable host+path, but the extension loader would refuse the host, + # so naming it would advertise an entry that gets skipped on load. + "https://localhost/authorize?access_token=AKIAIOSFODNN7EXAMPLE", + # Nameable host+path, but the gate never grants the carve-out to an + # explicit port, so the entry would be refused again after adding it. + "https://auth.example.com:8443/authorize?access_token=AKIAIOSFODNN7EXAMPLE", + ], + ids=["credential-in-host", "credential-in-path", "loader-refuses-host", "explicit-port"], +) +async def test_a_rejection_the_helper_cannot_name_leaves_the_card_unnamed( + monkeypatch: pytest.MonkeyPatch, protected_pids: set[int], caplog, tainted: str +): + """Control for the naming case: when no copy-ready endpoint exists the row + carries NO rejected_endpoint, so the card falls back to its unnamed message + rather than showing a partial host, a redaction tag, or a remedy that + cannot work.""" + view, logged = await _reject_twice(monkeypatch, caplog, tainted) + + assert view is not None + assert _state_only(view) == {"state": "failed", "reason": "mint_url_rejected"} + assert logged == ["error reason=mint_url_rejected"] + assert "AKIAIOSFODNN7EXAMPLE" not in caplog.text + assert "AKIAIOSFODNN7EXAMPLE" not in json.dumps(logged) + assert "AKIAIOSFODNN7EXAMPLE" not in json.dumps(view) + + +@pytest.mark.asyncio +async def test_the_named_endpoint_is_host_and_path_only( + monkeypatch: pytest.MonkeyPatch, protected_pids: set[int], caplog +): + """The card gets the endpoint identity and nothing else from the URL: no + scheme, query, fragment, or the state/PKCE material that lives in them.""" + tainted = ( + "https://IdP.Example.com/realms/dev/authorize" + "?client_id=abc&state=TOPSECRETSTATE&code_challenge=PKCEMATERIAL" + "&access_token=AKIAIOSFODNN7EXAMPLE#frag" + ) + view, logged = await _reject_twice(monkeypatch, caplog, tainted) + + assert view is not None + assert view["rejected_endpoint"] == "idp.example.com/realms/dev/authorize" + serialized = json.dumps(view) + for never in ( + "https://", + "TOPSECRETSTATE", + "PKCEMATERIAL", + "AKIAIOSFODNN7EXAMPLE", + "#frag", + "?", + ): + assert never not in serialized + assert never not in caplog.text + assert never not in json.dumps(logged) + + +@pytest.mark.asyncio +async def test_a_named_endpoint_never_reaches_the_log_or_audit_line( + monkeypatch: pytest.MonkeyPatch, protected_pids: set[int], caplog +): + """The scanner decision: the endpoint is a CARD field, not log text. If a + future edit routes it through the logger, this fails before Semgrep or + CodeQL do.""" + tainted = "https://auth.example.com/authorize?access_token=AKIAIOSFODNN7EXAMPLE" + view, logged = await _reject_twice(monkeypatch, caplog, tainted) + + assert view is not None + assert view["rejected_endpoint"] == "auth.example.com/authorize" + assert caplog.text # the slug-only warning still fires + assert "notion" in caplog.text + assert "auth.example.com" not in caplog.text + assert logged == ["error reason=mint_url_rejected"] + + +def test_a_rejected_endpoint_rides_the_card_view_only_beside_its_reason(): + """``pending_mint_for`` projects the field through the same allowlist as + ``reason``: present when stored, absent when not, never invented.""" + mint._mints["notion"] = {"state": "failed", "reason": "mint_url_rejected", "token": "t1", "started": 0.0, "rejected_endpoint": "idp.example.com/authorize"} # type: ignore[typeddict-item] + assert _state_only(mint.pending_mint_for("notion")) == { + "state": "failed", + "reason": "mint_url_rejected", + "rejected_endpoint": "idp.example.com/authorize", + } + mint._mints["notion"] = { + "state": "failed", + "reason": "mint_url_rejected", + "token": "t2", + "started": 0.0, + } + assert _state_only(mint.pending_mint_for("notion")) == { + "state": "failed", + "reason": "mint_url_rejected", + } @pytest.mark.asyncio diff --git a/test/test_connections_warm.py b/test/test_connections_warm.py index f12bdab9f43c..51f719bbd4b7 100644 --- a/test/test_connections_warm.py +++ b/test/test_connections_warm.py @@ -20,7 +20,7 @@ from conftest import requires_symlinks from kiro_crew import security from kiro_crew.agent_files import AGENT_FILENAME -from kiro_crew.connections import tool_aliases, warm +from kiro_crew.connections import mint, tool_aliases, warm from kiro_crew.connections.mint import _mints from kiro_crew.connections.registry import Provider @@ -1567,6 +1567,46 @@ async def test_a_url_carrying_a_credential_is_refused_rather_than_stored(_stub_a assert "linear" not in _mints, "the claim is released so the card asks for a fresh mint" +@pytest.mark.asyncio +async def test_a_refused_premint_stays_slug_only_and_hands_naming_to_the_cold_mint( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, _stub_activation +): + """The warm gate is one half of a two-step surface. It must NOT name the endpoint + itself -- the warning and the audit line are logger sinks, and URL-derived text there + is what the credential-disclosure scanners flag -- but the URL it refuses must be one + the cold mint CAN name, or releasing the claim would send the card to a fresh mint that + ends just as opaquely. Both halves are pinned here: the release leaves no row (so the + card's poll reads ``idle`` and asks for a cold mint), the warm-side text carries the + slug and nothing from the URL, and the display contract the cold mint applies to the + same URL yields the copy-ready endpoint.""" + url = "https://linear.example/authorize?state=AKIA" + "IOSFODNN7EXAMPLE1" + audited: list[tuple[str, str, str]] = [] + monkeypatch.setattr( + warm, "_log_warm_event", lambda op, res, outcome="ok": audited.append((op, res, outcome)) + ) + provider = _provider("linear") + claims = await _claim("linear") + + with caplog.at_level(logging.WARNING, logger=warm.logger.name): + absorbed = await warm._absorb_warm_requests( + _result([provider], [{"serverName": "linear", "oauthUrl": url}]), claims + ) + + assert absorbed == [] + assert "linear" not in _mints + assert mint.pending_mint_for("linear") is None + # Slug-only on every warm-side channel. + assert audited == [("connections_warm_mint_url", "provider:linear", "refused")] + assert "linear" in caplog.text + for never in ("linear.example", "/authorize", "AKIA", url): + assert never not in caplog.text + assert never not in json.dumps(audited) + # The hand-off is coherent: the cold mint the card now starts re-hits this URL, + # and its card view names exactly this endpoint (host+path, nothing from the query). + assert security.oauth_url_contains_credential(url) + assert security.sanitized_oauth_endpoint_display(url) == "linear.example/authorize" + + @pytest.mark.asyncio async def test_the_screen_is_the_shared_security_gate_not_a_local_copy( monkeypatch: pytest.MonkeyPatch, _stub_activation diff --git a/test/test_security.py b/test/test_security.py index 4c18a4e47d1a..b1d7ffa28555 100644 --- a/test/test_security.py +++ b/test/test_security.py @@ -34,6 +34,7 @@ redact_credentials, redact_exfiltration_urls, sanitized_oauth_endpoint, + sanitized_oauth_endpoint_display, scan_exfiltration_urls, scan_history, should_record_observe_history, @@ -3692,14 +3693,26 @@ def test_overlong_path_is_truncated(self) -> None: assert len(path) == security._SANITIZED_OAUTH_PATH_MAX_LEN + 1 assert path.endswith("…") - def test_overlong_host_is_capped(self) -> None: + def test_overlong_host_is_capped_with_a_marker(self) -> None: # 30-char labels: below the 40-char bare-run floor, so the host is - # benign-long — it caps, not bails. + # benign-long — it caps, not bails, and the cap is VISIBLE: a chopped + # host that reads as a whole hostname names an endpoint that does not + # exist, which is worse than an obviously partial one. long_host = ".".join(["a" * 30] * 9) + ".example" result = sanitized_oauth_endpoint(f"https://{long_host}/authorize") assert result is not None host, _ = result - assert len(host) <= security._SANITIZED_OAUTH_HOST_MAX_LEN + assert len(host) == security._SANITIZED_OAUTH_HOST_MAX_LEN + 1 + assert host.endswith("…") + assert host[:-1] == long_host[: security._SANITIZED_OAUTH_HOST_MAX_LEN] + + def test_a_host_at_the_cap_is_not_marked(self) -> None: + # Exactly the DNS maximum is a legal hostname; only an EXCESS is chopped. + # 30-char labels again: no 40-char run that reads as a bare secret. + at_cap = ".".join(["b" * 30] * 8) + ".abcde" + assert len(at_cap) == security._SANITIZED_OAUTH_HOST_MAX_LEN + result = sanitized_oauth_endpoint(f"https://{at_cap}/authorize") + assert result == (at_cap, "/authorize") @pytest.mark.parametrize( "url", @@ -3715,6 +3728,154 @@ def test_unparseable_urls_return_none(self, url: str) -> None: assert sanitized_oauth_endpoint(url) is None +class TestSanitizedOAuthEndpointDisplay: + """``sanitized_oauth_endpoint_display`` is the COPY-READY contract. + + The diagnostic pair may legitimately carry a component that is not + pasteable (redaction tag, ``…`` cap) or that the ``oauth_endpoints.json`` + loader would refuse (``localhost``, an IP literal, a percent-escape in the + path) or that the gate would never honour (``http``, an explicit port). A + card that says "add THIS to oauth_endpoints.json" must hand back a string + only when adding it would actually work. Every signature the helper judges + is enumerated here with its verdict, so a widened or narrowed rule shows up + as a specific row rather than a vague failure. + """ + + GITHUB_TOKEN = "ghp_" "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef12" + + @pytest.mark.parametrize( + ("url", "expected"), + [ + ( + "https://idp.example.com/authorize?state=x&code_challenge=y", + "idp.example.com/authorize", + ), + ( + "https://idp.example.com/authorize?access_token=AKIAIOSFODNN7EXAMPLE", + "idp.example.com/authorize", + ), + ( + "https://IdP.Example.COM/Realms/Dev/Authorize", + "idp.example.com/Realms/Dev/Authorize", + ), + ("https://idp.example.com", "idp.example.com/"), + ("https://idp.example.com/authorize#fragment-secret", "idp.example.com/authorize"), + ("https://bücher.example/authorize", "xn--bcher-kva.example/authorize"), + ( + "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize", + "login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize", + ), + # urlparse strips ``;params`` from the last segment, and the gate compares + # ``parsed.path`` the same way, so "/authorize" IS the entry that matches. + ("https://idp.example.com/authorize;v=1", "idp.example.com/authorize"), + ], + ids=[ + "plain-endpoint-query-dropped", + "credential-in-query-is-not-echoed", + "host-lowercased-path-case-kept", + "empty-path-becomes-slash", + "fragment-dropped", + "idn-host-in-a-label-form", + "multi-segment-path", + "path-params-dropped-like-the-gate", + ], + ) + def test_nameable_endpoints_come_back_as_host_slash_path(self, url: str, expected: str) -> None: + assert sanitized_oauth_endpoint_display(url) == expected + + @pytest.mark.parametrize( + "url", + [ + # -- the diagnostic pair itself is None -- + "", + "not a url at all", + "https:///path-without-host", + f"https://{GITHUB_TOKEN}@idp.example.com/authorize", + "https://user%3Apass%40idp.example.com/authorize", + "https://AKIAIOSFODNN7EXAMPLE.example.com/authorize", + # -- pair is not pasteable: redaction tag / cap marker -- + "https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize", + "https://idp.example.com" + "/seg-ment" * 40, + "https://" + ".".join(["a" * 30] * 9) + ".example/authorize", + # -- the extension loader would refuse the host -- + "https://localhost/authorize", + "https://10.0.0.1/authorize", + "https://idp.example.com./authorize", + "https://idp/authorize", + # -- the extension loader would refuse the path -- + "https://idp.example.com/auth%20orize", + "https://idp.example.com/../authorize", + "https://idp.example.com/auth\\orize", + # -- the gate would never grant the carve-out -- + "http://idp.example.com/authorize", + "https://idp.example.com:8443/authorize", + "https://idp.example.com:443/authorize", + ], + ids=[ + "empty", + "not-a-url", + "no-host", + "userinfo", + "encoded-userinfo", + "credential-in-host", + "credential-in-path-redacted", + "overlong-path-capped", + "overlong-host-capped", + "localhost-no-letter-tld", + "ipv4-literal", + "trailing-dot-host", + "single-label-host", + "percent-escape-in-path", + "dot-dot-in-path", + "backslash-in-path", + "http-scheme", + "explicit-port", + "explicit-default-port", + ], + ) + def test_unnameable_endpoints_return_none(self, url: str) -> None: + assert sanitized_oauth_endpoint_display(url) is None + + def test_the_display_string_is_exactly_what_the_loader_would_accept(self) -> None: + """Contract closure: split the string back into (host, path) and run it + through the SAME validators the extension loader applies, so the two + can only drift together.""" + display = sanitized_oauth_endpoint_display( + "https://idp.example.com/realms/dev/protocol/openid-connect/auth?state=s" + ) + assert display is not None + host, _, rest = display.partition("/") + path = "/" + rest + assert security._OAUTH_EXTENSION_HOST_RE.fullmatch(host) + assert security._valid_oauth_extension_path(path) + assert security._validate_operator_oauth_entries( + {"additional_authorization_endpoints": [{"host": host, "path": path}]} + ) == frozenset({(host, path)}) + + def test_the_raw_url_and_its_query_never_appear_in_the_display(self) -> None: + url = ( + "https://idp.example.com/authorize" + "?client_id=abc&state=TOPSECRETSTATE&code_challenge=PKCEMATERIAL" + f"&access_token={self.GITHUB_TOKEN}" + ) + display = sanitized_oauth_endpoint_display(url) + assert display == "idp.example.com/authorize" + for secret in ("TOPSECRETSTATE", "PKCEMATERIAL", self.GITHUB_TOKEN, "client_id", "?"): + assert secret not in display + + def test_a_redacted_path_is_refused_rather_than_joined(self) -> None: + # The diagnostic pair is (host, tag): the tag must never be glued onto + # the host as if it were a path a user could type. + pair = sanitized_oauth_endpoint("https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize") + assert pair == ("idp.example.com", security._REDACTED_CREDENTIAL_TAG) + assert ( + sanitized_oauth_endpoint_display( + "https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize" + ) + is None + ) + + class TestOperatorOAuthEndpointExtension: """The keystone ``oauth_endpoints.json`` extends the OAuth endpoint set. diff --git a/website/scripts/capture-connections-mint-rejected-endpoint.mjs b/website/scripts/capture-connections-mint-rejected-endpoint.mjs new file mode 100644 index 000000000000..a8e6915260f6 --- /dev/null +++ b/website/scripts/capture-connections-mint-rejected-endpoint.mjs @@ -0,0 +1,128 @@ +/** + * Screenshot harness for the Connections card's rejected-URL failure copy. + * + * Runs the REAL built SPA (website/dist) behind the shared in-process static + * server, with every /api/** call answered from fixtures via Playwright route + * interception -- gateway-free, no kiro-cli, no MCP child, no consent flow. + * + * The scene is the Notion card walked through one real connect whose mint ends + * in `failed` / `mint_url_rejected`. Two frames, each from a fresh page: + * + * 1. `rejected_endpoint` present -- the card names the endpoint the gate + * refused and points at oauth_endpoints.json; + * 2. `rejected_endpoint` absent -- the card keeps its unnamed message. + * + * Before each shot the harness asserts the copy it expects is on screen, that + * no first-run dialog covers the card, and that nothing from the rejected URL + * beyond host+path (scheme, query, token) ever reached the page text. + * + * Usage: node scripts/capture-connections-mint-rejected-endpoint.mjs [outDir] + */ +import { chromium } from 'playwright' +import { mkdirSync } from 'node:fs' +import { serveDist } from './lib/serve-dist.mjs' +import { json, logPageProblems, stubDashboardApi } from './lib/stub-dashboard-api.mjs' + +const OUT = process.argv[2] || '../temp-screenshots/connections-mint-rejected-endpoint' +const SLUG = 'notion' +const ENDPOINT = 'auth.example-idp.com/realms/dev/authorize' +/** Strings from the rejected URL that must NEVER appear on the card. */ +const NEVER_ON_SCREEN = ['https://', 'access_token', 'AKIAIOSFODNN7EXAMPLE', 'code_challenge', '?'] + +mkdirSync(OUT, { recursive: true }) + +const entry = () => ({ + name: SLUG, + command: '', + url: 'https://mcp.notion.com/mcp', + status: 'error', + error: 'authorization required', + tools: [], + source: 'kirocrew', + enabled: true, + kirocrewManaged: true, +}) + +async function frame(browser, base, { name, endpoint, expectText, forbidText }) { + const context = await browser.newContext({ viewport: { width: 1400, height: 880 }, deviceScaleFactor: 1 }) + const page = await context.newPage() + logPageProblems(page) + + const scene = { installed: false, mint: { slug: SLUG, state: 'idle' } } + await stubDashboardApi(page, { + slots: [], + extra: async (path, route) => { + if (path === '/api/config/kirocrew') return json(route, { connections_ui: true }), true + if (path === '/api/mcp' || path === '/api/mcp/probe') { + return json(route, scene.installed ? [entry()] : []), true + } + if (path === '/api/mcp/custom') { + scene.installed = true + return json(route, { ok: true, added: [SLUG], enabled: true }), true + } + if (path === '/api/connections/mint') { + if (route.request().method() === 'POST') { + scene.mint = { slug: SLUG, state: 'minting' } + return json(route, { ok: true, slug: SLUG, state: 'minting' }), true + } + return json(route, scene.mint), true + } + if (path.startsWith('/api/chat/slots/')) { + return json(route, { running: false, has_more: false, total: 0, queue: [], messages: [] }), true + } + return false + }, + }) + + const card = page.locator(`#connection-${SLUG}`) + await page.goto(base + '/capabilities?tab=mcp', { waitUntil: 'domcontentloaded' }) + await page.locator(`#connection-${SLUG}[data-state="not-connected"]`).waitFor({ state: 'visible', timeout: 20000 }) + const connect = card.getByRole('button', { name: 'Connect', exact: true }) + await connect.waitFor({ state: 'visible', timeout: 20000 }) + await connect.click() + await page.locator(`#connection-${SLUG}[data-state="waiting-for-approval"]`).waitFor({ state: 'visible', timeout: 20000 }) + + // The terminal verdict: the gate refused the URL twice, so the row failed. + scene.mint = { + slug: SLUG, + state: 'failed', + reason: 'mint_url_rejected', + ...(endpoint ? { rejected_endpoint: endpoint } : {}), + } + await card.getByText(expectText, { exact: false }).first().waitFor({ state: 'visible', timeout: 20000 }) + + if (await page.getByRole('dialog').count()) throw new Error(`${name}: a dialog covers the card`) + const text = await card.innerText() + for (const never of [...NEVER_ON_SCREEN, ...forbidText]) { + if (text.includes(never)) throw new Error(`${name}: card text carries ${JSON.stringify(never)}`) + } + if (!text.includes(expectText)) throw new Error(`${name}: card text lacks ${JSON.stringify(expectText)}`) + await page.waitForTimeout(400) + await card.screenshot({ path: `${OUT}/${name}.png` }) + console.log('wrote', `${OUT}/${name}.png`) + await context.close() +} + +async function main() { + const { srv, base } = await serveDist() + const browser = await chromium.launch() + try { + await frame(browser, base, { + name: '1-card-rejected-endpoint-named', + endpoint: ENDPOINT, + expectText: `The authorization endpoint ${ENDPOINT} looked like it carried a credential`, + forbidText: ['so it was not displayed'], + }) + await frame(browser, base, { + name: '2-card-rejected-endpoint-unnamed-fallback', + endpoint: undefined, + expectText: 'containing credential-like data, so it was not displayed', + forbidText: [ENDPOINT, 'oauth_endpoints.json'], + }) + } finally { + await browser.close() + srv.close() + } +} + +main().catch(err => { console.error(err); process.exit(1) }) diff --git a/website/src/api/client.ts b/website/src/api/client.ts index 2357821456da..6b26c96488b5 100644 --- a/website/src/api/client.ts +++ b/website/src/api/client.ts @@ -248,6 +248,11 @@ export interface ConnectionMintState { state: 'idle' | 'minting' | 'waiting' | 'granted' | 'failed' | 'expired' oauth_url?: string reason?: string + /** Copy-ready "host/path" of the authorization URL the credential gate + * refused. Present only beside reason === 'mint_url_rejected', and only when + * the backend could reduce the URL to a string the oauth_endpoints.json + * loader would accept (query, fragment, port and userinfo are never sent). */ + rejected_endpoint?: string /** Opaque id of the backend row, unique across gateway restarts as well as * within one process. Reported so a row can be told apart from its * successor for the same provider. */ diff --git a/website/src/i18n/locales/bn.json b/website/src/i18n/locales/bn.json index d70c2c62b05c..dcbf2699e7c3 100644 --- a/website/src/i18n/locales/bn.json +++ b/website/src/i18n/locales/bn.json @@ -10900,6 +10900,7 @@ "mint_failure_timed_out": "অনুমোদনের ঠিকানা প্রস্তুত হওয়ার আগেই অনুমোদন সেটআপের সময় শেষ হয়েছে। আবার সংযোগ করার চেষ্টা করুন।", "mint_failure_unknown": "অনুমোদনের ঠিকানা প্রস্তুত হওয়ার আগেই অনুমোদন সেটআপ ব্যর্থ হয়েছে। আবার সংযোগ করার চেষ্টা করুন।", "mint_failure_url_rejected": "প্রদানকারী এমন একটি অনুমোদনের ঠিকানা ফিরিয়েছে যাতে শংসাপত্রের মতো ডেটা ছিল, তাই সেটি দেখানো হয়নি।", + "mint_failure_url_rejected_endpoint": "অনুমোদন এন্ডপয়েন্ট {{endpoint}} দেখে মনে হয়েছে এতে শংসাপত্র রয়েছে, তাই এটি প্রত্যাখ্যান করা হয়েছে। এটি যদি এমন একটি বিশ্বস্ত পরিচয় প্রদানকারী হয় যা {{productName}} চেনে না, তবে {{productName}} ডেটা হোমে থাকা oauth_endpoints.json-এ {{endpoint}} যোগ করো (কী লিখতে হবে তা docs/guides/connecting-remote-oauth-mcp-server.md-এ দেখো)। না হলে সার্ভার মালিককে URL ঠিক করতে বলো।", "needs_attention": "মনোযোগ প্রয়োজন", "no_matching_services": "এই অনুসন্ধানের সাথে কোনো পরিষেবা মেলেনি।", "not_connected": "সংযুক্ত নয়", diff --git a/website/src/i18n/locales/de.json b/website/src/i18n/locales/de.json index ed15d1750fe9..6e5cd4771b24 100644 --- a/website/src/i18n/locales/de.json +++ b/website/src/i18n/locales/de.json @@ -10900,6 +10900,7 @@ "mint_failure_timed_out": "Beim Einrichten der Autorisierung wurde das Zeitlimit erreicht, bevor die Freigabeadresse bereit war. Versuche erneut, eine Verbindung herzustellen.", "mint_failure_unknown": "Die Autorisierung konnte nicht eingerichtet werden, bevor die Freigabeadresse bereit war. Versuche erneut, eine Verbindung herzustellen.", "mint_failure_url_rejected": "Der Anbieter hat eine Freigabeadresse mit Daten zurückgegeben, die wie Zugangsdaten aussehen. Daher wurde sie nicht angezeigt.", + "mint_failure_url_rejected_endpoint": "Der Autorisierungsendpunkt {{endpoint}} sah aus, als enthielte er Zugangsdaten, und wurde daher abgelehnt. Wenn es sich um einen vertrauenswürdigen Identitätsanbieter handelt, den {{productName}} nicht kennt, trage {{endpoint}} in die Datei oauth_endpoints.json im {{productName}}-Datenverzeichnis ein (den Eintrag zeigt docs/guides/connecting-remote-oauth-mcp-server.md). Andernfalls bitte den Serverbetreiber, die URL zu korrigieren.", "needs_attention": "Aktion erforderlich", "no_matching_services": "Keine Dienste entsprechen dieser Suche.", "not_connected": "Nicht verbunden", diff --git a/website/src/i18n/locales/en-XA.json b/website/src/i18n/locales/en-XA.json index 2ec9794ecdc6..ca22e80cd796 100644 --- a/website/src/i18n/locales/en-XA.json +++ b/website/src/i18n/locales/en-XA.json @@ -15439,6 +15439,7 @@ "mint_failure_timed_out": "[Àùţĥøŕìžàţìøñ şèţùþ ţìɱèð øùţ ƀèƒøŕè àñ àþþŕøṽàĺ àððŕèşş ẁàş ŕèàðý. Ţŕý çøññèçţìñğ àğàìñ. ···························]", "mint_failure_unknown": "[Àùţĥøŕìžàţìøñ şèţùþ ƒàìĺèð ƀèƒøŕè àñ àþþŕøṽàĺ àððŕèşş ẁàş ŕèàðý. Ţŕý çøññèçţìñğ àğàìñ. ··························]", "mint_failure_url_rejected": "[Ţĥè þŕøṽìðèŕ ŕèţùŕñèð àñ àþþŕøṽàĺ àððŕèşş çøñţàìñìñğ çŕèðèñţìàĺ-ĺìķè ðàţà, şø ìţ ẁàş ñøţ ðìşþĺàýèð. ······························]", + "mint_failure_url_rejected_endpoint": "[Ţĥè àùţĥøŕìžàţìøñ èñðþøìñţ {{endpoint}} ĺøøķèð ĺìķè ìţ çàŕŕìèð à çŕèðèñţìàĺ, şø ìţ ẁàş ŕèĵèçţèð. ̃ ìţ ìş à ţŕùşţèð ìðèñţìţý þŕøṽìðèŕ ţĥàţ {{productName}} ðøèş ñøţ ŕèçøğñìžè, àðð {{endpoint}} ţø øàùţĥ_èñðþøìñţş.ĵşøñ ìñ ţĥè {{productName}} ðàţà ĥøɱè (ðøçş/ğùìðèş/çøññèçţìñğ-ŕèɱøţè-øàùţĥ-ɱçþ-şèŕṽèŕ.ɱð şĥøẁş ţĥè èñţŕý ţø ẁŕìţè). Øţĥèŕẁìşè àşķ ţĥè şèŕṽèŕ øẁñèŕ ţø ƒìẋ ţĥè ÙŔĹ. ································································································]", "needs_attention": "[Ñèèðş àţţèñţìøñ ··············]", "no_matching_services": "[Ñø şèŕṽìçèş ɱàţçĥ ţĥìş şèàŕçĥ. ·····················]", "not_connected": "[Ñøţ çøññèçţèð ············]", diff --git a/website/src/i18n/locales/en.manual.json b/website/src/i18n/locales/en.manual.json index 6d53b8652c67..449bb7e3d86c 100644 --- a/website/src/i18n/locales/en.manual.json +++ b/website/src/i18n/locales/en.manual.json @@ -4622,6 +4622,7 @@ "mint_failure_timed_out": "Authorization setup timed out before an approval address was ready. Try connecting again.", "mint_failure_unknown": "Authorization setup failed before an approval address was ready. Try connecting again.", "mint_failure_url_rejected": "The provider returned an approval address containing credential-like data, so it was not displayed.", + "mint_failure_url_rejected_endpoint": "The authorization endpoint {{endpoint}} looked like it carried a credential, so it was rejected. If it is a trusted identity provider that {{productName}} does not recognize, add {{endpoint}} to oauth_endpoints.json in the {{productName}} data home (docs/guides/connecting-remote-oauth-mcp-server.md shows the entry to write). Otherwise ask the server owner to fix the URL.", "needs_attention": "Needs attention", "no_matching_services": "No services match this search.", "not_connected": "Not connected", diff --git a/website/src/i18n/locales/es.json b/website/src/i18n/locales/es.json index 21b3de83f729..0728dc1ef2e7 100644 --- a/website/src/i18n/locales/es.json +++ b/website/src/i18n/locales/es.json @@ -11059,6 +11059,7 @@ "mint_failure_timed_out": "La configuración de autorización agotó el tiempo de espera antes de que la dirección de aprobación estuviera lista. Intenta conectarte de nuevo.", "mint_failure_unknown": "La configuración de autorización falló antes de que la dirección de aprobación estuviera lista. Intenta conectarte de nuevo.", "mint_failure_url_rejected": "El proveedor devolvió una dirección de aprobación que contenía datos similares a credenciales, por lo que no se mostró.", + "mint_failure_url_rejected_endpoint": "El punto de conexión de autorización {{endpoint}} parecía contener una credencial, así que se rechazó. Si es un proveedor de identidad de confianza que {{productName}} no reconoce, añade {{endpoint}} a oauth_endpoints.json en el directorio de datos de {{productName}} (docs/guides/connecting-remote-oauth-mcp-server.md muestra la entrada que hay que escribir). Si no, pide al propietario del servidor que corrija la URL.", "needs_attention": "Requiere atención", "no_matching_services": "Ningún servicio coincide con esta búsqueda.", "not_connected": "No conectado", diff --git a/website/src/i18n/locales/fr.json b/website/src/i18n/locales/fr.json index 9dc0a0ee3415..cf54e6cd8a5d 100644 --- a/website/src/i18n/locales/fr.json +++ b/website/src/i18n/locales/fr.json @@ -11059,6 +11059,7 @@ "mint_failure_timed_out": "La configuration de l’autorisation a expiré avant que l’adresse d’approbation soit prête. Réessayez de vous connecter.", "mint_failure_unknown": "La configuration de l’autorisation a échoué avant que l’adresse d’approbation soit prête. Réessayez de vous connecter.", "mint_failure_url_rejected": "Le fournisseur a renvoyé une adresse d’approbation contenant des données ressemblant à des identifiants. Elle n’a donc pas été affichée.", + "mint_failure_url_rejected_endpoint": "Le point de terminaison d’autorisation {{endpoint}} semblait contenir un identifiant, il a donc été refusé. S’il s’agit d’un fournisseur d’identité de confiance que {{productName}} ne reconnaît pas, ajoute {{endpoint}} au fichier oauth_endpoints.json dans le dossier de données de {{productName}} (docs/guides/connecting-remote-oauth-mcp-server.md montre l’entrée à écrire). Sinon, demande au propriétaire du serveur de corriger l’URL.", "needs_attention": "Action requise", "no_matching_services": "Aucun service ne correspond à cette recherche.", "not_connected": "Non connecté", diff --git a/website/src/i18n/locales/hi.json b/website/src/i18n/locales/hi.json index 3cde12dbf562..97c8a9fb8c58 100644 --- a/website/src/i18n/locales/hi.json +++ b/website/src/i18n/locales/hi.json @@ -10900,6 +10900,7 @@ "mint_failure_timed_out": "मंज़ूरी का पता तैयार होने से पहले प्राधिकरण सेटअप का समय समाप्त हो गया। फिर से कनेक्ट करने की कोशिश करें।", "mint_failure_unknown": "मंज़ूरी का पता तैयार होने से पहले प्राधिकरण सेटअप विफल हो गया। फिर से कनेक्ट करने की कोशिश करें।", "mint_failure_url_rejected": "प्रदाता ने ऐसा मंज़ूरी पता लौटाया जिसमें क्रेडेंशियल जैसा डेटा था, इसलिए उसे नहीं दिखाया गया।", + "mint_failure_url_rejected_endpoint": "प्राधिकरण एंडपॉइंट {{endpoint}} में क्रेडेंशियल जैसा कुछ दिखा, इसलिए उसे अस्वीकार कर दिया गया। अगर यह कोई भरोसेमंद पहचान प्रदाता है जिसे {{productName}} नहीं पहचानता, तो {{productName}} डेटा होम में oauth_endpoints.json में {{endpoint}} जोड़ो (क्या लिखना है, यह docs/guides/connecting-remote-oauth-mcp-server.md में देखो)। नहीं तो सर्वर मालिक से URL ठीक करने को कहो।", "needs_attention": "ध्यान देने की ज़रूरत", "no_matching_services": "इस खोज से कोई सेवा मेल नहीं खाती।", "not_connected": "कनेक्टेड नहीं", diff --git a/website/src/i18n/locales/it.json b/website/src/i18n/locales/it.json index 5d457850cd2e..9891cba81eea 100644 --- a/website/src/i18n/locales/it.json +++ b/website/src/i18n/locales/it.json @@ -11059,6 +11059,7 @@ "mint_failure_timed_out": "La configurazione dell’autorizzazione è scaduta prima che l’indirizzo di approvazione fosse pronto. Prova a connetterti di nuovo.", "mint_failure_unknown": "La configurazione dell’autorizzazione non è riuscita prima che l’indirizzo di approvazione fosse pronto. Prova a connetterti di nuovo.", "mint_failure_url_rejected": "Il provider ha restituito un indirizzo di approvazione contenente dati simili a credenziali, quindi non è stato mostrato.", + "mint_failure_url_rejected_endpoint": "L’endpoint di autorizzazione {{endpoint}} sembrava contenere una credenziale, quindi è stato rifiutato. Se è un provider di identità affidabile che {{productName}} non riconosce, aggiungi {{endpoint}} a oauth_endpoints.json nella cartella dati di {{productName}} (docs/guides/connecting-remote-oauth-mcp-server.md mostra la voce da scrivere). Altrimenti chiedi al proprietario del server di correggere l’URL.", "needs_attention": "Richiede attenzione", "no_matching_services": "Nessun servizio corrisponde alla ricerca.", "not_connected": "Non connesso", diff --git a/website/src/i18n/locales/ja.json b/website/src/i18n/locales/ja.json index d49e824a13ee..b16f382edb92 100644 --- a/website/src/i18n/locales/ja.json +++ b/website/src/i18n/locales/ja.json @@ -10741,6 +10741,7 @@ "mint_failure_timed_out": "承認アドレスの準備ができる前に、認証の設定がタイムアウトしました。もう一度接続してください。", "mint_failure_unknown": "承認アドレスの準備ができる前に、認証の設定に失敗しました。もう一度接続してください。", "mint_failure_url_rejected": "プロバイダーから認証情報のようなデータを含む承認アドレスが返されたため、表示しませんでした。", + "mint_failure_url_rejected_endpoint": "認可エンドポイント「{{endpoint}}」に認証情報が含まれているように見えたため、拒否しました。{{productName}} が認識していない信頼できる ID プロバイダーであれば、{{productName}} のデータホームにある oauth_endpoints.json に「{{endpoint}}」を追加してください(書き方は docs/guides/connecting-remote-oauth-mcp-server.md を参照)。そうでなければ、サーバーの所有者に URL の修正を依頼してください。", "needs_attention": "注意が必要", "no_matching_services": "この検索に一致するサービスはありません。", "not_connected": "接続されていません", diff --git a/website/src/i18n/locales/ko.json b/website/src/i18n/locales/ko.json index a796476696a6..efc8a6d1cc8a 100644 --- a/website/src/i18n/locales/ko.json +++ b/website/src/i18n/locales/ko.json @@ -10741,6 +10741,7 @@ "mint_failure_timed_out": "승인 주소가 준비되기 전에 인증 설정 시간이 초과되었습니다. 다시 연결해 보세요.", "mint_failure_unknown": "승인 주소가 준비되기 전에 인증 설정에 실패했습니다. 다시 연결해 보세요.", "mint_failure_url_rejected": "공급자가 자격 증명과 유사한 데이터가 포함된 승인 주소를 반환하여 표시하지 않았습니다.", + "mint_failure_url_rejected_endpoint": "인증 엔드포인트 ‘{{endpoint}}’에 자격 증명이 포함된 것처럼 보여 거부했습니다. {{productName}}이(가) 인식하지 못하는 신뢰할 수 있는 ID 공급자라면 {{productName}} 데이터 홈의 oauth_endpoints.json에 ‘{{endpoint}}’을(를) 추가하세요(작성할 항목은 docs/guides/connecting-remote-oauth-mcp-server.md 참고). 그렇지 않다면 서버 소유자에게 URL 수정을 요청하세요.", "needs_attention": "확인 필요", "no_matching_services": "이 검색과 일치하는 서비스가 없습니다.", "not_connected": "연결되지 않음", diff --git a/website/src/i18n/locales/pt.json b/website/src/i18n/locales/pt.json index 35f29ab5dd92..0b70103f9bda 100644 --- a/website/src/i18n/locales/pt.json +++ b/website/src/i18n/locales/pt.json @@ -11059,6 +11059,7 @@ "mint_failure_timed_out": "A configuração da autorização atingiu o tempo limite antes que o endereço de aprovação estivesse pronto. Tente conectar novamente.", "mint_failure_unknown": "A configuração da autorização falhou antes que o endereço de aprovação estivesse pronto. Tente conectar novamente.", "mint_failure_url_rejected": "O provedor retornou um endereço de aprovação com dados semelhantes a credenciais, por isso ele não foi exibido.", + "mint_failure_url_rejected_endpoint": "O endpoint de autorização {{endpoint}} parecia conter uma credencial, por isso foi rejeitado. Se for um provedor de identidade confiável que o {{productName}} não reconhece, adicione {{endpoint}} ao oauth_endpoints.json na pasta de dados do {{productName}} (docs/guides/connecting-remote-oauth-mcp-server.md mostra a entrada a escrever). Caso contrário, peça ao dono do servidor para corrigir a URL.", "needs_attention": "Requer atenção", "no_matching_services": "Nenhum serviço corresponde a esta busca.", "not_connected": "Não conectado", diff --git a/website/src/i18n/locales/ru.json b/website/src/i18n/locales/ru.json index e0366008a8a1..b36988d8a356 100644 --- a/website/src/i18n/locales/ru.json +++ b/website/src/i18n/locales/ru.json @@ -11218,6 +11218,7 @@ "mint_failure_timed_out": "Время настройки авторизации истекло до того, как адрес подтверждения был готов. Попробуйте подключиться снова.", "mint_failure_unknown": "Настройка авторизации завершилась ошибкой до того, как адрес подтверждения был готов. Попробуйте подключиться снова.", "mint_failure_url_rejected": "Поставщик вернул адрес подтверждения с данными, похожими на учетные данные, поэтому адрес не был показан.", + "mint_failure_url_rejected_endpoint": "Конечная точка авторизации {{endpoint}} выглядела так, будто содержит учетные данные, поэтому она отклонена. Если это доверенный поставщик удостоверений, которого {{productName}} не знает, добавь {{endpoint}} в oauth_endpoints.json в каталоге данных {{productName}} (какую запись писать, показано в docs/guides/connecting-remote-oauth-mcp-server.md). Иначе попроси владельца сервера исправить URL.", "needs_attention": "Требует внимания", "no_matching_services": "Нет сервисов, соответствующих поиску.", "not_connected": "Не подключено", diff --git a/website/src/i18n/locales/zh-CN.json b/website/src/i18n/locales/zh-CN.json index b8cdf285d14a..d5c27660cbb1 100644 --- a/website/src/i18n/locales/zh-CN.json +++ b/website/src/i18n/locales/zh-CN.json @@ -10741,6 +10741,7 @@ "mint_failure_timed_out": "授权设置在批准地址准备好之前超时。请重试连接。", "mint_failure_unknown": "授权设置在批准地址准备好之前失败。请重试连接。", "mint_failure_url_rejected": "服务商返回的批准地址包含类似凭据的数据,因此未予显示。", + "mint_failure_url_rejected_endpoint": "授权端点 {{endpoint}} 看起来带有凭据,因此已被拒绝。如果它是 {{productName}} 尚未识别但可信的身份提供方,请把 {{endpoint}} 添加到 {{productName}} 数据目录中的 oauth_endpoints.json(条目写法见 docs/guides/connecting-remote-oauth-mcp-server.md)。否则,请让服务器所有者修正该 URL。", "needs_attention": "需要处理", "no_matching_services": "没有与搜索匹配的服务。", "not_connected": "未连接", diff --git a/website/src/pages/connections/ConnectionsPage.tsx b/website/src/pages/connections/ConnectionsPage.tsx index f64aa9b2b241..eb882b1a04f9 100644 --- a/website/src/pages/connections/ConnectionsPage.tsx +++ b/website/src/pages/connections/ConnectionsPage.tsx @@ -1385,7 +1385,7 @@ export default function ConnectionsPage({ servicesEnabled = false }: { servicesE // Decided BEFORE any setState: a state updater runs on a later render, so // collecting side-effect targets inside one leaves them empty at read time. const cleared: string[] = [] - const mintFailures: Array<{ slug: string; reason?: string }> = [] + const mintFailures: Array<{ slug: string; reason?: string; endpoint?: string }> = [] const grantedMints: string[] = [] for (const provider of CONNECTION_PROVIDERS) { const pending = locallyWaiting[provider.slug] @@ -1406,7 +1406,7 @@ export default function ConnectionsPage({ servicesEnabled = false }: { servicesE && mint.reason ) ) { - mintFailures.push({ slug: provider.slug, reason: mint.reason }) + mintFailures.push({ slug: provider.slug, reason: mint.reason, endpoint: mint.rejected_endpoint }) } if (outcome.probe) grantedMints.push(provider.slug) } @@ -1433,7 +1433,7 @@ export default function ConnectionsPage({ servicesEnabled = false }: { servicesE if (mintFailures.length) { setFeedback(current => { const next = { ...current } - for (const { slug, reason } of mintFailures) { + for (const { slug, reason, endpoint } of mintFailures) { let error: string switch (reason) { case 'mint_timeouterror': @@ -1446,7 +1446,12 @@ export default function ConnectionsPage({ servicesEnabled = false }: { servicesE error = t('pages.connectionsPage.mint_failure_server_absent') break case 'mint_url_rejected': - error = t('pages.connectionsPage.mint_failure_url_rejected') + // Name WHICH endpoint was refused when the backend could reduce + // it to a copy-ready host/path; otherwise keep the unnamed + // message rather than show a remedy that cannot work. + error = endpoint + ? t('pages.connectionsPage.mint_failure_url_rejected_endpoint', { endpoint }) + : t('pages.connectionsPage.mint_failure_url_rejected') break default: error = t('pages.connectionsPage.mint_failure_unknown') From bd55f0c1301783660e026b507b0c46efd6af06a8 Mon Sep 17 00:00:00 2001 From: CrysisDeu <32421101+CrysisDeu@users.noreply.github.com> Date: Wed, 23 Sep 2026 02:20:20 +0000 Subject: [PATCH 2/2] fix(connections): name the endpoint only when the allowlist would clear the rejection Naming an endpoint and pointing at oauth_endpoints.json is only honest when adding that entry makes the URL pass. The allowlist relaxes just the query-entropy heuristics on standard front-channel parameters; a URL refused for a fixed credential, userinfo, a fragment, path parameters, heavy percent-encoding, http or an explicit port is refused again after the entry is added. security.oauth_rejection_is_endpoint_exemptible(url) answers that question by re-running the real gate with the endpoint treated as approved: diagnose_oauth_url_credential gains assume_approved_endpoint and _exfil_url_warning gains assume_oauth_endpoint, both default-off, neither consulting the builtin set or the operator file (so no allowlist lookup and no extension-used audit event). sanitized_oauth_endpoint_display requires it, which replaces its own scheme/port check. mint.py runs the display helper off the event loop like the gate, since the counterfactual can stat the operator file. Card copy: the error line is one sentence in the card's own vocabulary ("approval address"); the oauth_endpoints.json remedy rides Feedback.detail as its own line and names whoever runs the server rather than an owner; the guide section rides Feedback.help as the existing Documentation link. Same fallback when no copy-ready endpoint exists. Tests: the operator-extension corpus is the positive set (rejected today, passes under the assumption, named verbatim); unconditional rules still reject under the assumption; the display table's nameable rows carry the long-state query and the fixed-credential / fragment / path-params rows move to unnamed; the mint and warm naming tests use the corpus URL and the fixed-credential URL becomes an unnamed control. --- docs/system-specs/modules/security.md | 2 +- src/kiro_crew/connections/mint.py | 14 +- src/kiro_crew/security/__init__.py | 30 ++- src/kiro_crew/security/_exports.py | 1 + src/kiro_crew/security/exfil.py | 49 +++- test/test_connections_mint.py | 72 +++--- test/test_connections_warm.py | 14 +- test/test_security.py | 220 +++++++++++++----- ...ure-connections-mint-rejected-endpoint.mjs | 36 ++- website/src/i18n/locales/bn.json | 3 +- website/src/i18n/locales/de.json | 3 +- website/src/i18n/locales/en-XA.json | 3 +- website/src/i18n/locales/en.manual.json | 3 +- website/src/i18n/locales/es.json | 3 +- website/src/i18n/locales/fr.json | 3 +- website/src/i18n/locales/hi.json | 3 +- website/src/i18n/locales/it.json | 3 +- website/src/i18n/locales/ja.json | 3 +- website/src/i18n/locales/ko.json | 3 +- website/src/i18n/locales/pt.json | 3 +- website/src/i18n/locales/ru.json | 3 +- website/src/i18n/locales/zh-CN.json | 3 +- .../src/pages/connections/ConnectionsPage.tsx | 29 ++- 23 files changed, 362 insertions(+), 144 deletions(-) diff --git a/docs/system-specs/modules/security.md b/docs/system-specs/modules/security.md index 0e4af3d6f961..576fa39bab69 100644 --- a/docs/system-specs/modules/security.md +++ b/docs/system-specs/modules/security.md @@ -573,7 +573,7 @@ contracts and retain their existing lexical descriptor checks. - **Decision-seam consent (keystone leaf `decisions_consent.json`)** — the switch that lets the decision seam send message text and skill descriptions to the external Jev provider (see [decisions.md](decisions.md)) is `~/.kiro/crew/decisions_consent.json`, on `_CREW_SECRET_LEAVES` (agent file tools refuse read and write), `sandbox._CREW_READONLY_LEAVES` (mounted read-only in every mode) and the absent-ceiling pre-create list. Same class and same reasoning as `aws_service_consent.json`: consent to send the operator's data to a paid external service is an authorization, and `config.json` is a `VISIBLE`, hot-applied leaf, so a `decisions.enabled` there would be flippable by a prompt-injected agent shell through any redirect and take effect on the next message. `DecisionsConfig` therefore carries no `enabled` field and the config PATCH refuses the path. Consent is bound to a destination: the keystone records the `provider.endpoint` the config named when the owner consented, and `consent.permits()` sends only while the configured endpoint still equals it — `provider.endpoint` lives in the same agent-writable `config.json`, so a bare yes/no would let the same injected shell redirect consented messages to its own server. Reads fail soft to `{}` → not consented, with a strict `is True` identity test; the only writer is the owner-only, browser-called `PUT /api/decisions/consent` handler, which refuses app tokens and allow-listed non-owner users on the read as well as the write, audits every grant/revocation to SEL, and leaves a corrupt file byte-identical rather than resetting it. - **Browsing has no keystone capability toggle, deliberately (see [browser.md](browser.md)); its executable is a READONLY keystone leaf.** `/playwright-cli` holds the product-managed entrypoint and npm package tree. It is on `_CREW_SECRET_LEAVES` for agent file tools and `_CREW_READONLY_LEAVES` for every OS sandbox: in-sandbox browser commands can read and execute it, while a write that would choose the binary the unsandboxed gateway executes fails at the kernel boundary. The empty directory is absent-equivalent and belongs to `_CREW_PRECREATE_READONLY_DIR_LEAVES`, so the first sandbox cannot win an absent-target race before the first install. It is also the sole `_CREW_NOFOLLOW_READONLY_DIR_LEAVES` member: a resolving symlink, or one that wins the `mkdir` race, refuses the spawn because the bind mount would seal its target while leaving the executable name replaceable. Gateway resolution checks this absolute leaf first, then fixed system directories whose resolved launcher hierarchy the gateway user cannot write. The in-product installer also creates and no-follow pins the real directory before passing it to npm; links, Windows reparse points and create/open identity races abort before any package write, and the Windows pin blocks rename for the duration of npm. It never resolves from `PATH`, `~/.local/bin`, an active project or the workspace; legacy user-local launchers remain on disk and are ignored. The launcher is identity only for gateway-owned calls on every OS: the managed installer atomically stages the native Node executable as `gateway-node` on POSIX or `node.exe` on Windows, and the gateway runs it with the attributed package's contained `playwright-cli.js`. A fixed-system copy is usable only with a Node and package entry whose complete hierarchies also pass the non-writable-system check. Thus a POSIX `env node` shebang cannot select an agent-writable version-manager binary, and owner URL bytes never cross a Windows command-processor boundary. Binary presence is still NOT an approval signal. Every agent invocation follows the ordinary shell approval ladder, and only an explicit trusted pattern, session trust or auto-approve grant may skip the prompt. Because browsing is a shell command, it is governed on the `commands` plane and an `mcp`-scope deny does not reach it. -- **Operator OAuth consent-endpoint extension (keystone leaf `oauth_endpoints.json`)** — the security module's OAuth banner-safety contract (`security.oauth_url_contains_credential`, and `_exfil_url_warning` under `allow_oauth_entropy=True`) exempts standard front-channel params (`state`, PKCE, …) from the base64-blob/query-length heuristics only at an exact-match `(host, path)` in the code-owned `_OAUTH_AUTHORIZATION_ENDPOINTS`. `~/.kiro/crew/oauth_endpoints.json` (`{"additional_authorization_endpoints": [{"host", "path"}]}`) is the operator's escape hatch for identity providers outside that launch set (Okta orgs, Auth0, self-hosted OIDC, tenant-scoped Entra paths): `security._load_operator_oauth_endpoints()` unions strictly validated entries with the builtin set at check time (`_approved_oauth_authorization_endpoint`, memoized on the file's stat so a hand-edit takes effect on the next check without a restart). **Enforcement point:** the dashboard's live MCP OAuth banner validates URLs with this same gate — `_emit_mcp_oauth_request` in `chat_runner.py` calls `security.oauth_url_contains_credential` directly — so an operator endpoint entry governs the banner path as well as every other consumer wired to the contract gate. Each entry widens a trust boundary, so the file is on `_CREW_SECRET_LEAVES` (full read+write keystone block on both the tool path and every shell form) — an agent must not be able to author its own exemption — and there is deliberately no dashboard writer; the operator hand-edits it out-of-band. Every read fails soft to the EMPTY set (missing/unreadable/corrupt/non-object file, mirroring `computer_use.enable_state.load_state`), invalid entries are skipped individually with a warning (no wildcards, schemes, ports, userinfo, percent-escapes, IP literals, `..`, whitespace, or backslashes; hosts are lowercase-normalized DNS names with a letter TLD, paths exact and case-sensitive), and the entry list is truncated at 50 before validation so a mangled file cannot amplify. HTTPS-only / no-explicit-port / exact-match stay enforced by the gate logic and are NOT relaxable via the file, and the exemption grants exactly what the builtin set grants — fixed-credential patterns, heavy percent-encoding, userinfo, fragments, backslashes, and unknown-param heuristics remain unconditional. The markerless bare-secret entropy heuristic follows the same exact endpoint/parameter scope instead of scanning entropy-bearing recognized parameter values first; parameter names, unknown parameters, and non-query components remain in its scan target. That exemption is additionally bounded to the shapes the protocol itself can emit (`_oauth_entropy_value_is_protocol_shaped`, judged on EVERY decoded form: it percent-decodes until the text stops changing, bounded by `_MAX_URL_DECODE_PASSES`, and refuses a value still decodable at the bound, so `%252F` cannot launder the standard alphabet past a single decode): base64url emits `-`/`_` and never `+`/`/`, and an S256 `code_challenge` is base64url of a 32-byte digest, so it is exactly 43 characters. A base64-standard-alphabet run — the shape of an AWS secret key — therefore cannot ride `state`, `nonce`, or `code_challenge` into the blanked set. The residual is narrower but real: a markerless 40-character credential that happens to be alphanumeric is indistinguishable from ordinary base64url state entropy and is accepted only at this boundary; general output redactors retain the heuristic. An approval that came from an operator entry (not the builtin set) emits a best-effort `oauth_endpoint_extension_used` SEL event, deduped per process per endpoint. **Rejections name the endpoint, never the values:** `security.sanitized_oauth_endpoint(url)` returns the lowercase host + path of a rejected authorization URL (query/fragment/port/userinfo are never included; both components are scanned at every percent-decode layer up to the gate's own `_MAX_URL_DECODE_PASSES` budget — a credential-bearing or budget-exhausting path self-redacts to the shared tag, a credential-bearing host makes the helper return `None`, a non-ASCII host is surfaced in IDNA A-label form; both components are length-capped and a capped component ends in `…`; unparseable URLs return `None`). The banner path (`_emit_mcp_oauth_request`) surfaces that pair in the rejection text — which also spells the `{"additional_authorization_endpoints": [{"host", "path"}]}` entry shape — and inside the `error` meta field the dashboard's failed banner actually renders; no additional meta keys are emitted because no shipped surface reads any. So the user can tell WHICH endpoint tripped the scanner and what to write into `oauth_endpoints.json`, without the rejection ever echoing state/PKCE material (#7578). **Connections mint/warm rejection surfaces name the endpoint on the card, never in a log.** The cold mint (`connections/mint.py`, terminal `mint_url_rejected`) calls `security.sanitized_oauth_endpoint_display(url)` — the copy-ready contract layered on the diagnostic pair: it returns one `host/path` string only when the pair would also be ACCEPTED by the `oauth_endpoints.json` loader and honoured by the gate (host matches `_OAUTH_EXTENSION_HOST_RE`, so `localhost`, IP literals and a `…`-capped host are refused; path passes `_valid_oauth_extension_path` and is neither the redaction tag nor `…`-capped; scheme is `https` with no explicit port), and `None` otherwise — and stores the result as `MintState["rejected_endpoint"]`, which rides `pending_mint_for` and the `GET /api/connections/mint` payload to the Connections card (`mint_failure_url_rejected_endpoint`; the unnamed `mint_failure_url_rejected` copy stays the fallback on `None`). The warning log and the `_log_mint_outcome` audit line stay slug-only by decision: routing URL-derived text through the logger is what the credential-disclosure scanners (Semgrep `python-logger-credential-disclosure`, CodeQL `py/clear-text-logging-sensitive-data`) flag, and a card field is not a logger sink, so no inline suppression or barrier model is needed. The warm premint gate (`warm._credential_bearing_slugs`) does not name the endpoint itself: a refused slug's claim is RELEASED (never a failed row — `test_a_url_carrying_a_credential_is_refused_rather_than_stored`), the card then asks for a cold mint, and that mint re-hits the same URL and names the endpoint through the surface above, so the warm refusal is actionable without a second channel (#7765). +- **Operator OAuth consent-endpoint extension (keystone leaf `oauth_endpoints.json`)** — the security module's OAuth banner-safety contract (`security.oauth_url_contains_credential`, and `_exfil_url_warning` under `allow_oauth_entropy=True`) exempts standard front-channel params (`state`, PKCE, …) from the base64-blob/query-length heuristics only at an exact-match `(host, path)` in the code-owned `_OAUTH_AUTHORIZATION_ENDPOINTS`. `~/.kiro/crew/oauth_endpoints.json` (`{"additional_authorization_endpoints": [{"host", "path"}]}`) is the operator's escape hatch for identity providers outside that launch set (Okta orgs, Auth0, self-hosted OIDC, tenant-scoped Entra paths): `security._load_operator_oauth_endpoints()` unions strictly validated entries with the builtin set at check time (`_approved_oauth_authorization_endpoint`, memoized on the file's stat so a hand-edit takes effect on the next check without a restart). **Enforcement point:** the dashboard's live MCP OAuth banner validates URLs with this same gate — `_emit_mcp_oauth_request` in `chat_runner.py` calls `security.oauth_url_contains_credential` directly — so an operator endpoint entry governs the banner path as well as every other consumer wired to the contract gate. Each entry widens a trust boundary, so the file is on `_CREW_SECRET_LEAVES` (full read+write keystone block on both the tool path and every shell form) — an agent must not be able to author its own exemption — and there is deliberately no dashboard writer; the operator hand-edits it out-of-band. Every read fails soft to the EMPTY set (missing/unreadable/corrupt/non-object file, mirroring `computer_use.enable_state.load_state`), invalid entries are skipped individually with a warning (no wildcards, schemes, ports, userinfo, percent-escapes, IP literals, `..`, whitespace, or backslashes; hosts are lowercase-normalized DNS names with a letter TLD, paths exact and case-sensitive), and the entry list is truncated at 50 before validation so a mangled file cannot amplify. HTTPS-only / no-explicit-port / exact-match stay enforced by the gate logic and are NOT relaxable via the file, and the exemption grants exactly what the builtin set grants — fixed-credential patterns, heavy percent-encoding, userinfo, fragments, backslashes, and unknown-param heuristics remain unconditional. The markerless bare-secret entropy heuristic follows the same exact endpoint/parameter scope instead of scanning entropy-bearing recognized parameter values first; parameter names, unknown parameters, and non-query components remain in its scan target. That exemption is additionally bounded to the shapes the protocol itself can emit (`_oauth_entropy_value_is_protocol_shaped`, judged on EVERY decoded form: it percent-decodes until the text stops changing, bounded by `_MAX_URL_DECODE_PASSES`, and refuses a value still decodable at the bound, so `%252F` cannot launder the standard alphabet past a single decode): base64url emits `-`/`_` and never `+`/`/`, and an S256 `code_challenge` is base64url of a 32-byte digest, so it is exactly 43 characters. A base64-standard-alphabet run — the shape of an AWS secret key — therefore cannot ride `state`, `nonce`, or `code_challenge` into the blanked set. The residual is narrower but real: a markerless 40-character credential that happens to be alphanumeric is indistinguishable from ordinary base64url state entropy and is accepted only at this boundary; general output redactors retain the heuristic. An approval that came from an operator entry (not the builtin set) emits a best-effort `oauth_endpoint_extension_used` SEL event, deduped per process per endpoint. **Rejections name the endpoint, never the values:** `security.sanitized_oauth_endpoint(url)` returns the lowercase host + path of a rejected authorization URL (query/fragment/port/userinfo are never included; both components are scanned at every percent-decode layer up to the gate's own `_MAX_URL_DECODE_PASSES` budget — a credential-bearing or budget-exhausting path self-redacts to the shared tag, a credential-bearing host makes the helper return `None`, a non-ASCII host is surfaced in IDNA A-label form; both components are length-capped and a capped component ends in `…`; unparseable URLs return `None`). The banner path (`_emit_mcp_oauth_request`) surfaces that pair in the rejection text — which also spells the `{"additional_authorization_endpoints": [{"host", "path"}]}` entry shape — and inside the `error` meta field the dashboard's failed banner actually renders; no additional meta keys are emitted because no shipped surface reads any. So the user can tell WHICH endpoint tripped the scanner and what to write into `oauth_endpoints.json`, without the rejection ever echoing state/PKCE material (#7578). **Connections mint/warm rejection surfaces name the endpoint on the card, never in a log.** The cold mint (`connections/mint.py`, terminal `mint_url_rejected`) calls `security.sanitized_oauth_endpoint_display(url)` — the copy-ready contract layered on the diagnostic pair: it returns one `host/path` string only when writing the entry would WORK: the host matches `_OAUTH_EXTENSION_HOST_RE` (so `localhost`, IP literals and a `…`-capped host are refused), the path passes `_valid_oauth_extension_path` and is neither the redaction tag nor `…`-capped, and the rejection is one the allowlist can clear — `security.oauth_rejection_is_endpoint_exemptible(url)` re-runs the gate via `diagnose_oauth_url_credential(url, assume_approved_endpoint=True)`, which treats the endpoint as approved WITHOUT consulting the builtin set or the operator file (no lookup, no `oauth_endpoint_extension_used` audit) and relaxes nothing else, so a URL refused for a fixed credential, userinfo, a fragment, path parameters, heavy percent-encoding, `http` or an explicit port stays unnamed rather than advertise a remedy that leaves it rejected; `None` otherwise — and stores the result as `MintState["rejected_endpoint"]`, which rides `pending_mint_for` and the `GET /api/connections/mint` payload to the Connections card (`mint_failure_url_rejected_endpoint`; the unnamed `mint_failure_url_rejected` copy stays the fallback on `None`). The warning log and the `_log_mint_outcome` audit line stay slug-only by decision: routing URL-derived text through the logger is what the credential-disclosure scanners (Semgrep `python-logger-credential-disclosure`, CodeQL `py/clear-text-logging-sensitive-data`) flag, and a card field is not a logger sink, so no inline suppression or barrier model is needed. The warm premint gate (`warm._credential_bearing_slugs`) does not name the endpoint itself: a refused slug's claim is RELEASED (never a failed row — `test_a_url_carrying_a_credential_is_refused_rather_than_stored`), the card then asks for a cold mint, and that mint re-hits the same URL and names the endpoint through the surface above, so the warm refusal is actionable without a second channel (#7765). **Privacy-safe OAuth rejection diagnostics.** `security.diagnose_oauth_url_credential()` returns `None` for an accepted URL or an `OAuthUrlCredentialDiagnostic` for the first rejecting sub-check. The record carries only a stable `rule`, a URL-component category, an optional code-owned standard query-parameter name, and a shape profile: total length plus counts of ASCII uppercase, ASCII lowercase, digits, percent signs, URL punctuation, and all other characters. `oauth_url_contains_credential()` retains its boolean caller contract and logs that same bounded signature when it rejects. The diagnostic path does not change a rule, add a bypass, retry, or retain a URL. The URL and parameter value are never returned, logged, persisted, hashed, sampled, or represented by a prefix/suffix; malformed, credential-shaped, and unrecognized parameter names are omitted rather than echoed. This is sufficient for a controlled mint loop to distinguish standard OAuth entropy false positives (for example, `credential_scan_bare_secret_raw` on `state` versus `exfil_query_length`) without creating a second credential-bearing sink. An entropy-bearing recognized parameter value at an approved endpoint produces no diagnostic on entropy alone, while the same shape in an unknown parameter retains the stable `credential_scan_bare_secret_raw` rejection signature. diff --git a/src/kiro_crew/connections/mint.py b/src/kiro_crew/connections/mint.py index 735503e02bf2..fef57c604a95 100644 --- a/src/kiro_crew/connections/mint.py +++ b/src/kiro_crew/connections/mint.py @@ -930,12 +930,14 @@ async def start_oauth_mint( # Named on the CARD, never in the log: without the host+path the # user cannot know what to write into oauth_endpoints.json, so the # failure reads as unfixable. The display helper owns the - # copy-ready contract (None for a host-borne credential, userinfo, - # a redacted or capped component, a non-https or ported URL, or a - # shape the extension loader would refuse), so the card falls back - # to its unnamed message rather than showing a remedy that cannot - # work. Pure parse-and-match, so no thread hop is needed. - rejected_endpoint = sanitized_oauth_endpoint_display(oauth_url) + # copy-ready contract: None for a host-borne credential, userinfo, + # a redacted or capped component, a shape the extension loader would + # refuse, or a rejection the allowlist could not clear anyway (fixed + # credential, fragment, path params, http, explicit port) -- so the + # card falls back to its unnamed message rather than show a remedy + # that cannot work. Same thread hop as the gate: the counterfactual + # re-runs it, and it can stat the operator's endpoint file. + rejected_endpoint = await asyncio.to_thread(sanitized_oauth_endpoint_display, oauth_url) async with _mints_lock: if _mints.get(slug, {}).get("token") == my_token: failed: MintState = { diff --git a/src/kiro_crew/security/__init__.py b/src/kiro_crew/security/__init__.py index 3b3d89beeb8a..4dc213b904b2 100644 --- a/src/kiro_crew/security/__init__.py +++ b/src/kiro_crew/security/__init__.py @@ -292,6 +292,7 @@ canonicalize_ip, diagnose_oauth_url_credential, exfil_query_min_len, + oauth_rejection_is_endpoint_exemptible, oauth_url_contains_credential, redact_exfiltration_urls, scan_exfiltration_urls, @@ -775,21 +776,23 @@ def sanitized_oauth_endpoint_display(url: str) -> str | None: ``oauth_endpoints.json``" must not join those into text that reads as actionable and is not. - So this helper returns a string only when the pair would also be accepted - by the extension file's own loader and honoured by the gate that reads it: + So this helper returns a string only when writing the entry would WORK: * the host matches ``_OAUTH_EXTENSION_HOST_RE`` (lowercase DNS name with a letter TLD — so ``localhost``, IP literals and a capped host are refused); * the path passes ``_valid_oauth_extension_path`` (leading ``/``, no ``; ? # % \\ ..`` or whitespace) and is neither redacted nor capped; - * the URL is ``https`` with no explicit port, because the gate grants the - endpoint carve-out only under those two conditions and an entry for an - ``http`` or ``:8443`` endpoint would be refused again after the user - added it. - - Callers fall back to their unnamed message on ``None``. The function is a - pure parse-and-match: it never re-runs the credential verdict and never - touches the operator file, so it is safe to call inline. + * the rejection is one the allowlist can clear + (:func:`oauth_rejection_is_endpoint_exemptible`): the gate is re-run as + if the endpoint were approved, and only a URL that then PASSES is named. + A URL refused for a fixed credential, userinfo, a fragment, path + parameters, heavy percent-encoding, ``http`` or an explicit port would be + refused again after the entry is added, so it stays unnamed rather than + advertise a remedy that cannot work. + + Callers fall back to their unnamed message on ``None``. Because the + counterfactual re-runs the gate, this can stat the operator file (memoized), + so callers treat it like the gate itself and run it off the event loop. """ endpoint = sanitized_oauth_endpoint(url) if endpoint is None: @@ -801,12 +804,7 @@ def sanitized_oauth_endpoint_display(url: str) -> str | None: return None if not _OAUTH_EXTENSION_HOST_RE.fullmatch(host) or not _valid_oauth_extension_path(path): return None - try: - parsed = urlparse(url) - port = parsed.port - except ValueError: - return None - if parsed.scheme.lower() != "https" or port is not None: + if not oauth_rejection_is_endpoint_exemptible(url): return None return f"{host}{path}" diff --git a/src/kiro_crew/security/_exports.py b/src/kiro_crew/security/_exports.py index 2793d8e07476..b8b4e742d8ea 100644 --- a/src/kiro_crew/security/_exports.py +++ b/src/kiro_crew/security/_exports.py @@ -533,6 +533,7 @@ "maintenance_executor", "math", "normalize_shell_command", + "oauth_rejection_is_endpoint_exemptible", "oauth_url_contains_credential", "os", "parse_qs", diff --git a/src/kiro_crew/security/exfil.py b/src/kiro_crew/security/exfil.py index f0108aacc2bb..e88ca49b69ce 100644 --- a/src/kiro_crew/security/exfil.py +++ b/src/kiro_crew/security/exfil.py @@ -874,6 +874,7 @@ def _exfil_url_warning( is_https: bool = True, allow_safe_presigned: bool = True, allow_oauth_entropy: bool = False, + assume_oauth_endpoint: bool = False, _rule_out: list[str] | None = None, ) -> str | None: """Classify one matched URL — the single per-URL exfil verdict. @@ -882,6 +883,11 @@ def _exfil_url_warning( redact_exfiltration_urls (which redacts every URL that returns non-None), so the two paths can never drift. Returns the warning string, or None if clean. ``_rule_out`` receives only a stable rule id, never URL-derived text. + ``assume_oauth_endpoint`` answers a counterfactual, never a verdict: it + treats the endpoint as if it were on the OAuth allowlist WITHOUT consulting + the builtin set or the operator file, so a caller can ask "would this URL + pass if the operator added its endpoint?". HTTPS-only / no-explicit-port + are not assumed away, because the allowlist never relaxes them either. """ def trace(rule: str) -> None: @@ -961,7 +967,10 @@ def trace(rule: str) -> None: allow_oauth_entropy and is_https and not port - and _approved_oauth_authorization_endpoint(_dom, path_and_query.split("?", 1)[0]) + and ( + assume_oauth_endpoint + or _approved_oauth_authorization_endpoint(_dom, path_and_query.split("?", 1)[0]) + ) ) if _oauth_endpoint: # Names are matched literally and case-sensitively; encoded/mixed-case @@ -1177,8 +1186,19 @@ def _oauth_credential_scan_target( return url[: query_start + 1] + sanitized_query + suffix -def diagnose_oauth_url_credential(url: str) -> OAuthUrlCredentialDiagnostic | None: - """Return a safe rejection signature, never URL/value bytes or derivatives.""" +def diagnose_oauth_url_credential( + url: str, *, assume_approved_endpoint: bool = False +) -> OAuthUrlCredentialDiagnostic | None: + """Return a safe rejection signature, never URL/value bytes or derivatives. + + ``assume_approved_endpoint`` runs the SAME gate as if the URL's endpoint + were on the OAuth allowlist (builtin or operator file), without reading + either. It exists so a rejection surface can tell whether the + ``oauth_endpoints.json`` remedy would actually clear THIS rejection before + advertising it; every unconditional rule (fixed credentials, userinfo, + fragments, path params, heavy percent-encoding, http, explicit port) still + rejects under the assumption, exactly as it does for an approved endpoint. + """ if not url: return None @@ -1242,7 +1262,10 @@ def diagnose_oauth_url_credential(url: str) -> OAuthUrlCredentialDiagnostic | No approved_endpoint = ( parsed.scheme.lower() == "https" and not port - and _approved_oauth_authorization_endpoint(parsed.hostname.lower(), parsed.path) + and ( + assume_approved_endpoint + or _approved_oauth_authorization_endpoint(parsed.hostname.lower(), parsed.path) + ) ) scan_target = _oauth_credential_scan_target( url, @@ -1291,6 +1314,7 @@ def diagnose_oauth_url_credential(url: str) -> OAuthUrlCredentialDiagnostic | No is_https=parsed.scheme.lower() == "https", allow_safe_presigned=False, allow_oauth_entropy=True, + assume_oauth_endpoint=assume_approved_endpoint, _rule_out=rules, ) if warning is None: @@ -1382,6 +1406,23 @@ def oauth_url_contains_credential(url: str) -> bool: return True +def oauth_rejection_is_endpoint_exemptible(url: str) -> bool: + """True when *url* is rejected today AND would pass with its endpoint allowlisted. + + This is the question a rejection surface must answer before it names the + endpoint and points at ``oauth_endpoints.json``: the allowlist relaxes only + the query-entropy heuristics on standard front-channel parameters, so a URL + refused for a fixed credential, userinfo, a fragment, path parameters, heavy + percent-encoding, ``http`` or an explicit port is refused again after the + entry is added, and naming it would advertise a remedy that cannot work. + Reads the operator file only through the ordinary gate (memoized stat), so + callers treat it like the gate itself: run it off the event loop. + """ + if diagnose_oauth_url_credential(url) is None: + return False + return diagnose_oauth_url_credential(url, assume_approved_endpoint=True) is None + + # Data-egress / reverse-shell command shapes — the exfiltration-specific subset # of SUSPICIOUS_BASH_PATTERNS. These are enforced at the # tool-invocation gate (denied), unlike the full SUSPICIOUS_BASH_PATTERNS list diff --git a/test/test_connections_mint.py b/test/test_connections_mint.py index 38f6538430bc..4c37c5e4bbab 100644 --- a/test/test_connections_mint.py +++ b/test/test_connections_mint.py @@ -21,6 +21,7 @@ from aiohttp import web from aiohttp.test_utils import TestClient, TestServer from dashboard_owner_helpers import as_owner +from oauth_url_corpus import OPERATOR_EXTENSION_OAUTH_URLS from conftest import requires_symlinks from kiro_crew import hooks, mcp_grant @@ -1003,29 +1004,31 @@ def __init__(self, **kwargs: Any) -> None: view = mint.pending_mint_for("notion") assert view is not None assert view["token"] == token - # The card learns WHICH endpoint the gate refused (host+path only), so the - # user knows what to write into oauth_endpoints.json. The credential lived - # in the query, which the display helper never echoes. - assert _state_only(view) == { - "state": "failed", - "reason": "mint_url_rejected", - "rejected_endpoint": "auth.example.com/authorize", - } + # A fixed credential in the query is a rejection the allowlist cannot + # clear, so the card is NOT told which endpoint to add: naming it here would + # advertise a remedy that leaves the URL rejected. The naming case is the + # allowlist-clearable rejection below. + assert _state_only(view) == {"state": "failed", "reason": "mint_url_rejected"} assert len(_FakeClient.instances) == 2 assert [client.shutdowns for client in _FakeClient.instances] == [1, 1] assert protected_pids == set() assert logged == ["error reason=mint_url_rejected"] assert "AKIAIOSFODNN7EXAMPLE" not in caplog.text assert "AKIAIOSFODNN7EXAMPLE" not in json.dumps(logged) - # The endpoint rides ONLY the card view: neither the warning log nor the - # audit line may carry any URL-derived text, or the credential-disclosure - # scanners would be right to flag them. assert "auth.example.com" not in caplog.text - assert "auth.example.com" not in json.dumps(logged) - assert tainted not in caplog.text assert tainted not in json.dumps(view) +# The URL the operator extension exists for: standard front-channel parameters +# whose opaque state trips the long-query heuristic at any endpoint outside the +# allowlist, and passes once the endpoint is added. This is the shape the card +# must NAME, because adding the entry actually fixes it. +_EXEMPTIBLE_NAME, _EXEMPTIBLE_URL, (_EXEMPTIBLE_HOST, _EXEMPTIBLE_PATH) = ( + OPERATOR_EXTENSION_OAUTH_URLS[0] +) +_EXEMPTIBLE_ENDPOINT = f"{_EXEMPTIBLE_HOST}{_EXEMPTIBLE_PATH}" + + async def _reject_twice( monkeypatch: pytest.MonkeyPatch, caplog, tainted: str ) -> tuple[dict | None, list[str]]: @@ -1061,12 +1064,24 @@ def __init__(self, **kwargs: Any) -> None: "https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize", # Nameable host+path, but the extension loader would refuse the host, # so naming it would advertise an entry that gets skipped on load. - "https://localhost/authorize?access_token=AKIAIOSFODNN7EXAMPLE", + _EXEMPTIBLE_URL.replace(_EXEMPTIBLE_HOST, "localhost", 1), # Nameable host+path, but the gate never grants the carve-out to an # explicit port, so the entry would be refused again after adding it. - "https://auth.example.com:8443/authorize?access_token=AKIAIOSFODNN7EXAMPLE", + _EXEMPTIBLE_URL.replace(_EXEMPTIBLE_HOST, _EXEMPTIBLE_HOST + ":8443", 1), + # Nameable, loader-valid host+path, but a fixed credential in the query + # is refused unconditionally -- the allowlist would not clear it. + f"https://{_EXEMPTIBLE_HOST}{_EXEMPTIBLE_PATH}?access_token=AKIAIOSFODNN7EXAMPLE", + # Same, for a fragment: providers never emit one, the gate never allows one. + _EXEMPTIBLE_URL + "#AKIAIOSFODNN7EXAMPLE", + ], + ids=[ + "credential-in-host", + "credential-in-path", + "loader-refuses-host", + "explicit-port", + "fixed-credential-in-query", + "fragment", ], - ids=["credential-in-host", "credential-in-path", "loader-refuses-host", "explicit-port"], ) async def test_a_rejection_the_helper_cannot_name_leaves_the_card_unnamed( monkeypatch: pytest.MonkeyPatch, protected_pids: set[int], caplog, tainted: str @@ -1091,22 +1106,19 @@ async def test_the_named_endpoint_is_host_and_path_only( ): """The card gets the endpoint identity and nothing else from the URL: no scheme, query, fragment, or the state/PKCE material that lives in them.""" - tainted = ( - "https://IdP.Example.com/realms/dev/authorize" - "?client_id=abc&state=TOPSECRETSTATE&code_challenge=PKCEMATERIAL" - "&access_token=AKIAIOSFODNN7EXAMPLE#frag" - ) + # Mixed-case host, and every query value is opaque material the card must + # never echo (the 128-char state is what trips the gate). + tainted = _EXEMPTIBLE_URL.replace(_EXEMPTIBLE_HOST, _EXEMPTIBLE_HOST.title(), 1) view, logged = await _reject_twice(monkeypatch, caplog, tainted) assert view is not None - assert view["rejected_endpoint"] == "idp.example.com/realms/dev/authorize" + assert view["rejected_endpoint"] == _EXEMPTIBLE_ENDPOINT serialized = json.dumps(view) for never in ( "https://", - "TOPSECRETSTATE", - "PKCEMATERIAL", - "AKIAIOSFODNN7EXAMPLE", - "#frag", + "a1B2c3D4", + "E9Melhoa2Owv", + "client_id", "?", ): assert never not in serialized @@ -1121,14 +1133,14 @@ async def test_a_named_endpoint_never_reaches_the_log_or_audit_line( """The scanner decision: the endpoint is a CARD field, not log text. If a future edit routes it through the logger, this fails before Semgrep or CodeQL do.""" - tainted = "https://auth.example.com/authorize?access_token=AKIAIOSFODNN7EXAMPLE" - view, logged = await _reject_twice(monkeypatch, caplog, tainted) + view, logged = await _reject_twice(monkeypatch, caplog, _EXEMPTIBLE_URL) assert view is not None - assert view["rejected_endpoint"] == "auth.example.com/authorize" + assert view["rejected_endpoint"] == _EXEMPTIBLE_ENDPOINT assert caplog.text # the slug-only warning still fires assert "notion" in caplog.text - assert "auth.example.com" not in caplog.text + assert _EXEMPTIBLE_HOST not in caplog.text + assert _EXEMPTIBLE_HOST not in json.dumps(logged) assert logged == ["error reason=mint_url_rejected"] diff --git a/test/test_connections_warm.py b/test/test_connections_warm.py index 51f719bbd4b7..c3e3bd03e2cb 100644 --- a/test/test_connections_warm.py +++ b/test/test_connections_warm.py @@ -15,6 +15,7 @@ from typing import Any import pytest +from oauth_url_corpus import OPERATOR_EXTENSION_OAUTH_URLS from test_connections_mint import _FS_ATTRS, _FS_NAMES, _called_names from conftest import requires_symlinks @@ -1579,7 +1580,10 @@ async def test_a_refused_premint_stays_slug_only_and_hands_naming_to_the_cold_mi card's poll reads ``idle`` and asks for a cold mint), the warm-side text carries the slug and nothing from the URL, and the display contract the cold mint applies to the same URL yields the copy-ready endpoint.""" - url = "https://linear.example/authorize?state=AKIA" + "IOSFODNN7EXAMPLE1" + # The operator-extension corpus: rejected for a long opaque state at an + # endpoint outside the allowlist, clean once the endpoint is added -- the + # one shape whose cold-mint card must name the endpoint. + _, url, (host, path) = OPERATOR_EXTENSION_OAUTH_URLS[0] audited: list[tuple[str, str, str]] = [] monkeypatch.setattr( warm, "_log_warm_event", lambda op, res, outcome="ok": audited.append((op, res, outcome)) @@ -1598,13 +1602,15 @@ async def test_a_refused_premint_stays_slug_only_and_hands_naming_to_the_cold_mi # Slug-only on every warm-side channel. assert audited == [("connections_warm_mint_url", "provider:linear", "refused")] assert "linear" in caplog.text - for never in ("linear.example", "/authorize", "AKIA", url): + for never in (host, path, "a1B2c3D4", url): assert never not in caplog.text assert never not in json.dumps(audited) # The hand-off is coherent: the cold mint the card now starts re-hits this URL, - # and its card view names exactly this endpoint (host+path, nothing from the query). + # and its card view names exactly this endpoint (host+path, nothing from the query) + # -- because this is a rejection the allowlist entry would clear. assert security.oauth_url_contains_credential(url) - assert security.sanitized_oauth_endpoint_display(url) == "linear.example/authorize" + assert security.oauth_rejection_is_endpoint_exemptible(url) + assert security.sanitized_oauth_endpoint_display(url) == f"{host}{path}" @pytest.mark.asyncio diff --git a/test/test_security.py b/test/test_security.py index b1d7ffa28555..110e75868d42 100644 --- a/test/test_security.py +++ b/test/test_security.py @@ -3728,61 +3728,170 @@ def test_unparseable_urls_return_none(self, url: str) -> None: assert sanitized_oauth_endpoint(url) is None +def _long_state_query(*, extra: str = "") -> str: + """A standard front-channel query whose opaque ``state`` pushes it past the + long-query heuristic: rejected at any endpoint outside the allowlist, clean + at an allowlisted one, because every parameter is a known OAuth name.""" + return ( + "?client_id=client123&response_type=code" + "&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback" + "&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" + "&code_challenge_method=S256" + "&state=" + ("a1B2c3D4" * 16) + extra + ) + + +class TestOAuthRejectionIsEndpointExemptible: + """``oauth_rejection_is_endpoint_exemptible`` answers "would the allowlist fix it?". + + The counterfactual (``diagnose_oauth_url_credential(url, + assume_approved_endpoint=True)``) re-runs the real gate with the endpoint + treated as approved and nothing else relaxed. The operator-extension corpus + is the positive set by definition: each entry is a URL the field rejected + until its operator added the endpoint. + """ + + @pytest.mark.parametrize( + ("url", "endpoint"), + [(url, endpoint) for _, url, endpoint in OPERATOR_EXTENSION_OAUTH_URLS], + ids=[name for name, _, _ in OPERATOR_EXTENSION_OAUTH_URLS], + ) + def test_corpus_urls_are_rejected_today_and_pass_once_allowlisted( + self, url: str, endpoint: tuple[str, str] + ) -> None: + assert security.diagnose_oauth_url_credential(url) is not None + assert security.diagnose_oauth_url_credential(url, assume_approved_endpoint=True) is None + assert security.oauth_rejection_is_endpoint_exemptible(url) is True + + @pytest.mark.parametrize( + "url", + [ + "https://idp.example.com/authorize?access_token=AKIAIOSFODNN7EXAMPLE", + "https://idp.example.com/authorize" + _long_state_query(extra="#frag"), + "https://idp.example.com/authorize;v=1" + _long_state_query(), + f"https://user:pw@idp.example.com/authorize{_long_state_query()}", + "http://idp.example.com/authorize" + _long_state_query(), + "https://idp.example.com:8443/authorize" + _long_state_query(), + "https://idp.example.com/authorize?state=" + ("%41" * 80), + ], + ids=[ + "fixed-credential-in-query", + "fragment", + "path-params", + "userinfo", + "http-scheme", + "explicit-port", + "heavy-percent-encoding", + ], + ) + def test_unconditional_rules_still_reject_under_the_assumption(self, url: str) -> None: + assert security.diagnose_oauth_url_credential(url) is not None + assert ( + security.diagnose_oauth_url_credential(url, assume_approved_endpoint=True) is not None + ) + assert security.oauth_rejection_is_endpoint_exemptible(url) is False + + def test_a_url_the_gate_accepts_has_nothing_to_exempt(self) -> None: + clean = "https://idp.example.com/authorize?state=abc&code_challenge_method=S256" + assert security.diagnose_oauth_url_credential(clean) is None + assert security.oauth_rejection_is_endpoint_exemptible(clean) is False + + def test_the_assumption_does_not_consult_the_operator_file( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """The counterfactual is a pure re-run of the gate: no allowlist lookup, + so no ``oauth_endpoint_extension_used`` audit event can fire for an + endpoint nobody actually approved.""" + looked_up: list[tuple[str, str]] = [] + + def spy(host: str, path: str) -> bool: + looked_up.append((host, path)) + return False + + monkeypatch.setattr(security, "_approved_oauth_authorization_endpoint", spy) + url = OPERATOR_EXTENSION_OAUTH_URLS[0][1] + assert security.diagnose_oauth_url_credential(url, assume_approved_endpoint=True) is None + assert looked_up == [] + assert security.diagnose_oauth_url_credential(url) is not None + assert looked_up != [] + + def test_the_default_verdict_is_unchanged(self) -> None: + """``assume_approved_endpoint`` defaults off, so the boolean gate every + caller uses is byte-for-byte the old one.""" + url = OPERATOR_EXTENSION_OAUTH_URLS[0][1] + assert security.oauth_url_contains_credential(url) is True + + class TestSanitizedOAuthEndpointDisplay: """``sanitized_oauth_endpoint_display`` is the COPY-READY contract. The diagnostic pair may legitimately carry a component that is not pasteable (redaction tag, ``…`` cap) or that the ``oauth_endpoints.json`` loader would refuse (``localhost``, an IP literal, a percent-escape in the - path) or that the gate would never honour (``http``, an explicit port). A - card that says "add THIS to oauth_endpoints.json" must hand back a string - only when adding it would actually work. Every signature the helper judges - is enumerated here with its verdict, so a widened or narrowed rule shows up - as a specific row rather than a vague failure. + path); and a URL may be rejected for a reason the allowlist cannot clear + (a fixed credential, a fragment, path parameters, ``http``, a port). A card + that says "add THIS to oauth_endpoints.json" must hand back a string only + when adding it would actually work. Every signature the helper judges is + enumerated here with its verdict, so a widened or narrowed rule shows up as + a specific row rather than a vague failure. """ GITHUB_TOKEN = "ghp_" "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef12" + Q = _long_state_query() @pytest.mark.parametrize( ("url", "expected"), [ + ("https://idp.example.com/authorize" + Q, "idp.example.com/authorize"), ( - "https://idp.example.com/authorize?state=x&code_challenge=y", - "idp.example.com/authorize", + "https://IdP.Example.COM/Realms/Dev/Authorize" + Q, + "idp.example.com/Realms/Dev/Authorize", ), + ("https://idp.example.com" + Q, "idp.example.com/"), + ("https://bücher.example/authorize" + Q, "xn--bcher-kva.example/authorize"), + # Operator-extension shapes the loader exists for: an Okta org, an + # Auth0 tenant, a Keycloak realm, a tenant-scoped Entra path. ( - "https://idp.example.com/authorize?access_token=AKIAIOSFODNN7EXAMPLE", - "idp.example.com/authorize", + "https://dev-123456.okta.com/oauth2/default/v1/authorize" + Q, + "dev-123456.okta.com/oauth2/default/v1/authorize", ), + ("https://acme.us.auth0.com/authorize" + Q, "acme.us.auth0.com/authorize"), ( - "https://IdP.Example.COM/Realms/Dev/Authorize", - "idp.example.com/Realms/Dev/Authorize", + "https://idp.example.com/realms/dev/protocol/openid-connect/auth" + Q, + "idp.example.com/realms/dev/protocol/openid-connect/auth", ), - ("https://idp.example.com", "idp.example.com/"), - ("https://idp.example.com/authorize#fragment-secret", "idp.example.com/authorize"), - ("https://bücher.example/authorize", "xn--bcher-kva.example/authorize"), ( - "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize", + "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize" + Q, "login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize", ), - # urlparse strips ``;params`` from the last segment, and the gate compares - # ``parsed.path`` the same way, so "/authorize" IS the entry that matches. - ("https://idp.example.com/authorize;v=1", "idp.example.com/authorize"), ], ids=[ - "plain-endpoint-query-dropped", - "credential-in-query-is-not-echoed", + "long-state-query-dropped", "host-lowercased-path-case-kept", "empty-path-becomes-slash", - "fragment-dropped", "idn-host-in-a-label-form", - "multi-segment-path", - "path-params-dropped-like-the-gate", + "okta-org", + "auth0-tenant", + "keycloak-realm", + "entra-tenant-path", ], ) def test_nameable_endpoints_come_back_as_host_slash_path(self, url: str, expected: str) -> None: assert sanitized_oauth_endpoint_display(url) == expected + @pytest.mark.parametrize( + ("name", "url", "endpoint"), + OPERATOR_EXTENSION_OAUTH_URLS, + ids=[name for name, _, _ in OPERATOR_EXTENSION_OAUTH_URLS], + ) + def test_the_operator_extension_corpus_is_named_verbatim( + self, name: str, url: str, endpoint: tuple[str, str] + ) -> None: + """The URLs the extension file exists for are exactly the ones the card + must name, and the string it names is the entry that fixes them.""" + host, path = endpoint + assert sanitized_oauth_endpoint_display(url) == f"{host}{path}" + @pytest.mark.parametrize( "url", [ @@ -3790,26 +3899,31 @@ def test_nameable_endpoints_come_back_as_host_slash_path(self, url: str, expecte "", "not a url at all", "https:///path-without-host", - f"https://{GITHUB_TOKEN}@idp.example.com/authorize", - "https://user%3Apass%40idp.example.com/authorize", - "https://AKIAIOSFODNN7EXAMPLE.example.com/authorize", + f"https://{GITHUB_TOKEN}@idp.example.com/authorize" + Q, + "https://user%3Apass%40idp.example.com/authorize" + Q, + "https://AKIAIOSFODNN7EXAMPLE.example.com/authorize" + Q, # -- pair is not pasteable: redaction tag / cap marker -- - "https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize", - "https://idp.example.com" + "/seg-ment" * 40, - "https://" + ".".join(["a" * 30] * 9) + ".example/authorize", + "https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize" + Q, + "https://idp.example.com" + "/seg-ment" * 40 + Q, + "https://" + ".".join(["a" * 30] * 9) + ".example/authorize" + Q, # -- the extension loader would refuse the host -- - "https://localhost/authorize", - "https://10.0.0.1/authorize", - "https://idp.example.com./authorize", - "https://idp/authorize", + "https://localhost/authorize" + Q, + "https://10.0.0.1/authorize" + Q, + "https://idp.example.com./authorize" + Q, + "https://idp/authorize" + Q, # -- the extension loader would refuse the path -- - "https://idp.example.com/auth%20orize", - "https://idp.example.com/../authorize", - "https://idp.example.com/auth\\orize", - # -- the gate would never grant the carve-out -- - "http://idp.example.com/authorize", - "https://idp.example.com:8443/authorize", - "https://idp.example.com:443/authorize", + "https://idp.example.com/auth%20orize" + Q, + "https://idp.example.com/../authorize" + Q, + "https://idp.example.com/auth\\orize" + Q, + # -- the allowlist could not clear the rejection -- + "https://idp.example.com/authorize?access_token=AKIAIOSFODNN7EXAMPLE", + "https://idp.example.com/authorize" + _long_state_query(extra="#frag"), + "https://idp.example.com/authorize;v=1" + Q, + "http://idp.example.com/authorize" + Q, + "https://idp.example.com:8443/authorize" + Q, + "https://idp.example.com:443/authorize" + Q, + # -- not rejected at all: nothing to name -- + "https://idp.example.com/authorize?state=x&code_challenge_method=S256", ], ids=[ "empty", @@ -3828,9 +3942,13 @@ def test_nameable_endpoints_come_back_as_host_slash_path(self, url: str, expecte "percent-escape-in-path", "dot-dot-in-path", "backslash-in-path", + "fixed-credential-in-query", + "fragment", + "path-params", "http-scheme", "explicit-port", "explicit-default-port", + "accepted-url", ], ) def test_unnameable_endpoints_return_none(self, url: str) -> None: @@ -3841,7 +3959,7 @@ def test_the_display_string_is_exactly_what_the_loader_would_accept(self) -> Non through the SAME validators the extension loader applies, so the two can only drift together.""" display = sanitized_oauth_endpoint_display( - "https://idp.example.com/realms/dev/protocol/openid-connect/auth?state=s" + "https://idp.example.com/realms/dev/protocol/openid-connect/auth" + self.Q ) assert display is not None host, _, rest = display.partition("/") @@ -3853,27 +3971,21 @@ def test_the_display_string_is_exactly_what_the_loader_would_accept(self) -> Non ) == frozenset({(host, path)}) def test_the_raw_url_and_its_query_never_appear_in_the_display(self) -> None: - url = ( - "https://idp.example.com/authorize" - "?client_id=abc&state=TOPSECRETSTATE&code_challenge=PKCEMATERIAL" - f"&access_token={self.GITHUB_TOKEN}" - ) + url = "https://idp.example.com/authorize" + self.Q display = sanitized_oauth_endpoint_display(url) assert display == "idp.example.com/authorize" - for secret in ("TOPSECRETSTATE", "PKCEMATERIAL", self.GITHUB_TOKEN, "client_id", "?"): + for secret in ("a1B2c3D4", "E9Melhoa2Owv", "client_id", "?", "https://"): assert secret not in display def test_a_redacted_path_is_refused_rather_than_joined(self) -> None: # The diagnostic pair is (host, tag): the tag must never be glued onto # the host as if it were a path a user could type. - pair = sanitized_oauth_endpoint("https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize") - assert pair == ("idp.example.com", security._REDACTED_CREDENTIAL_TAG) - assert ( - sanitized_oauth_endpoint_display( - "https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize" - ) - is None + url = "https://idp.example.com/AKIAIOSFODNN7EXAMPLE/authorize" + self.Q + assert sanitized_oauth_endpoint(url) == ( + "idp.example.com", + security._REDACTED_CREDENTIAL_TAG, ) + assert sanitized_oauth_endpoint_display(url) is None class TestOperatorOAuthEndpointExtension: diff --git a/website/scripts/capture-connections-mint-rejected-endpoint.mjs b/website/scripts/capture-connections-mint-rejected-endpoint.mjs index a8e6915260f6..4116f5ab9025 100644 --- a/website/scripts/capture-connections-mint-rejected-endpoint.mjs +++ b/website/scripts/capture-connections-mint-rejected-endpoint.mjs @@ -8,13 +8,16 @@ * The scene is the Notion card walked through one real connect whose mint ends * in `failed` / `mint_url_rejected`. Two frames, each from a fresh page: * - * 1. `rejected_endpoint` present -- the card names the endpoint the gate - * refused and points at oauth_endpoints.json; - * 2. `rejected_endpoint` absent -- the card keeps its unnamed message. + * 1. `rejected_endpoint` present -- the error line names the endpoint the + * gate refused, a second line carries the oauth_endpoints.json remedy, + * and a Documentation link points at the allowlist guide section; + * 2. `rejected_endpoint` absent -- the card keeps its unnamed message, with + * no remedy line and no link. * * Before each shot the harness asserts the copy it expects is on screen, that - * no first-run dialog covers the card, and that nothing from the rejected URL - * beyond host+path (scheme, query, token) ever reached the page text. + * the link (when expected) resolves to the guide anchor, that no first-run + * dialog covers the card, and that nothing from the rejected URL beyond + * host+path (scheme, query, token) ever reached the page text. * * Usage: node scripts/capture-connections-mint-rejected-endpoint.mjs [outDir] */ @@ -26,6 +29,7 @@ import { json, logPageProblems, stubDashboardApi } from './lib/stub-dashboard-ap const OUT = process.argv[2] || '../temp-screenshots/connections-mint-rejected-endpoint' const SLUG = 'notion' const ENDPOINT = 'auth.example-idp.com/realms/dev/authorize' +const GUIDE_URL = 'https://github.com/kirodotdev/KiroCrew/blob/main/docs/guides/connecting-remote-oauth-mcp-server.md#if-the-host-is-not-recognized-the-oauth-endpoint-allowlist' /** Strings from the rejected URL that must NEVER appear on the card. */ const NEVER_ON_SCREEN = ['https://', 'access_token', 'AKIAIOSFODNN7EXAMPLE', 'code_challenge', '?'] @@ -43,7 +47,7 @@ const entry = () => ({ kirocrewManaged: true, }) -async function frame(browser, base, { name, endpoint, expectText, forbidText }) { +async function frame(browser, base, { name, endpoint, expectText, expectAlso = [], forbidText, expectLink }) { const context = await browser.newContext({ viewport: { width: 1400, height: 880 }, deviceScaleFactor: 1 }) const page = await context.newPage() logPageProblems(page) @@ -96,7 +100,17 @@ async function frame(browser, base, { name, endpoint, expectText, forbidText }) for (const never of [...NEVER_ON_SCREEN, ...forbidText]) { if (text.includes(never)) throw new Error(`${name}: card text carries ${JSON.stringify(never)}`) } - if (!text.includes(expectText)) throw new Error(`${name}: card text lacks ${JSON.stringify(expectText)}`) + for (const want of [expectText, ...expectAlso]) { + if (!text.includes(want)) throw new Error(`${name}: card text lacks ${JSON.stringify(want)}`) + } + const docLinks = card.getByRole('link', { name: /Documentation/ }) + if (expectLink) { + await docLinks.first().waitFor({ state: 'visible', timeout: 20000 }) + const href = await docLinks.first().getAttribute('href') + if (href !== expectLink) throw new Error(`${name}: Documentation link points at ${href}`) + } else if (await docLinks.count()) { + throw new Error(`${name}: a Documentation link rendered without an endpoint to act on`) + } await page.waitForTimeout(400) await card.screenshot({ path: `${OUT}/${name}.png` }) console.log('wrote', `${OUT}/${name}.png`) @@ -110,14 +124,16 @@ async function main() { await frame(browser, base, { name: '1-card-rejected-endpoint-named', endpoint: ENDPOINT, - expectText: `The authorization endpoint ${ENDPOINT} looked like it carried a credential`, - forbidText: ['so it was not displayed'], + expectText: `The approval address from ${ENDPOINT} looked like it carried a credential`, + expectAlso: [`If ${ENDPOINT} is a trusted identity provider`, 'oauth_endpoints.json'], + forbidText: ['containing credential-like data'], + expectLink: GUIDE_URL, }) await frame(browser, base, { name: '2-card-rejected-endpoint-unnamed-fallback', endpoint: undefined, expectText: 'containing credential-like data, so it was not displayed', - forbidText: [ENDPOINT, 'oauth_endpoints.json'], + forbidText: [ENDPOINT, 'oauth_endpoints.json', 'identity provider'], }) } finally { await browser.close() diff --git a/website/src/i18n/locales/bn.json b/website/src/i18n/locales/bn.json index dcbf2699e7c3..8f2d94841401 100644 --- a/website/src/i18n/locales/bn.json +++ b/website/src/i18n/locales/bn.json @@ -10900,7 +10900,8 @@ "mint_failure_timed_out": "অনুমোদনের ঠিকানা প্রস্তুত হওয়ার আগেই অনুমোদন সেটআপের সময় শেষ হয়েছে। আবার সংযোগ করার চেষ্টা করুন।", "mint_failure_unknown": "অনুমোদনের ঠিকানা প্রস্তুত হওয়ার আগেই অনুমোদন সেটআপ ব্যর্থ হয়েছে। আবার সংযোগ করার চেষ্টা করুন।", "mint_failure_url_rejected": "প্রদানকারী এমন একটি অনুমোদনের ঠিকানা ফিরিয়েছে যাতে শংসাপত্রের মতো ডেটা ছিল, তাই সেটি দেখানো হয়নি।", - "mint_failure_url_rejected_endpoint": "অনুমোদন এন্ডপয়েন্ট {{endpoint}} দেখে মনে হয়েছে এতে শংসাপত্র রয়েছে, তাই এটি প্রত্যাখ্যান করা হয়েছে। এটি যদি এমন একটি বিশ্বস্ত পরিচয় প্রদানকারী হয় যা {{productName}} চেনে না, তবে {{productName}} ডেটা হোমে থাকা oauth_endpoints.json-এ {{endpoint}} যোগ করো (কী লিখতে হবে তা docs/guides/connecting-remote-oauth-mcp-server.md-এ দেখো)। না হলে সার্ভার মালিককে URL ঠিক করতে বলো।", + "mint_failure_url_rejected_endpoint": "{{endpoint}} থেকে আসা অনুমোদনের ঠিকানায় শংসাপত্র রয়েছে বলে মনে হয়েছে, তাই সেটি দেখানো হয়নি।", + "mint_failure_url_rejected_endpoint_detail": "{{endpoint}} যদি এমন একটি বিশ্বস্ত পরিচয় প্রদানকারী হয় যা {{productName}} চেনে না, তবে এটি oauth_endpoints.json-এ যোগ করো (কোথায় ও কীভাবে, তা ডকুমেন্টেশন লিঙ্কে দেখো)। না হলে যে সার্ভারটি চালায় তাকে URL ঠিক করতে বলো।", "needs_attention": "মনোযোগ প্রয়োজন", "no_matching_services": "এই অনুসন্ধানের সাথে কোনো পরিষেবা মেলেনি।", "not_connected": "সংযুক্ত নয়", diff --git a/website/src/i18n/locales/de.json b/website/src/i18n/locales/de.json index 6e5cd4771b24..96fe85111be4 100644 --- a/website/src/i18n/locales/de.json +++ b/website/src/i18n/locales/de.json @@ -10900,7 +10900,8 @@ "mint_failure_timed_out": "Beim Einrichten der Autorisierung wurde das Zeitlimit erreicht, bevor die Freigabeadresse bereit war. Versuche erneut, eine Verbindung herzustellen.", "mint_failure_unknown": "Die Autorisierung konnte nicht eingerichtet werden, bevor die Freigabeadresse bereit war. Versuche erneut, eine Verbindung herzustellen.", "mint_failure_url_rejected": "Der Anbieter hat eine Freigabeadresse mit Daten zurückgegeben, die wie Zugangsdaten aussehen. Daher wurde sie nicht angezeigt.", - "mint_failure_url_rejected_endpoint": "Der Autorisierungsendpunkt {{endpoint}} sah aus, als enthielte er Zugangsdaten, und wurde daher abgelehnt. Wenn es sich um einen vertrauenswürdigen Identitätsanbieter handelt, den {{productName}} nicht kennt, trage {{endpoint}} in die Datei oauth_endpoints.json im {{productName}}-Datenverzeichnis ein (den Eintrag zeigt docs/guides/connecting-remote-oauth-mcp-server.md). Andernfalls bitte den Serverbetreiber, die URL zu korrigieren.", + "mint_failure_url_rejected_endpoint": "Die Freigabeadresse von {{endpoint}} sah aus, als enthielte sie Zugangsdaten. Daher wurde sie nicht angezeigt.", + "mint_failure_url_rejected_endpoint_detail": "Wenn {{endpoint}} ein vertrauenswürdiger Identitätsanbieter ist, den {{productName}} nicht kennt, trage ihn in oauth_endpoints.json ein (wo und wie, zeigt der Dokumentationslink). Andernfalls bitte die Person, die diesen Server betreibt, die URL zu korrigieren.", "needs_attention": "Aktion erforderlich", "no_matching_services": "Keine Dienste entsprechen dieser Suche.", "not_connected": "Nicht verbunden", diff --git a/website/src/i18n/locales/en-XA.json b/website/src/i18n/locales/en-XA.json index ca22e80cd796..4ddd3aa962e1 100644 --- a/website/src/i18n/locales/en-XA.json +++ b/website/src/i18n/locales/en-XA.json @@ -15439,7 +15439,8 @@ "mint_failure_timed_out": "[Àùţĥøŕìžàţìøñ şèţùþ ţìɱèð øùţ ƀèƒøŕè àñ àþþŕøṽàĺ àððŕèşş ẁàş ŕèàðý. Ţŕý çøññèçţìñğ àğàìñ. ···························]", "mint_failure_unknown": "[Àùţĥøŕìžàţìøñ şèţùþ ƒàìĺèð ƀèƒøŕè àñ àþþŕøṽàĺ àððŕèşş ẁàş ŕèàðý. Ţŕý çøññèçţìñğ àğàìñ. ··························]", "mint_failure_url_rejected": "[Ţĥè þŕøṽìðèŕ ŕèţùŕñèð àñ àþþŕøṽàĺ àððŕèşş çøñţàìñìñğ çŕèðèñţìàĺ-ĺìķè ðàţà, şø ìţ ẁàş ñøţ ðìşþĺàýèð. ······························]", - "mint_failure_url_rejected_endpoint": "[Ţĥè àùţĥøŕìžàţìøñ èñðþøìñţ {{endpoint}} ĺøøķèð ĺìķè ìţ çàŕŕìèð à çŕèðèñţìàĺ, şø ìţ ẁàş ŕèĵèçţèð. ̃ ìţ ìş à ţŕùşţèð ìðèñţìţý þŕøṽìðèŕ ţĥàţ {{productName}} ðøèş ñøţ ŕèçøğñìžè, àðð {{endpoint}} ţø øàùţĥ_èñðþøìñţş.ĵşøñ ìñ ţĥè {{productName}} ðàţà ĥøɱè (ðøçş/ğùìðèş/çøññèçţìñğ-ŕèɱøţè-øàùţĥ-ɱçþ-şèŕṽèŕ.ɱð şĥøẁş ţĥè èñţŕý ţø ẁŕìţè). Øţĥèŕẁìşè àşķ ţĥè şèŕṽèŕ øẁñèŕ ţø ƒìẋ ţĥè ÙŔĹ. ································································································]", + "mint_failure_url_rejected_endpoint": "[Ţĥè àþþŕøṽàĺ àððŕèşş ƒŕøɱ {{endpoint}} ĺøøķèð ĺìķè ìţ çàŕŕìèð à çŕèðèñţìàĺ, şø ìţ ẁàş ñøţ ðìşþĺàýèð. ··························]", + "mint_failure_url_rejected_endpoint_detail": "[̃ {{endpoint}} ìş à ţŕùşţèð ìðèñţìţý þŕøṽìðèŕ ţĥàţ {{productName}} ðøèş ñøţ ŕèçøğñìžè, àðð ìţ ţø øàùţĥ_èñðþøìñţş.ĵşøñ (ţĥè Ðøçùɱèñţàţìøñ ĺìñķ şĥøẁş ẁĥèŕè àñð ĥøẁ). Øţĥèŕẁìşè àşķ ẁĥøèṽèŕ ŕùñş ţĥàţ şèŕṽèŕ ţø ƒìẋ ţĥè ÙŔĹ. ··························································]", "needs_attention": "[Ñèèðş àţţèñţìøñ ··············]", "no_matching_services": "[Ñø şèŕṽìçèş ɱàţçĥ ţĥìş şèàŕçĥ. ·····················]", "not_connected": "[Ñøţ çøññèçţèð ············]", diff --git a/website/src/i18n/locales/en.manual.json b/website/src/i18n/locales/en.manual.json index 449bb7e3d86c..b118a77b49cb 100644 --- a/website/src/i18n/locales/en.manual.json +++ b/website/src/i18n/locales/en.manual.json @@ -4622,7 +4622,8 @@ "mint_failure_timed_out": "Authorization setup timed out before an approval address was ready. Try connecting again.", "mint_failure_unknown": "Authorization setup failed before an approval address was ready. Try connecting again.", "mint_failure_url_rejected": "The provider returned an approval address containing credential-like data, so it was not displayed.", - "mint_failure_url_rejected_endpoint": "The authorization endpoint {{endpoint}} looked like it carried a credential, so it was rejected. If it is a trusted identity provider that {{productName}} does not recognize, add {{endpoint}} to oauth_endpoints.json in the {{productName}} data home (docs/guides/connecting-remote-oauth-mcp-server.md shows the entry to write). Otherwise ask the server owner to fix the URL.", + "mint_failure_url_rejected_endpoint": "The approval address from {{endpoint}} looked like it carried a credential, so it was not displayed.", + "mint_failure_url_rejected_endpoint_detail": "If {{endpoint}} is a trusted identity provider that {{productName}} does not recognize, add it to oauth_endpoints.json (the Documentation link shows where and how). Otherwise ask whoever runs that server to fix the URL.", "needs_attention": "Needs attention", "no_matching_services": "No services match this search.", "not_connected": "Not connected", diff --git a/website/src/i18n/locales/es.json b/website/src/i18n/locales/es.json index 0728dc1ef2e7..b08dcc87b056 100644 --- a/website/src/i18n/locales/es.json +++ b/website/src/i18n/locales/es.json @@ -11059,7 +11059,8 @@ "mint_failure_timed_out": "La configuración de autorización agotó el tiempo de espera antes de que la dirección de aprobación estuviera lista. Intenta conectarte de nuevo.", "mint_failure_unknown": "La configuración de autorización falló antes de que la dirección de aprobación estuviera lista. Intenta conectarte de nuevo.", "mint_failure_url_rejected": "El proveedor devolvió una dirección de aprobación que contenía datos similares a credenciales, por lo que no se mostró.", - "mint_failure_url_rejected_endpoint": "El punto de conexión de autorización {{endpoint}} parecía contener una credencial, así que se rechazó. Si es un proveedor de identidad de confianza que {{productName}} no reconoce, añade {{endpoint}} a oauth_endpoints.json en el directorio de datos de {{productName}} (docs/guides/connecting-remote-oauth-mcp-server.md muestra la entrada que hay que escribir). Si no, pide al propietario del servidor que corrija la URL.", + "mint_failure_url_rejected_endpoint": "La dirección de aprobación de {{endpoint}} parecía contener una credencial, por lo que no se mostró.", + "mint_failure_url_rejected_endpoint_detail": "Si {{endpoint}} es un proveedor de identidad de confianza que {{productName}} no reconoce, añádelo a oauth_endpoints.json (el enlace de documentación muestra dónde y cómo). Si no, pide a quien administre ese servidor que corrija la URL.", "needs_attention": "Requiere atención", "no_matching_services": "Ningún servicio coincide con esta búsqueda.", "not_connected": "No conectado", diff --git a/website/src/i18n/locales/fr.json b/website/src/i18n/locales/fr.json index cf54e6cd8a5d..60115496866d 100644 --- a/website/src/i18n/locales/fr.json +++ b/website/src/i18n/locales/fr.json @@ -11059,7 +11059,8 @@ "mint_failure_timed_out": "La configuration de l’autorisation a expiré avant que l’adresse d’approbation soit prête. Réessayez de vous connecter.", "mint_failure_unknown": "La configuration de l’autorisation a échoué avant que l’adresse d’approbation soit prête. Réessayez de vous connecter.", "mint_failure_url_rejected": "Le fournisseur a renvoyé une adresse d’approbation contenant des données ressemblant à des identifiants. Elle n’a donc pas été affichée.", - "mint_failure_url_rejected_endpoint": "Le point de terminaison d’autorisation {{endpoint}} semblait contenir un identifiant, il a donc été refusé. S’il s’agit d’un fournisseur d’identité de confiance que {{productName}} ne reconnaît pas, ajoute {{endpoint}} au fichier oauth_endpoints.json dans le dossier de données de {{productName}} (docs/guides/connecting-remote-oauth-mcp-server.md montre l’entrée à écrire). Sinon, demande au propriétaire du serveur de corriger l’URL.", + "mint_failure_url_rejected_endpoint": "L’adresse d’approbation de {{endpoint}} semblait contenir un identifiant. Elle n’a donc pas été affichée.", + "mint_failure_url_rejected_endpoint_detail": "Si {{endpoint}} est un fournisseur d’identité de confiance que {{productName}} ne reconnaît pas, ajoute-le à oauth_endpoints.json (le lien Documentation indique où et comment). Sinon, demande à la personne qui gère ce serveur de corriger l’URL.", "needs_attention": "Action requise", "no_matching_services": "Aucun service ne correspond à cette recherche.", "not_connected": "Non connecté", diff --git a/website/src/i18n/locales/hi.json b/website/src/i18n/locales/hi.json index 97c8a9fb8c58..b53ba12595a4 100644 --- a/website/src/i18n/locales/hi.json +++ b/website/src/i18n/locales/hi.json @@ -10900,7 +10900,8 @@ "mint_failure_timed_out": "मंज़ूरी का पता तैयार होने से पहले प्राधिकरण सेटअप का समय समाप्त हो गया। फिर से कनेक्ट करने की कोशिश करें।", "mint_failure_unknown": "मंज़ूरी का पता तैयार होने से पहले प्राधिकरण सेटअप विफल हो गया। फिर से कनेक्ट करने की कोशिश करें।", "mint_failure_url_rejected": "प्रदाता ने ऐसा मंज़ूरी पता लौटाया जिसमें क्रेडेंशियल जैसा डेटा था, इसलिए उसे नहीं दिखाया गया।", - "mint_failure_url_rejected_endpoint": "प्राधिकरण एंडपॉइंट {{endpoint}} में क्रेडेंशियल जैसा कुछ दिखा, इसलिए उसे अस्वीकार कर दिया गया। अगर यह कोई भरोसेमंद पहचान प्रदाता है जिसे {{productName}} नहीं पहचानता, तो {{productName}} डेटा होम में oauth_endpoints.json में {{endpoint}} जोड़ो (क्या लिखना है, यह docs/guides/connecting-remote-oauth-mcp-server.md में देखो)। नहीं तो सर्वर मालिक से URL ठीक करने को कहो।", + "mint_failure_url_rejected_endpoint": "{{endpoint}} से आए मंज़ूरी पते में क्रेडेंशियल जैसा कुछ दिखा, इसलिए उसे नहीं दिखाया गया।", + "mint_failure_url_rejected_endpoint_detail": "अगर {{endpoint}} कोई भरोसेमंद पहचान प्रदाता है जिसे {{productName}} नहीं पहचानता, तो उसे oauth_endpoints.json में जोड़ो (कहाँ और कैसे, यह दस्तावेज़ लिंक में देखो)। नहीं तो जो उस सर्वर को चलाता है, उससे URL ठीक करने को कहो।", "needs_attention": "ध्यान देने की ज़रूरत", "no_matching_services": "इस खोज से कोई सेवा मेल नहीं खाती।", "not_connected": "कनेक्टेड नहीं", diff --git a/website/src/i18n/locales/it.json b/website/src/i18n/locales/it.json index 9891cba81eea..2acd4875dbc3 100644 --- a/website/src/i18n/locales/it.json +++ b/website/src/i18n/locales/it.json @@ -11059,7 +11059,8 @@ "mint_failure_timed_out": "La configurazione dell’autorizzazione è scaduta prima che l’indirizzo di approvazione fosse pronto. Prova a connetterti di nuovo.", "mint_failure_unknown": "La configurazione dell’autorizzazione non è riuscita prima che l’indirizzo di approvazione fosse pronto. Prova a connetterti di nuovo.", "mint_failure_url_rejected": "Il provider ha restituito un indirizzo di approvazione contenente dati simili a credenziali, quindi non è stato mostrato.", - "mint_failure_url_rejected_endpoint": "L’endpoint di autorizzazione {{endpoint}} sembrava contenere una credenziale, quindi è stato rifiutato. Se è un provider di identità affidabile che {{productName}} non riconosce, aggiungi {{endpoint}} a oauth_endpoints.json nella cartella dati di {{productName}} (docs/guides/connecting-remote-oauth-mcp-server.md mostra la voce da scrivere). Altrimenti chiedi al proprietario del server di correggere l’URL.", + "mint_failure_url_rejected_endpoint": "L’indirizzo di approvazione di {{endpoint}} sembrava contenere una credenziale, quindi non è stato mostrato.", + "mint_failure_url_rejected_endpoint_detail": "Se {{endpoint}} è un provider di identità affidabile che {{productName}} non riconosce, aggiungilo a oauth_endpoints.json (il link alla documentazione mostra dove e come). Altrimenti chiedi a chi gestisce quel server di correggere l’URL.", "needs_attention": "Richiede attenzione", "no_matching_services": "Nessun servizio corrisponde alla ricerca.", "not_connected": "Non connesso", diff --git a/website/src/i18n/locales/ja.json b/website/src/i18n/locales/ja.json index b16f382edb92..8c9a8fe7f746 100644 --- a/website/src/i18n/locales/ja.json +++ b/website/src/i18n/locales/ja.json @@ -10741,7 +10741,8 @@ "mint_failure_timed_out": "承認アドレスの準備ができる前に、認証の設定がタイムアウトしました。もう一度接続してください。", "mint_failure_unknown": "承認アドレスの準備ができる前に、認証の設定に失敗しました。もう一度接続してください。", "mint_failure_url_rejected": "プロバイダーから認証情報のようなデータを含む承認アドレスが返されたため、表示しませんでした。", - "mint_failure_url_rejected_endpoint": "認可エンドポイント「{{endpoint}}」に認証情報が含まれているように見えたため、拒否しました。{{productName}} が認識していない信頼できる ID プロバイダーであれば、{{productName}} のデータホームにある oauth_endpoints.json に「{{endpoint}}」を追加してください(書き方は docs/guides/connecting-remote-oauth-mcp-server.md を参照)。そうでなければ、サーバーの所有者に URL の修正を依頼してください。", + "mint_failure_url_rejected_endpoint": "「{{endpoint}}」からの承認アドレスに認証情報が含まれているように見えたため、表示しませんでした。", + "mint_failure_url_rejected_endpoint_detail": "「{{endpoint}}」が {{productName}} の認識していない信頼できる ID プロバイダーであれば、oauth_endpoints.json に追加してください(場所と書き方はドキュメントのリンクを参照)。そうでなければ、そのサーバーを運用している人に URL の修正を依頼してください。", "needs_attention": "注意が必要", "no_matching_services": "この検索に一致するサービスはありません。", "not_connected": "接続されていません", diff --git a/website/src/i18n/locales/ko.json b/website/src/i18n/locales/ko.json index efc8a6d1cc8a..5c588189d01f 100644 --- a/website/src/i18n/locales/ko.json +++ b/website/src/i18n/locales/ko.json @@ -10741,7 +10741,8 @@ "mint_failure_timed_out": "승인 주소가 준비되기 전에 인증 설정 시간이 초과되었습니다. 다시 연결해 보세요.", "mint_failure_unknown": "승인 주소가 준비되기 전에 인증 설정에 실패했습니다. 다시 연결해 보세요.", "mint_failure_url_rejected": "공급자가 자격 증명과 유사한 데이터가 포함된 승인 주소를 반환하여 표시하지 않았습니다.", - "mint_failure_url_rejected_endpoint": "인증 엔드포인트 ‘{{endpoint}}’에 자격 증명이 포함된 것처럼 보여 거부했습니다. {{productName}}이(가) 인식하지 못하는 신뢰할 수 있는 ID 공급자라면 {{productName}} 데이터 홈의 oauth_endpoints.json에 ‘{{endpoint}}’을(를) 추가하세요(작성할 항목은 docs/guides/connecting-remote-oauth-mcp-server.md 참고). 그렇지 않다면 서버 소유자에게 URL 수정을 요청하세요.", + "mint_failure_url_rejected_endpoint": "‘{{endpoint}}’에서 받은 승인 주소에 자격 증명이 포함된 것처럼 보여 표시하지 않았습니다.", + "mint_failure_url_rejected_endpoint_detail": "‘{{endpoint}}’이(가) {{productName}}이(가) 인식하지 못하는 신뢰할 수 있는 ID 공급자라면 oauth_endpoints.json에 추가하세요(위치와 작성법은 문서 링크 참고). 그렇지 않다면 해당 서버를 운영하는 사람에게 URL 수정을 요청하세요.", "needs_attention": "확인 필요", "no_matching_services": "이 검색과 일치하는 서비스가 없습니다.", "not_connected": "연결되지 않음", diff --git a/website/src/i18n/locales/pt.json b/website/src/i18n/locales/pt.json index 0b70103f9bda..1d51ec38ee95 100644 --- a/website/src/i18n/locales/pt.json +++ b/website/src/i18n/locales/pt.json @@ -11059,7 +11059,8 @@ "mint_failure_timed_out": "A configuração da autorização atingiu o tempo limite antes que o endereço de aprovação estivesse pronto. Tente conectar novamente.", "mint_failure_unknown": "A configuração da autorização falhou antes que o endereço de aprovação estivesse pronto. Tente conectar novamente.", "mint_failure_url_rejected": "O provedor retornou um endereço de aprovação com dados semelhantes a credenciais, por isso ele não foi exibido.", - "mint_failure_url_rejected_endpoint": "O endpoint de autorização {{endpoint}} parecia conter uma credencial, por isso foi rejeitado. Se for um provedor de identidade confiável que o {{productName}} não reconhece, adicione {{endpoint}} ao oauth_endpoints.json na pasta de dados do {{productName}} (docs/guides/connecting-remote-oauth-mcp-server.md mostra a entrada a escrever). Caso contrário, peça ao dono do servidor para corrigir a URL.", + "mint_failure_url_rejected_endpoint": "O endereço de aprovação de {{endpoint}} parecia conter uma credencial, por isso ele não foi exibido.", + "mint_failure_url_rejected_endpoint_detail": "Se {{endpoint}} for um provedor de identidade confiável que o {{productName}} não reconhece, adicione-o ao oauth_endpoints.json (o link de documentação mostra onde e como). Caso contrário, peça a quem administra esse servidor para corrigir a URL.", "needs_attention": "Requer atenção", "no_matching_services": "Nenhum serviço corresponde a esta busca.", "not_connected": "Não conectado", diff --git a/website/src/i18n/locales/ru.json b/website/src/i18n/locales/ru.json index b36988d8a356..b6ba27e1c941 100644 --- a/website/src/i18n/locales/ru.json +++ b/website/src/i18n/locales/ru.json @@ -11218,7 +11218,8 @@ "mint_failure_timed_out": "Время настройки авторизации истекло до того, как адрес подтверждения был готов. Попробуйте подключиться снова.", "mint_failure_unknown": "Настройка авторизации завершилась ошибкой до того, как адрес подтверждения был готов. Попробуйте подключиться снова.", "mint_failure_url_rejected": "Поставщик вернул адрес подтверждения с данными, похожими на учетные данные, поэтому адрес не был показан.", - "mint_failure_url_rejected_endpoint": "Конечная точка авторизации {{endpoint}} выглядела так, будто содержит учетные данные, поэтому она отклонена. Если это доверенный поставщик удостоверений, которого {{productName}} не знает, добавь {{endpoint}} в oauth_endpoints.json в каталоге данных {{productName}} (какую запись писать, показано в docs/guides/connecting-remote-oauth-mcp-server.md). Иначе попроси владельца сервера исправить URL.", + "mint_failure_url_rejected_endpoint": "Адрес подтверждения от {{endpoint}} выглядел так, будто содержит учетные данные, поэтому он не был показан.", + "mint_failure_url_rejected_endpoint_detail": "Если {{endpoint}} — доверенный поставщик удостоверений, которого {{productName}} не знает, добавь его в oauth_endpoints.json (где и как — по ссылке на документацию). Иначе попроси того, кто отвечает за этот сервер, исправить URL.", "needs_attention": "Требует внимания", "no_matching_services": "Нет сервисов, соответствующих поиску.", "not_connected": "Не подключено", diff --git a/website/src/i18n/locales/zh-CN.json b/website/src/i18n/locales/zh-CN.json index d5c27660cbb1..733628d6fcd7 100644 --- a/website/src/i18n/locales/zh-CN.json +++ b/website/src/i18n/locales/zh-CN.json @@ -10741,7 +10741,8 @@ "mint_failure_timed_out": "授权设置在批准地址准备好之前超时。请重试连接。", "mint_failure_unknown": "授权设置在批准地址准备好之前失败。请重试连接。", "mint_failure_url_rejected": "服务商返回的批准地址包含类似凭据的数据,因此未予显示。", - "mint_failure_url_rejected_endpoint": "授权端点 {{endpoint}} 看起来带有凭据,因此已被拒绝。如果它是 {{productName}} 尚未识别但可信的身份提供方,请把 {{endpoint}} 添加到 {{productName}} 数据目录中的 oauth_endpoints.json(条目写法见 docs/guides/connecting-remote-oauth-mcp-server.md)。否则,请让服务器所有者修正该 URL。", + "mint_failure_url_rejected_endpoint": "来自 {{endpoint}} 的批准地址看起来带有凭据,因此未予显示。", + "mint_failure_url_rejected_endpoint_detail": "如果 {{endpoint}} 是 {{productName}} 尚未识别但可信的身份提供方,请把它添加到 oauth_endpoints.json(位置与写法见文档链接)。否则,请让运行该服务器的人修正该 URL。", "needs_attention": "需要处理", "no_matching_services": "没有与搜索匹配的服务。", "not_connected": "未连接", diff --git a/website/src/pages/connections/ConnectionsPage.tsx b/website/src/pages/connections/ConnectionsPage.tsx index eb882b1a04f9..6611f1ed17e6 100644 --- a/website/src/pages/connections/ConnectionsPage.tsx +++ b/website/src/pages/connections/ConnectionsPage.tsx @@ -44,6 +44,12 @@ const MINT_POLL_MS = 2_000 * a grant completed outside the dashboard and keep connected-since fresh. */ const CONNECTION_STATUS_POLL_MS = 30_000 +/** The guide section that shows the oauth_endpoints.json entry a refused + * approval address needs. Linked from the mint_url_rejected feedback via + * `Feedback.help`, so the card's remedy ends in a link rather than a bare path. */ +const OAUTH_ENDPOINT_ALLOWLIST_GUIDE_URL = + 'https://github.com/kirodotdev/KiroCrew/blob/main/docs/guides/connecting-remote-oauth-mcp-server.md#if-the-host-is-not-recognized-the-oauth-endpoint-allowlist' + export type ConnectionCardState = | 'not-connected' | 'waiting-for-approval' @@ -1435,6 +1441,8 @@ export default function ConnectionsPage({ servicesEnabled = false }: { servicesE const next = { ...current } for (const { slug, reason, endpoint } of mintFailures) { let error: string + let detail: string | undefined + let help: Feedback['help'] switch (reason) { case 'mint_timeouterror': error = t('pages.connectionsPage.mint_failure_timed_out') @@ -1446,12 +1454,19 @@ export default function ConnectionsPage({ servicesEnabled = false }: { servicesE error = t('pages.connectionsPage.mint_failure_server_absent') break case 'mint_url_rejected': - // Name WHICH endpoint was refused when the backend could reduce - // it to a copy-ready host/path; otherwise keep the unnamed - // message rather than show a remedy that cannot work. - error = endpoint - ? t('pages.connectionsPage.mint_failure_url_rejected_endpoint', { endpoint }) - : t('pages.connectionsPage.mint_failure_url_rejected') + // Name WHICH endpoint was refused when the backend could reduce it + // to a copy-ready host/path. The error line stays one sentence; + // the oauth_endpoints.json remedy rides `detail` (its own line) + // and the guide rides `help` (a link), so the alarm text does not + // swallow the instructions. Without an endpoint the card keeps + // its unnamed message rather than show a remedy that cannot work. + if (endpoint) { + error = t('pages.connectionsPage.mint_failure_url_rejected_endpoint', { endpoint }) + detail = t('pages.connectionsPage.mint_failure_url_rejected_endpoint_detail', { endpoint }) + help = { href: OAUTH_ENDPOINT_ALLOWLIST_GUIDE_URL } + } else { + error = t('pages.connectionsPage.mint_failure_url_rejected') + } break default: error = t('pages.connectionsPage.mint_failure_unknown') @@ -1459,6 +1474,8 @@ export default function ConnectionsPage({ servicesEnabled = false }: { servicesE next[slug] = { kind: 'error', text: t('pages.connectionsPage.action_failed', { error }), + ...(detail ? { detail } : {}), + ...(help ? { help } : {}), } } return next