Repository navigation
feat(mcp): Patchy reads clients' metadata documents and publishes its own authorization metadata - #880
Conversation
|
GPT-6.1-Sol (xhigh) review, three rounds Round 1, on 7eda271: one blocking, four should-fix. All fixed in fd374a4.
Round 2, on fd374a4: one blocking, one should-fix. Both fixed in 867c072.
Round 3, on 867c072: nothing blocking, no should-fix or nits. Sol also probed an already-closed scope, a close during blocked DNS with 20 waiters, and cancelling the first caller, and found no interleaving that leaves a waiter hanging. It confirmed the earlier rules still hold: address checks and pinning, no redirects, 200 only, 5,000 bytes, 5 s, header-based caching, errors never kept, 30 starts a minute, and one fetch per URL. Each round also confirmed DNS rebinding is handled (one lookup, connection pinned through Node's |
Acceptance: PASS with notesChecked Done means
Focused command: Additional probes against the head's service and disposable local HTTP servers: Golden journeys
Rollback answers: match the diff. This PR adds routes and in-memory state; it changes no migration, persisted shape, infrastructure or existing CLI contract. Reverting discards that state and removes discovery routes; cached discovery can outlast the routes for its advertised hour, as the PR explains. The previous release can still run. No Not run
Notes
|
2f28800 to
0a1da02
Compare
867c072 to
056b09a
Compare
0a1da02 to
2e06801
Compare
The Postgres integration's global-unicast check moves to @patchy/core, so the client metadata document fetcher refuses exactly the same addresses. Its test moves with it and adds the cloud metadata, IPv4-compatible, NAT64 local-use and Teredo forms. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… own authorization metadata Patchy serves the protected resource metadata for /mcp and its authorization server metadata: client ID metadata documents, auth method none, PKCE S256, the patches scope and iss, with no registration endpoint. Both are cacheable for an hour and open to any origin in production; a dev instance has no CORS and advertises its token endpoint on 127.0.0.1. ClientDocuments fetches the document a client id names: global unicast only, DNS resolved once and the connection pinned to the checked answer, no redirects, 200 only, 5,000 bytes and 5 seconds at most. It accepts a document whose client_id is the URL fetched and which offers none (the list first, then the single field), keeps it as its headers say within an hour, never keeps a failure, and holds to 30 starts a minute host-wide with one fetch per URL. redirectAllowed matches listed redirects exactly, and loopback ones on any port. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… and real redirects From Sol's first review: - Effect's Cache counted a running fetch as an entry and could evict it, so a second load started the same fetch again. ClientDocuments now keeps accepted documents and running fetches apart; the fetch belongs to the service. - A document needs client_name, as MCP requires, and every redirect it lists must be an absolute URI without a fragment. - A listed loopback redirect matches only when written canonically, so only the port varies. - Age counts against the default hour too, and freshness counts from the request. - Any dev instance advertises its token endpoint on 127.0.0.1, [::1] included. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…service ends every wait From Sol's second review: claiming a URL and starting its fetch now happen under one uninterruptible mask, so an interrupted load can't leave a claim with no fetch behind it. The waiters are settled by an observer on the fetch fiber, which also fires when the service's scope closes before the fetch has run. Co-Authored-By: Claude Opus 5.5 <[email protected]>
056b09a to
1dd34b1
Compare
…ge and refresh (#881) Stacked on #880 (ticket #848); merges with the rest of #833's stack, not alone. ## What changed An MCP client couldn't turn a person's consent into an agent connection: nothing answered `/oauth/authorize` or `/oauth/token`. Now Patchy is the authorization server. The person signs in before anything else happens. The request is checked before anything is shown. An approval records only a short-lived code. The client's code exchange creates the agent connection, and refresh rotates it. Closes #849 ## Look at - **Nobody is sent anywhere before signing in** (`packages/auth/src/OAuthEndpoints.ts`). `GET /oauth/authorize` signs the person in first. A refused request is explained on the page and never sent back to the client, because its redirect is vouched for only by a stranger's document (RFC 9700 §4.11.2). Only the person's own answer, Allow or Deny (#850), goes back to the client, with `iss` and `state`. An unsigned request even names `redirect_uri=https://evil.example/`: ``` GET /oauth/authorize?…&redirect_uri=https%3A%2F%2Fevil.example%2F (no session) → 401, the sign-in door; no Location header its sign-in link returns to https://patchy.example/oauth/authorize?… and nothing else no client document was fetched ``` - **The serialisations** (`packages/auth/src/Consents.ts`), each a race test in `Consents.test.ts` held open both ways round: - approval and the exchange hold #841's agent access lock (FOR SHARE), and off deletes the company's codes not yet exchanged in its own transaction (`Companies.setAgentAccess`), so off then on doesn't revive them; - a code is stamped with `clock_timestamp()` under the person's row lock, so one made at or before #838's stamp is dead. Disconnect everything and deactivation need no change; the stamp cancels their codes; - lock order is company, then the code's row, then the person's; - two exchanges of one code: the second ends what the first made, committed before `invalid_grant`. - **The token endpoint's failure limit counts failures only.** A failure past 60 a minute from one address is answered 429, and a successful exchange or refresh is never refused, even from a shared address. That's my reading of "counted on failures … so shared egress is never refused for being busy". The other reading refuses everything from an address once its failures are spent. The test `answers 429 to an address's failures past the limit, never to its successes` pins my reading. ## How it was verified - **Done means.** `apps/server/src/AgentConsent.test.ts` boots the whole server as a dev instance boots it: personas, a `<label>.localhost` origin, its token endpoint at `127.0.0.1`, and Claude Code's fixture document. It covers each Done means item: - The scripted client reads the metadata. Signed out, it gets only the sign-in door. It signs in as a persona, gets the consent page, approves through `Consents.approve`, exchanges with a loopback redirect on a random port and refreshes. - The `work` token is 401 on `/api/me`. - The replay ends the connection, so even the refreshed token stops working. - **With agent access off, nothing is issued:** `Consents.test.ts` › *with agent access off nothing is issued…* and both off races. - **The threat model as tests:** - PKCE downgrade (no method, `plain`, no challenge, or the challenge sent as the verifier); - `resource` and `redirect_uri` mix-ups; - a parameter sent twice; - code injection across accounts (each code redeems only with its own verifier, as its own person); - a refused exchange leaving the code to the request it was approved for; - expiry; - `iss` on approve and deny; - the per-address failure limit and the per-connection rotation limit; - CORS `*` without credentials in production, and none plus no preflight on a dev instance. - **Mutation check.** I removed the off deletion, the stamp check and the replay ending one at a time, and 8 of the then 12 Consents tests failed. - **A late replay** still ends its connection, after the code expired and after a sweep (`Consents.test.ts` › *a replay long after…*). - **Retries** within the minute don't spend the rotation limit (`OAuthEndpoints.test.ts` › *limits rotations per agent connection…*). - **Suites.** `pnpm typecheck` and eslint are clean. These all pass: - the auth suite (198 tests); - companies (55); - limits (25); - the server's AgentConsent, Server, ApiGuard, SweepSchedules and migrations suites. - **`pnpm verify`** passed on aeb26fd: format, lint, typecheck, synth, test, postgres-concurrency, cli-smoke, tier2-smoke and browser (81 specs). - **Rollback rehearsal:** `pnpm test:rollback-rehearsal --live e4243ff` passed, going e4243ff → fb827df → e4243ff → fb827df in 191 s. e4243ff is main's tip and has #837 and #838. CI's `rollback-rehearsal` job also passes on aeb26fd. - **Review:** GPT-6.1-Sol (xhigh) ran two rounds; see the review comment below. Round 1 had one blocking and two should-fix findings, all fixed in aeb26fd. Round 2 found nothing blocking. **Surfaces:** - the limits registry (`oauth.token.failures.perMinute`, `oauth.token.rotations.perMinute`), rendered into `docs/limits.md`; - the Auth glossary's *Consent*; - migration `0023_agent_consents`; - `ClientDocumentNetwork` now comes from the launcher (`start.ts` brings the pinned one, so a test can serve fixtures); - `AgentConnections.chainOf`, a lock-free read the token endpoint checks `client_id` and limits by before it calls #846's `refresh`. Untouched: - nothing changed in `packages/api`, so `docs/API.md` stands; - the CLI and the dev runner are unchanged; - `docs/DEVELOPMENT.md` gets its consent walkthrough with #850's page. **For #850:** the authorize page's success branch (`consentPage` in `OAuthEndpoints.ts`) is a placeholder heading. The consent page replaces it and adds the `POST` answer: re-run `Consents.check` on the form's fields, then `approve` or `deny`, which return the redirect. ## Release impact - [ ] **Breaking** — requires action from anyone already running this - [x] **Not breaking** — no action required Two new routes, a new table and two operating rows. Nothing existing changes shape. - **What does a revert leave behind?** The `agent_consents` table and any minute-long codes in it, and agent connections made through consent, which #846's tables already hold. - **Does the release before it still work with that?** Yes. Nothing before this reads `agent_consents`, and the release before keeps ending and refusing agent connections by #846's and #847's rules. Built by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code; reviewed and accepted by GPT-6.1-Sol (xhigh).
## What changed This PR adds release 17's What's new entry, written from `5dd94f3`. It covers everything merged since release 16's `through` (`dd3f41f`), and it sets the `patchy` release to `0.17.0` in `packages/patchy/package.json` and `CURRENT_RELEASE`. With this release, people's agents can use their company's patches through Patchy MCP (#833). | Change | PRs | | --- | --- | | New: Your AI agent can use your company's tools | #873, #878, #880, #881, #882, #883, #884, #886, #887 | | New: Admins choose whether agents can use the company's tools | #871 | | Improved: Your machines shows your agents too (Revoke all machines is now Disconnect everything) | #885, #879 | | New: See what agents can do with a tool | #876 | | New: The log says when an agent made a change | #888 | | New: Your agent can make a tool ready for agents | #869, #870, #872, #875, #896 | | Behind the scenes: agents' calls have their own limits, and a server only an agent uses rests a minute after its last call | #889, #892 | | Behind the scenes: New and Improved changes are public, for patchyhq.com | #893 | | Behind the scenes: library updates | #899 | Five merged PRs get no line: - #874 is release 16's own entry. - #894 is dev tooling: worker agent launchers and scenario data. Its one CLI fix lets a `patchy` installed outside a tier 2 repo publish it. The skills have agents use the repo's pinned `pnpm patchy` instead, so that path is off the documented one. - #900 is CI. - #901 rewords an internal skill. ## Look at - **The entry**, at the top of `releases` in `packages/core/src/whatsNew.ts`. - It names only Claude Code and Codex. Both have connected through real consent against dev instances. Hosted clients (Claude.ai, ChatGPT) are checked in production only (`docs/product.md` › Patchy MCP › Acceptance). - Its labels are the pages' own: Agent access on Company, Your machines, What agents can do, Disconnect everything, and "Jordan Lee via Claude". - **Rollback safety, from the live commit `e4243ff` to `5dd94f3`.** - No PR in the range is labelled `one-way`, and every PR answers both Release impact questions with "Yes". - Migrations 0020–0025 are all additive: - three defaulted or nullable columns on `companies`; - `agent_name` on the runtime log, with a widened `credential_kind` check; - the agent connection tables, `agent_consents` and `change_keys`; - two columns on execution bindings. The new tables reference `users` without a cascade, but no release deletes users or companies. Release 16 reads the runtime log only for credential kinds it knows, so rows from agents can't break it. - `rollback-rehearsal` on #892 rehearsed the whole stack, since #892 adds the last migration and the rest of the stack sits below it: `Exercised rollback paths passed: e4243ff → c8bede4 → e4243ff → c8bede4, in 238s.` #896's run skipped, because it changes no migration or handler descriptor. - #883 turns on the load balancer's host header preservation, which the Deploy workflow's app stack deploy applies. A rollback leaves it on. That's harmless, because release 16's server never reads `Host`. - A rollback takes `/mcp` and `/whats-new.json` away. Connected agents get a 404 until this release returns, and then their connections work again, unless one ended in between. Agent tools published in between stay refused to pages, because #837 already shipped in release 16. ## How it was verified - `pnpm check` on `2d528b1`: format, lint, typecheck and synth passed. In the test step, 2,300 of 2,301 tests passed. The one failure was `packages/sdk/src/install.test.ts` › "says how to reach patchy when the prefix's bin is not on PATH", which timed out at 180 s while the shared machine was loaded. Rerun alone, that file passes all 7 tests in 62 s. The release's own tests pass too: `whatsNew.test.ts`, `schemas.test.ts` and `WhatsNewPages.test.ts`. - The live commit was pinned from `/healthz/deep`: `e4243ff`, release 16. The Deploy run updated last succeeded, and none is unfinished. - Each PR in the range was read with `gh pr view`, including its Release impact answers. ## Release impact - [ ] **Breaking** — requires action from anyone already running this - [x] **Not breaking** — no action required This PR changes only the changelog text and the `patchy` version. As with every release, a CLI installed before this deploy is told to upgrade. - **What does a revert leave behind?** Nothing. People whose seen marker reached 17 would just see no new release. - **Does the release before it still work with that?** Yes. If this release misbehaves, roll back to `e4243ff54d2acbbc88b60eeb0cf9b82a26dc9d5d` (release 16). Prepared by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code. Co-authored-by: Claude Opus 5.5 <[email protected]>
Stacked on #879 (ticket #847); merges with the rest of #833's stack, not alone.
What changed
An MCP client such as Claude or Codex first reads how Patchy wants it to connect, then names itself with a metadata document on its own site. Patchy now publishes its protected resource metadata for
/mcpand its authorization server metadata, and it can fetch and judge a client's document under the spec's rules. That document's URL is a stranger's, so the fetch is the SSRF-sensitive part of this PR. Nothing calls it yet: #849's authorize and code exchange do.Closes #848
Look at
The fetch reaches only global unicast, and connects only to the answer it checked.
ClientDocumentsresolves the host once throughClientDocumentNetwork.resolve. It refuses the fetch if any answer isn't global unicast, then hands the checked addresses toconnect. The productionconnectopens TLS for the host name, withlookupanswering from those addresses, so the name is never resolved again. The address rule moved from the Postgres integration to@patchy/core(isPublicAddress), so both refuse the same set: only2000::/3passes for IPv6, so mapped, compatible, NAT64, 6to4 and Teredo forms all fail, and so do169.254.0.0/16andfd00:ec2::254. A client id must be the URL parser's own canonical https form on a host name. That refuses decimal, octal, hex and short-form IPv4, any IP literal, dot segments, userinfo, fragments and the default port before anything is fetched.The other limits live in two places. The HTTP rules are in
get: no redirect, 200 only, a declaredContent-Lengthover 5,000 refused before the body, a chunked body cut off once it crosses 5,000 bytes, and the whole fetch, DNS included, timed out at 5 s. The host limits are two maps inClientDocuments.make:keptholds accepted documents, least recently used first, andrunningholds the one fetch for each URL.max-age, orExpires−Date, or the hour row when neither is sent.Agecounts against each, the time is counted from the request, and the hour is the cap.no-store,no-cache,max-age=0and a malformed or repeatedmax-agekeep nothing, and a failure is never kept.Accepting.
client_idmust equal the URL exactly.client_nameandredirect_urisare required, as MCP's client registration requires, and every listed redirect must be an absolute URI without a fragment.token_endpoint_auth_methods_supportedis read when present andtoken_endpoint_auth_methodotherwise, and must offernone. That is exactly why ChatGPT's recorded document (single fieldprivate_key_jwt, list["none", "private_key_jwt"]) is accepted. Grant types and other fields are ignored.redirectAllowedmatches an https redirect the document lists exactly. It matches plain http tolocalhost,127.0.0.1or[::1]on any port, with the host and path exact, and only when written canonically, so only the port varies. It never allows plain http to another computer, even when listed.Patchy's metadata.
/.well-known/oauth-protected-resource/mcp(and the root form) namescope="patches"./.well-known/oauth-authorization-serveradvertisesclient_id_metadata_document_supported,none,S256,patches,issand noregistration_endpoint. Both sendcache-control: public, max-age=3600. In production they also sendaccess-control-allow-origin: *without credentials, and answer a preflight with the spec's headers.OAuthMetadata.corsandpreflightare exported for #849's token endpoint and #851's door. A dev instance (a loopback public origin, the rule dev personas already used, nowSession.isLoopback) sends no CORS and advertiseshttp://127.0.0.1:<port>/oauth/token, whatever loopback host it is served on.How it was verified
packages/auth/src/ClientDocuments.test.ts, 25 tests over a real HTTP server on loopback behind a testClientDocumentNetwork, with one test per rule. Highlights:@patchy/auth/testing, all accepted.169.254.169.254,fd00:ec2::254,::ffff:127.0.0.1,64:ff9b::a9fe:a9fe,0.0.0.0,::, and a public answer mixed with a private one.TestClock).ClientDocumentNetwork.test.ts: the productionconnectreaches a TLS server on127.0.0.1under the unresolvableclient.invalid, sends that name as SNI and refuses its self-signed certificate.no-store,Age, the loopback host match, the 200-only rule, the start limit and the IP-literal refusal.OAuthMetadata.test.tscovers both documents, the preflight, and dev instances on<label>.localhost,localhostand127.0.0.1.Server.test.tsshows the full server answers/.well-known/*ahead of/:company/:name/*.pnpm test:rollback-rehearsal --live e4243ff(release 16, live, with Tier 2 readers accept handler descriptions, read-only actions and agent tools, and enforce them #837 and Deactivation and Disconnect everything end pending device logins and record when a person's credentials ended #838) passed:e4243ff → fd374a4 → e4243ff → fd374a4, in 161s. The commit after fd374a4 only changesClientDocuments.loadand a test, and adds no migration.vitest run packages/limits packages/auth packages/core apps/server/src/Server.test.ts: 297 passed. The Postgres integration'sSource.test.tspassed after the move. Typecheck (packages and tests) and lint pass.Release impact
New routes and an in-memory service. No migration, configuration or wire contract changes, and the three new limits are optional
PATCHY_LIMITS_JSONids with defaults. Within the stack, the metadata names/oauth/authorizeand/oauth/token, which #849 builds. Nothing here ships before the whole stack does./oauth/*gone, as before the stack.Built by Claude Opus 5.5 (xhigh) in Claude Code on T3 Code; reviewed and accepted by GPT-6.1-Sol (xhigh).