diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3793af7..5e5e2cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,76 @@
# Changelog
+## 0.37.5 (2026-11-18)
+
+A client that registers itself is registered as a public client, whatever it asked for. In
+both SDKs; it concerns only a company with `client_registration` on.
+
+- **`POST /oauth/register` takes `token_endpoint_auth_method` left out, `none`,
+ `client_secret_post` or `client_secret_basic`**, registers a public client each time, and
+ says so: the response's `token_endpoint_auth_method` is `none`, with no `client_secret` and
+ no `client_secret_expires_at` (RFC 7591 §3.2.1: the server may replace what was requested,
+ and the client uses what is returned). 0.37.4 registered only a client that said `none`
+ itself, which refused MCP clients whose SDK leaves the method out or defaults to a secret.
+- **Unchanged:** a registration that names a `client_secret`, `jwks` or `jwks_uri` of its
+ own is refused, so a personal agent can't register as a public client; any other method
+ (`private_key_jwt`, an unknown one, one that is no text) is refused; grant types are
+ `authorization_code` and `refresh_token`; PKCE `S256` is mandatory; the redirect rules.
+ A client ID metadata document still says `none` itself.
+- **A request that carries a client secret is refused.** A token or revocation request
+ without a client assertion that sends `client_secret`, in its form or as HTTP Basic, is
+ `invalid_client` with a description saying the client has none. No secret is issued,
+ checked, or ignored: a request is never served as if a secret had been right. It is
+ refused before the code or the refresh token is looked at, so it spends nothing.
+
+## 0.37.4 (2026-11-18)
+
+Clients that are no personal agents. In both SDKs; additive API only, off by default, and a
+company that turns nothing on behaves exactly as before.
+
+- **`public_clients` (`publicClients`) on `CompanyConfig`** (spec 7: MCP clients sign in with
+ MCP's own OAuth flow). A public client, such as an MCP client, authenticates with nothing but
+ PKCE (S256) at Direct Sign-In's authorization endpoint. It is either verified by its domain,
+ a client ID metadata document that says `token_endpoint_auth_method` is `none` and names no
+ key, read by the client resolver's new optional `resolve_public` (`resolvePublic`); or, with
+ **`client_registration` (`clientRegistration`)**, registered at `POST /oauth/register`
+ (RFC 7591), unverified. A document that names a key is a personal agent's and no document is
+ both, so a personal agent can't skip its assertion. Guide: guides/company, *Other clients
+ than personal agents*.
+- **One service, and nothing of the protocol.** A public client's token is a Bearer token for
+ one of `resource_servers` or the company's own MCP server, named as `resource` in every
+ request; never the default token. It is refused at every endpoint of the protocol, with or
+ without a Session header; at the MCP server it calls tools with no Session, and a tool that
+ needs approval returns no operation. `access_token_for` (`accessTokenFor`) returns such a
+ token's record with `public` true, and asks the client policy as before. Scopes are
+ `public_client_scopes` (`publicClientScopes`), never `poppy:browser-sign-in`.
+- **Refresh tokens** of a public client are rotated at every use and one used twice ends the
+ sign-in whole, whatever `refresh_reuse_revokes` says; a sign-in lasts
+ `public_client_refresh_lifetime` (`publicClientRefreshLifetimeSeconds`, 30 days) from the
+ consent, and no access token of it outlives it.
+- **Redirect URIs** of a public client are loopback or HTTPS, written without user
+ information, fragment, backslash or space, compared as text, exactly but for a loopback
+ port (`public_redirect_uri`, `public_redirect_uri_matches`). An unverified client's errors
+ are pages, never redirects.
+- **For a consent page**: `authorization_request` (`authorizationRequest`) adds `client_class`
+ (`personal_agent` or `public_client`), `verified`, `redirect_host`, and `resource` for a
+ public client. The company's own page says when a client is unverified and where the
+ browser goes back to.
+- **Registration is bounded**: the host's rate limit is asked with `registration:{address}`,
+ then `client_registrations_per_hour` (10) for each address; a client that never signs in is
+ forgotten after an hour. A token or revocation request without an assertion asks the host's
+ rate limit with `public:{address}` before its client is looked at. `CompanyRequest` has an
+ optional `client_address` (`clientAddress`), which the ASGI and Node adapters fill with the
+ peer's.
+- **The client policy** may answer for public clients apart, with an optional
+ `allows_public(client_id)` (`allowsPublic`); without it, `allows` answers for both classes.
+- **For the company's owner**: `public_client_sign_ins` (`publicClientSignIns`) and
+ `revoke_public_client_sign_in` (`revokePublicClientSignIn`).
+- The issuer's metadata gains `none` in `token_endpoint_auth_methods_supported` and
+ `authorization_response_iss_parameter_supported` only with `public_clients`, and
+ `registration_endpoint` only with `client_registration`. New record kinds `public_client` and
+ `registration_count`; a personal agent's records are written as before.
+
## 0.37.3 (2026-11-18)
A company's services at URLs of their own. In both SDKs; additive API only, and a company that
diff --git a/docs/docs/guides/company.mdx b/docs/docs/guides/company.mdx
index d4b8a2d..fa12038 100644
--- a/docs/docs/guides/company.mdx
+++ b/docs/docs/guides/company.mdx
@@ -692,6 +692,142 @@ enforces the scopes on every call.
A company that names no resource server behaves as before.
+### Other clients than personal agents
+
+An MCP client that is no personal agent, such as a desktop assistant or an IDE, has no
+key and no Session: it signs in with MCP's own OAuth flow, the authorization code grant
+with PKCE and nothing else. The protocol leaves such clients outside (§7), and the
+reference company refuses them unless it is told otherwise:
+
+```python
+config = CompanyConfig(
+ name="Example",
+ domain="example.com",
+ scopes=("orders:read", "orders:write"),
+ agent_description="Your orders",
+ scope_descriptions={"orders:read": "See your orders", "orders:write": "Change your orders"},
+ write_scopes=("orders:write",),
+ resource_servers=("https://mcp.example.com/mcp",),
+ public_clients=True,
+ client_registration=True,
+ public_client_scopes=("orders:read",),
+)
+print(config.registration_endpoint)
+```
+
+`public_clients` (`publicClients`) lets public clients sign in at Direct Sign-In's
+authorization endpoint, so it needs `direct`. Everything below is off without it, and a
+company that leaves it off behaves exactly as before.
+
+**Two ways to be a public client.** Which one a client is, is never the request's to say.
+
+- **Verified by its domain.** Its `client_id` is the URL of a client ID metadata
+ document that says `token_endpoint_auth_method` is `none` and names no `jwks_uri`,
+ `jwks` or `client_secret`. A document that names a key is a personal agent's, and no
+ document is both: a personal agent can't present itself as a public client to skip its
+ assertion. The document is read by the `pap.company.clientResolver` contribution's
+ `resolve_public` (`resolvePublic`), as a personal agent's is: HTTPS, no redirect,
+ bounded, and never at a private address. A resolver without the method verifies none.
+ The redirect URIs used from it are the loopback ones and the HTTPS ones on the
+ `client_id`'s own host.
+- **Registered itself**, with `client_registration` (`clientRegistration`): `POST
+ /oauth/register` (RFC 7591) gives it a `client_id` that is no URL, and no secret.
+ Every client registered is a public client, whatever it asked for:
+ `token_endpoint_auth_method` left out, `none`, `client_secret_post` or
+ `client_secret_basic` is registered the same way, and the response says
+ `"token_endpoint_auth_method": "none"` with no `client_secret` (RFC 7591 §3.2.1: the
+ server may replace what was requested, and the client uses what is returned). A
+ registration that names a `client_secret`, `jwks` or `jwks_uri` of its own, or any
+ other method (`private_key_jwt` among them), is `invalid_client_metadata`, with an
+ `error_description` saying what to send: a personal agent can't register as a public
+ client. A token or revocation request that carries a `client_secret`, in its form or
+ as HTTP Basic, is `invalid_client`: no secret is ever issued, checked or ignored.
+ That includes a library that sends a public client's `client_id` as HTTP Basic with
+ an empty password: the `client_id` goes in the form, and no `Authorization` header.
+ Nothing verifies what a registered client says of itself, its name least of all.
+
+**Redirect URIs** of a public client are `http` to the loopback (`127.0.0.1`, `[::1]`,
+`localhost`) or HTTPS to a host written in small letters, with no user information,
+fragment, backslash or space, and are compared as text. A request's `redirect_uri`
+matches a registered one exactly; only a loopback one may differ by its port
+(RFC 8252 §7.3). Any other scheme is refused.
+
+**The consent page** is shown for every request. `authorization_request` says who asks:
+`client_class` is `public_client` (`personal_agent` otherwise), `verified` is false for
+a client that registered itself, `redirect_host` is where the browser goes back to and
+`resource` the service the sign-in is for. A hosted consent page shows the return host
+prominently, marks an unverified client as such, keeps `caution` (§10.8), and is never
+framed (`frame-ancestors 'none'`), as the company's own page does. An error of a request
+from an unverified client is a page, never a redirect: anyone can register any HTTPS
+redirect, and answering it without anyone's consent would make the endpoint an open
+redirector. Every answer carries `iss` (RFC 9207) and the request's `state`.
+
+**What a public client gets**, and what it never gets:
+
+- a Bearer token for one service, which every request names as `resource`: the
+ authorization request, the code exchange and each refresh, always the same one. The
+ services are `resource_servers` and the company's own MCP server. Never the default
+ token, never the conversation endpoint;
+- the scopes of `public_client_scopes` (`publicClientScopes`), or every scope of the
+ company's own when it names none; never `poppy:browser-sign-in`;
+- the code and refresh grants only. The device and mediated grants answer
+ `unauthorized_client`, and it can't push an authorization request;
+- no Session. Its token is refused at every endpoint of the protocol (conversations,
+ operations, tasks, feedback, the browser session, the APIs), with or without a
+ Session header, and at the MCP server once a Session header comes with it;
+- no operation. At the company's own MCP server a tool that needs the person's approval
+ answers an error and returns no operation: only a personal agent approves one.
+
+**Refresh tokens** of a public client are rotated at every use, and one used twice ends
+the whole sign-in, whatever `refresh_reuse_revokes` says for personal agents. A sign-in
+lasts `public_client_refresh_lifetime` (`publicClientRefreshLifetimeSeconds`, 30 days)
+from the moment the person allowed it, however often it refreshes; then they sign in
+again. No token outlives it: an access token issued near the end expires with the
+sign-in (`expires_in` says so), and a public client's token whose sign-in is over,
+ended or no longer on record is refused wherever it is read. A public client ends
+its own sign-in at the revocation endpoint with its `client_id` and the refresh token.
+
+**The client policy** is asked as for a personal agent: `allows` before anything is
+fetched or read for a `client_id`, `allows_sign_in` at the authorization endpoint and
+again when the code is exchanged, `allows_resource` for the service, at each token
+request and each time `access_token_for` reads a token. A service at a URL of its own
+reads `public` on the record `access_token_for` returns: true for a public client's
+token, to which it gives no Session and from which it takes no approval.
+
+A policy may answer for public clients apart, with `allows_public(client_id)`
+(`allowsPublic`): a company that lists the personal agents it serves takes public
+clients all the same, or none. Without the method, `allows` answers for both classes.
+`sign_in_disabled` is about personal agents only: it neither stops nor allows public
+clients, which `public_clients` alone decides.
+
+A client verified by its domain is read again at each token request, so a document that
+went away or became a personal agent's gets nothing more. The resolver's cache decides
+how often that is a fetch: the default one keeps a document as its `Cache-Control` says,
+and remembers for 30 seconds that one could not be read.
+
+**Registration is bounded.** The host's `pap.company.rateLimit` is asked first, with
+`registration:{address}` where it is asked a `client_id`; then the company counts
+`client_registrations_per_hour` (`clientRegistrationsPerHour`, 10) for each address.
+The address is the request's `client_address` (`clientAddress`): the peer's, which the
+ASGI and Node adapters fill in. Behind a proxy that is the proxy's, one count for
+everyone, unless the host passes the address its proxy vouches for. A registration is at
+most 16 KiB, names at most 10 redirect URIs and a name of at most 100 characters with
+no control or direction mark. A client that never signs in is forgotten an hour after
+it registered; one that signs in is kept `client_registration_lifetime` (90 days) from
+its last sign-in. A token or revocation request without a client assertion asks the
+host's rate limit too, with `public:{address}`, before the client it names is looked at.
+
+**For the company's owner.** `await service.public_client_sign_ins()`
+(`publicClientSignIns`) lists the sign-ins that have not ended: the client, its name,
+whether it is verified, the return host, the service, the account, the scopes, when it
+signed in and last got tokens, and when it ends.
+`revoke_public_client_sign_in(sign_in_id)` (`revokePublicClientSignIn`) ends one: its
+refresh and access tokens stop working at once.
+
+The issuer's metadata says `none` in `token_endpoint_auth_methods_supported` and
+`authorization_response_iss_parameter_supported` only with `public_clients`, and
+`registration_endpoint` only with `client_registration`.
+
### Before production
The defaults keep state in one process. A deployment contributes a durable
diff --git a/docs/docs/protocol/conformance-report.mdx b/docs/docs/protocol/conformance-report.mdx
index 7fd34c7..4ce2d52 100644
--- a/docs/docs/protocol/conformance-report.mdx
+++ b/docs/docs/protocol/conformance-report.mdx
@@ -6,7 +6,7 @@ title: Compatibility and conformance report
# Compatibility and conformance report
-SDK version **0.37.3**, PAP profile **0.4** (as published 2026-11-10), Operations extension **v3**; the pairings run at protocol version **1.0**, the default (1.0 as published 2026-11-14); the suite also runs at 0.4 in every pairing. Each pairing runs every positive, negative and recovery fixture case over real TCP and TLS, the personal agent in one language and the reference company (Manzanita) in the other. A case is skipped, never passed, when a side lacks what it needs; the reason is listed below.
+SDK version **0.37.5**, PAP profile **0.4** (as published 2026-11-10), Operations extension **v3**; the pairings run at protocol version **1.0**, the default (1.0 as published 2026-11-14); the suite also runs at 0.4 in every pairing. Each pairing runs every positive, negative and recovery fixture case over real TCP and TLS, the personal agent in one language and the reference company (Manzanita) in the other. A case is skipped, never passed, when a side lacks what it needs; the reason is listed below.
## Pairings
diff --git a/docs/docs/releases/compatibility.mdx b/docs/docs/releases/compatibility.mdx
index 0cb0512..a4ab48c 100644
--- a/docs/docs/releases/compatibility.mdx
+++ b/docs/docs/releases/compatibility.mdx
@@ -4,7 +4,7 @@ title: Compatibility
# Compatibility
-This page is versioned with the SDK: it describes **SDK 0.37.3**.
+This page is versioned with the SDK: it describes **SDK 0.37.5**.
## The PAP version implemented
@@ -35,6 +35,8 @@ profile, never picked up from an unattended fetch.
| SDK (PyPI and npm) | PAP profile | Specification revision | Operations | Breaking changes |
| --- | --- | --- | --- | --- |
+| `0.37.5` | `0.4` | 2026-11-10 | v3 | none: a client that registers itself (`client_registration`) is registered as a public client whatever `token_endpoint_auth_method` it asked for among `none`, `client_secret_post`, `client_secret_basic` or none at all, and told `none`; a request that sends a client secret is refused |
+| `0.37.4` | `0.4` | 2026-11-10 | v3 | none: a company may let clients that are no personal agents sign in (`public_clients`: MCP clients, with PKCE alone, verified by their client ID metadata document or registered at `/oauth/register` with `client_registration`), for tokens that work at one service and at no endpoint of the protocol; off by default |
| `0.37.3` | `0.4` | 2026-11-10 | v3 | none: a company names its services at URLs of their own (`resource_servers`, an MCP server on another host), which its issuer lists in `protected_resources` and issues Bearer tokens for, and which verify them with `access_token_for` |
| `0.37.2` | `0.4` | 2026-11-10 | v3 | none: opening a sign-in link reads its record without consuming it (the state store's optional `get`), a link begun by 0.37.0 still opens after an upgrade, and the Direct Sign-In start names its `state` for hosts whose redirect lands elsewhere |
| `0.37.1` | `0.4` | 2026-11-10 | v3 | none: a bound refresh token keeps its sign-in at a Bearer-only MCP server, `open_link` leaves the callback state to `complete`, an empty SSE event name is a message, and `effectiveContext` keeps a `__proto__` field as a field |
diff --git a/docs/docs/sdk/python-api.mdx b/docs/docs/sdk/python-api.mdx
index aebaef7..9032058 100644
--- a/docs/docs/sdk/python-api.mdx
+++ b/docs/docs/sdk/python-api.mdx
@@ -199,6 +199,7 @@ Unknown or internal symbols are deliberately excluded.
- [`PROTOCOL_REVISION`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/profile.py) — Constant. Public `PROTOCOL_REVISION` constant.
- [`ProtocolCache`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/reactor.py) — Class. Bound cached public protocol data by an absolute expiry.
- [`ProtocolValidationError`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/errors.py) — Class. A protocol document is malformed or internally inconsistent.
+- [`PublicClientMetadata`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/models.py) — Class. The client ID metadata document of a public client: an MCP client, never a
- [`RANDOM_SOURCES`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/reactor.py) — Constant. Public `RANDOM_SOURCES` constant.
- [`RandomSource`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/reactor.py) — Class. Supply cryptographically secure random bytes.
- [`RATE_LIMIT_BUDGETS`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/reactor.py) — Constant. Public `RATE_LIMIT_BUDGETS` constant.
diff --git a/docs/docs/sdk/typescript-api.mdx b/docs/docs/sdk/typescript-api.mdx
index fe3038d..52a490f 100644
--- a/docs/docs/sdk/typescript-api.mdx
+++ b/docs/docs/sdk/typescript-api.mdx
@@ -211,6 +211,7 @@ Unknown or internal symbols are deliberately excluded.
- [`isPapReplies`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/ui.ts) — Function; entry `.`. Whether a display is what a company answered, of the version this SDK reads.
- [`isPapRepliesData`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/ui.ts) — Function; entry `.`. Whether a value is the `data` of what a company answered, as `PapReplies`
- [`isPapSessionShown`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/ui.ts) — Function; entry `.`. Whether a value is a `PapSessionShown`: a 12-hex-digit reference and `signed_in`, nothing else.
+- [`isPublicLoopbackRedirect`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. A public client's loopback redirect URI (RFC 8252 §7.3, §8.3): `http` to `127.0.0.1`,
- [`JOSE_ALGORITHMS`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/crypto.ts) — Const; entry `.`. The algorithms a key in `jwks_uri` signs client assertions and delegations with (§4.1, §5.2).
- [`JoseAlgorithm`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/crypto.ts) — Type; entry `.`. Public TypeScript type `JoseAlgorithm`.
- [`JoseDpopProver`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/crypto.ts) — Class; entry `.`. `pap.dpopProver`: a fresh proof for each request, by the Company's DPoP key (§4.5).
@@ -366,6 +367,7 @@ Unknown or internal symbols are deliberately excluded.
- [`parseOperationHeader`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/operations.ts) — Function; entry `.`. The reference a `Poppy-Operation` value states, or `undefined`.
- [`parseOperationsContent`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. Public TypeScript function `parseOperationsContent`.
- [`parseProtectedResourceMetadata`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. Public TypeScript function `parseProtectedResourceMetadata`.
+- [`parsePublicClientMetadata`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. Public TypeScript function `parsePublicClientMetadata`.
- [`parseRetryAfter`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/limits.ts) — Function; entry `.`. `Retry-After` in seconds (delta-seconds or an HTTP date), or `undefined`.
- [`parseTasksResponse`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. Public TypeScript function `parseTasksResponse`.
- [`parseTokenResponse`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/sessions.ts) — Function; entry `.`. A token endpoint's JSON answer (§4.7).
@@ -384,7 +386,11 @@ Unknown or internal symbols are deliberately excluded.
- [`PROTOCOL_REVISION`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/profile.ts) — Const; entry `.`. The upstream specification revision implemented: the day 0.4 was published (commit 4803900).
- [`ProtocolCache`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/reactor.ts) — Interface; entry `.`. Public TypeScript interface `ProtocolCache`.
- [`ProtocolValidationError`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/errors.ts) — Class; entry `.`. Public TypeScript class `ProtocolValidationError`.
+- [`PublicClientMetadata`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Interface; entry `.`. The client ID metadata document of a public client: an MCP client, never a personal agent.
+- [`publicClientName`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. A public client's name as a consent page shows it (`RangeError` otherwise): text of 1 to 100
- [`publicJwk`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/crypto.ts) — Function; entry `.`. A public JWK with no private member: refused otherwise (§5.2).
+- [`publicRedirectUri`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. A redirect URI a public client may name: loopback, or HTTPS (`RangeError` otherwise).
+- [`publicRedirectUriMatches`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. Whether `given` is the redirect URI a public client `registered`.
- [`RandomBytes`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/sessions.ts) — Type; entry `.`. Public TypeScript type `RandomBytes`.
- [`RandomSource`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/reactor.ts) — Interface; entry `.`. Public TypeScript interface `RandomSource`.
- [`RandomSources`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/reactor.ts) — Const; entry `.`. Public TypeScript const `RandomSources`.
@@ -514,6 +520,7 @@ Unknown or internal symbols are deliberately excluded.
- [`urlDomain`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. The domain an HTTPS URL is on, as `organization.domain` names it (§3.1): its host, lowercase,
- [`UrlSafetyPolicies`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/reactor.ts) — Const; entry `.`. Public TypeScript const `UrlSafetyPolicies`.
- [`UrlSafetyPolicy`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/reactor.ts) — Interface; entry `.`. Public TypeScript interface `UrlSafetyPolicy`.
+- [`usableRedirectUris`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. The redirect URIs a company sends a public client's answers to: loopback, or HTTPS on the
- [`usableReferences`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. The references an agent may follow (§8.2).
- [`usableSkills`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/models.ts) — Function; entry `.`. The skills of a tasks response's `skill_index` this SDK can use (§9.4), each `url` resolved.
- [`USER_STEP_ATTRIBUTE`](https://github.com/datalayer/personal-agent-protocol/blob/main/src/browser-control.ts) — Const; entry `.`. The attribute that marks a step for the User (Browser Control 4).
diff --git a/package.json b/package.json
index 04064ca..2951743 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@datalayer/personal-agent-protocol",
- "version": "0.37.3",
+ "version": "0.37.5",
"description": "TypeScript SDK for Personal Agent Protocol 0.4 (2026-11-10) and its Operations extension v3",
"repository": {
"type": "git",
diff --git a/personal_agent_protocol/__init__.py b/personal_agent_protocol/__init__.py
index ec7161f..2cc9e50 100644
--- a/personal_agent_protocol/__init__.py
+++ b/personal_agent_protocol/__init__.py
@@ -146,6 +146,7 @@
OperationsContent,
Organization,
ProtectedResourceMetadata,
+ PublicClientMetadata,
ScopeHint,
SkillEntry,
TasksDescriptor,
@@ -478,6 +479,7 @@
"ProtectedResourceMetadata",
"ProtocolCache",
"ProtocolValidationError",
+ "PublicClientMetadata",
"RandomSource",
"RateLimitBudget",
"RecordingTelemetrySink",
diff --git a/personal_agent_protocol/__tests__/test_docs_examples.py b/personal_agent_protocol/__tests__/test_docs_examples.py
index 5edd6e2..b08fa16 100644
--- a/personal_agent_protocol/__tests__/test_docs_examples.py
+++ b/personal_agent_protocol/__tests__/test_docs_examples.py
@@ -807,6 +807,24 @@ async def check(namespace: dict[str, Any], out: str) -> None:
return {"CompanyConfig": CompanyConfig}, check
+@case("docs/docs/guides/company.mdx#5")
+async def _public_clients(docs: Docs) -> tuple[dict[str, Any], Check]:
+ async def check(namespace: dict[str, Any], out: str) -> None:
+ import httpx
+
+ from personal_agent_protocol.company import build_company
+
+ config = namespace["config"]
+ assert out.strip() == "https://example.com/oauth/register"
+ assert config.public_scopes == ("orders:read",)
+ async with httpx.AsyncClient() as http:
+ metadata = build_company(config, http_client=http).oauth_metadata()
+ assert metadata["token_endpoint_auth_methods_supported"] == ["private_key_jwt", "none"]
+ assert metadata["registration_endpoint"] == "https://example.com/oauth/register"
+
+ return {"CompanyConfig": CompanyConfig}, check
+
+
# CLI and extensions -----------------------------------------------------------------------
diff --git a/personal_agent_protocol/__tests__/test_hosted_pages.py b/personal_agent_protocol/__tests__/test_hosted_pages.py
index 17edefa..14521a8 100644
--- a/personal_agent_protocol/__tests__/test_hosted_pages.py
+++ b/personal_agent_protocol/__tests__/test_hosted_pages.py
@@ -120,8 +120,15 @@ async def test_authorize_redirects_to_the_hosted_consent_page_which_reads_the_re
# What the page starts with and says before the person goes on (spec 10.8).
assert summary["heading"] == "Atlas wants to connect to your Manzanita Outfitters account"
assert summary["caution"] == "Only continue if you asked Atlas to do this just now."
+ # Who asks, as a class of client, and where the browser goes back to.
+ assert summary["client_class"] == "personal_agent"
+ assert summary["verified"] is True
+ assert summary["redirect_host"] == "atlas.example"
assert set(summary) == {
"request_id",
+ "client_class",
+ "verified",
+ "redirect_host",
"client_name",
"client_domain",
"heading",
diff --git a/personal_agent_protocol/__tests__/test_public_clients.py b/personal_agent_protocol/__tests__/test_public_clients.py
new file mode 100644
index 0000000..487fe3f
--- /dev/null
+++ b/personal_agent_protocol/__tests__/test_public_clients.py
@@ -0,0 +1,1682 @@
+# Copyright (c) 2025-2026 Datalayer, Inc.
+#
+# BSD 3-Clause License
+
+"""Public clients: clients that are no personal agents (MCP clients) sign in with PKCE alone.
+
+Off by default. On, a public client is verified by its domain (a client ID metadata
+document that names no key) or registered itself (RFC 7591); it gets tokens for one
+service, rotated at every refresh, and nothing of the protocol: no Session, no default
+token, no operation approval.
+"""
+
+from __future__ import annotations
+
+import base64
+import dataclasses
+import hashlib
+import json
+from datetime import datetime, timedelta, timezone
+from typing import Any
+from urllib.parse import parse_qs, urlencode, urlsplit
+
+import httpx
+import pytest
+from pydantic import SecretStr, ValidationError
+from reactor import PluginManifest, hookimpl # type: ignore[import-untyped]
+
+from personal_agent_protocol.company import (
+ CLIENT_POLICIES,
+ CLIENT_RESOLVERS,
+ COMPANY_RATE_LIMITS,
+ CompanyConfig,
+ CompanyRequest,
+)
+from personal_agent_protocol.company.store import (
+ ACCOUNT_FAMILY,
+ AccountFamily,
+ AccountGrant,
+ IssuedAccessToken,
+ IssuedCode,
+ PendingAuthorization,
+)
+from personal_agent_protocol.demo.kit import json_site
+from personal_agent_protocol.demo.manzanita import CONFIG, manzanita
+from personal_agent_protocol.errors import PersonalAgentProtocolError
+from personal_agent_protocol.identity import AgentIdentityClient
+from personal_agent_protocol.models import (
+ DEVICE_CODE_GRANT,
+ PublicClientMetadata,
+ is_public_loopback_redirect,
+ public_client_name,
+ public_redirect_uri,
+ public_redirect_uri_matches,
+)
+from personal_agent_protocol.sessions import AccessToken, SessionClient
+
+from .test_company_end_to_end import World
+from .test_company_refusals import signed_in
+
+SHOP = "https://manzanita.example"
+MCP = f"{SHOP}/mcp"
+#: The company's MCP server on a host of its own.
+ELSEWHERE = "https://mcp.manzanita.example/mcp"
+#: A public client verified by its domain: its client ID metadata document.
+VERIFIED = "https://client.example/oauth/client.json"
+VERIFIED_REDIRECT = "https://client.example/callback"
+LOOPBACK = "http://127.0.0.1/callback"
+LIST_TOOLS = {"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
+
+
+def document(**changes: object) -> dict[str, object]:
+ return {
+ "client_id": VERIFIED,
+ "client_name": "Deskmate",
+ "redirect_uris": [VERIFIED_REDIRECT, LOOPBACK, "https://elsewhere.example/callback"],
+ "token_endpoint_auth_method": "none",
+ "grant_types": ["authorization_code", "refresh_token"],
+ "response_types": ["code"],
+ **changes,
+ }
+
+
+def public_world(*, site: dict[str, object] | None = None, **options: object) -> World:
+ """Manzanita with public clients and registration on, and a verified client's site."""
+
+ world = World()
+ settings: dict[str, object] = {
+ "public_clients": True,
+ "client_registration": True,
+ "resource_servers": (ELSEWHERE,),
+ **options,
+ }
+ world.shop, world.plugin = manzanita(
+ world.network,
+ world.clock,
+ config=dataclasses.replace(CONFIG, **settings), # type: ignore[arg-type]
+ )
+ world.network.add("client.example", json_site({"/oauth/client.json": site or document()}))
+ return world
+
+
+def pkce() -> tuple[str, str]:
+ verifier = "v" * 43
+ digest = hashlib.sha256(verifier.encode()).digest()
+ return verifier, base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
+
+
+async def register(world: World, **changes: object) -> httpx.Response:
+ body = {
+ "client_name": "Pocket MCP",
+ "redirect_uris": [LOOPBACK, "https://pocket.example/callback"],
+ "token_endpoint_auth_method": "none",
+ **changes,
+ }
+ return await world.http.post(f"{SHOP}/oauth/register", json=body)
+
+
+async def registered(world: World, **changes: object) -> str:
+ response = await register(world, **changes)
+ assert response.status_code == 201, response.text
+ return str(response.json()["client_id"])
+
+
+async def authorize(
+ world: World, client_id: str, redirect_uri: str, **changes: str | None
+) -> httpx.Response:
+ query: dict[str, str | None] = {
+ "response_type": "code",
+ "client_id": client_id,
+ "redirect_uri": redirect_uri,
+ "scope": "orders:read",
+ "state": "st-1",
+ "code_challenge": pkce()[1],
+ "code_challenge_method": "S256",
+ "resource": MCP,
+ **changes,
+ }
+ asked = {name: value for name, value in query.items() if value is not None}
+ return await world.http.get(f"{SHOP}/oauth/authorize?{urlencode(asked)}")
+
+
+def request_id_of(page: httpx.Response) -> str:
+ assert page.status_code == 200, page.text
+ return page.text.split('data-request-id="', 1)[1].split('"', 1)[0]
+
+
+async def token(world: World, **form: str) -> httpx.Response:
+ return await world.http.post(f"{SHOP}/oauth/token", data=form)
+
+
+async def code_for(world: World, client_id: str, redirect_uri: str, **changes: str | None) -> str:
+ page = await authorize(world, client_id, redirect_uri, **changes)
+ back = await world.shop.approve_authorization(request_id_of(page), account_id="acct_ada")
+ return parse_qs(urlsplit(back).query)["code"][0]
+
+
+async def sign_in(
+ world: World,
+ client_id: str,
+ redirect_uri: str = LOOPBACK,
+ *,
+ resource: str = MCP,
+ scope: str = "orders:read",
+) -> dict[str, Any]:
+ code = await code_for(world, client_id, redirect_uri, resource=resource, scope=scope)
+ response = await token(
+ world,
+ grant_type="authorization_code",
+ client_id=client_id,
+ code=code,
+ redirect_uri=redirect_uri,
+ code_verifier=pkce()[0],
+ resource=resource,
+ )
+ assert response.status_code == 200, response.text
+ return dict(response.json())
+
+
+async def refresh(world: World, client_id: str, refresh_token: str, **more: str) -> httpx.Response:
+ form = {
+ "grant_type": "refresh_token",
+ "client_id": client_id,
+ "refresh_token": refresh_token,
+ "resource": MCP,
+ **more,
+ }
+ return await token(world, **form)
+
+
+async def mcp(world: World, access_token: str, message: dict[str, object]) -> httpx.Response:
+ return await world.http.post(
+ MCP, json=message, headers={"authorization": f"Bearer {access_token}"}
+ )
+
+
+# Off by default ------------------------------------------------------------------------
+
+
+def test_nothing_is_on_unless_configured() -> None:
+ assert CONFIG.public_clients is False
+ assert CONFIG.client_registration is False
+ assert CONFIG.public_client_refresh_lifetime.days == 30
+
+
+@pytest.mark.asyncio
+async def test_off_a_company_answers_as_before() -> None:
+ world = World()
+ world.network.add("client.example", json_site({"/oauth/client.json": document()}))
+ metadata = (await world.http.get(f"{SHOP}/.well-known/oauth-authorization-server")).json()
+ assert metadata["token_endpoint_auth_methods_supported"] == ["private_key_jwt"]
+ assert "registration_endpoint" not in metadata
+ assert "authorization_response_iss_parameter_supported" not in metadata
+ assert (await register(world)).status_code == 404
+ # A public client's document is no personal agent's: nothing verifies it.
+ page = await authorize(world, VERIFIED, VERIFIED_REDIRECT)
+ assert page.status_code == 400 and "location" not in page.headers
+ # A token request with no assertion is `invalid_client`, as it always was.
+ refused = await refresh(world, VERIFIED, "rt_x")
+ assert (refused.status_code, refused.json()["error"]) == (401, "invalid_client")
+
+
+def test_the_settings_are_checked() -> None:
+ def config(**changes: object) -> CompanyConfig:
+ return dataclasses.replace(CONFIG, **changes) # type: ignore[arg-type]
+
+ with pytest.raises(ValueError, match="direct"):
+ config(public_clients=True, direct=False, ucp=False)
+ with pytest.raises(ValueError, match="public_clients is on"):
+ config(client_registration=True)
+ with pytest.raises(ValueError, match="push"):
+ config(public_clients=True, pushed_authorization_requests="required")
+ with pytest.raises(ValueError, match="public_client_scopes"):
+ config(public_clients=True, public_client_scopes=("poppy:browser-sign-in",))
+ with pytest.raises(ValueError, match="public_client_scopes"):
+ config(public_clients=True, public_client_scopes=())
+ with pytest.raises(ValueError, match="positive"):
+ dataclasses.replace(CONFIG, public_client_refresh_lifetime=timedelta(0))
+ with pytest.raises(ValueError, match="at least 1"):
+ dataclasses.replace(CONFIG, client_registrations_per_hour=0)
+
+
+@pytest.mark.asyncio
+async def test_on_the_issuer_says_so() -> None:
+ world = public_world()
+ metadata = (await world.http.get(f"{SHOP}/.well-known/oauth-authorization-server")).json()
+ assert metadata["token_endpoint_auth_methods_supported"] == ["private_key_jwt", "none"]
+ assert metadata["registration_endpoint"] == f"{SHOP}/oauth/register"
+ assert metadata["authorization_response_iss_parameter_supported"] is True
+ assert metadata["code_challenge_methods_supported"] == ["S256"]
+ # Public clients without registration: `none`, and no endpoint to register at.
+ without = public_world(client_registration=False)
+ metadata = (await without.http.get(f"{SHOP}/.well-known/oauth-authorization-server")).json()
+ assert "none" in metadata["token_endpoint_auth_methods_supported"]
+ assert "registration_endpoint" not in metadata
+ assert (await register(without)).status_code == 404
+
+
+# The two ways to be a public client ---------------------------------------------------------
+
+
+@pytest.mark.asyncio
+async def test_a_client_verified_by_its_domain_signs_in_and_calls_the_mcp_server() -> None:
+ world = public_world()
+ page = await authorize(world, VERIFIED, VERIFIED_REDIRECT)
+ request_id = request_id_of(page)
+ # The page is never framed, and says where the browser goes back to.
+ assert page.headers["x-frame-options"] == "DENY"
+ assert "frame-ancestors 'none'" in page.headers["content-security-policy"]
+ assert "client.example" in page.text
+ assert "Unverified" not in page.text
+ assert "Only continue if you asked Deskmate to do this just now." in page.text
+
+ summary = await world.shop.authorization_request(request_id)
+ assert summary["client_class"] == "public_client"
+ assert summary["verified"] is True
+ assert summary["client_name"] == "Deskmate"
+ assert summary["client_domain"] == "client.example"
+ assert summary["redirect_host"] == "client.example"
+ assert summary["resource"] == MCP
+ assert "state" not in summary and "code_challenge" not in summary
+
+ back = await world.shop.approve_authorization(request_id, account_id="acct_ada")
+ answer = parse_qs(urlsplit(back).query)
+ # The answer names the issuer and gives the state back (RFC 9207, RFC 6749 §4.1.2).
+ assert back.startswith(f"{VERIFIED_REDIRECT}?")
+ assert answer["iss"] == [SHOP] and answer["state"] == ["st-1"]
+
+ response = await token(
+ world,
+ grant_type="authorization_code",
+ client_id=VERIFIED,
+ code=answer["code"][0],
+ redirect_uri=VERIFIED_REDIRECT,
+ code_verifier=pkce()[0],
+ resource=MCP,
+ )
+ assert response.status_code == 200, response.text
+ tokens = response.json()
+ assert tokens["token_type"] == "Bearer"
+ assert tokens["refresh_token"] and tokens["access_token"]
+ assert response.headers["cache-control"] == "no-store"
+
+ # At the MCP server: its token alone, and no Session header.
+ listed = await mcp(world, tokens["access_token"], LIST_TOOLS)
+ assert listed.status_code == 200
+ assert [tool["name"] for tool in listed.json()["result"]["tools"]]
+ called = await mcp(
+ world,
+ tokens["access_token"],
+ {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_orders"}},
+ )
+ assert called.status_code == 200 and "isError" not in called.json()["result"]
+
+
+@pytest.mark.asyncio
+async def test_a_client_that_registered_itself_is_shown_as_unverified() -> None:
+ world = public_world()
+ client_id = await registered(world)
+ assert client_id.startswith("mcpc_") and "://" not in client_id
+ page = await authorize(world, client_id, "http://127.0.0.1:49152/callback", resource=ELSEWHERE)
+ assert "Unverified app." in page.text
+ assert "127.0.0.1:49152" in page.text
+ summary = await world.shop.authorization_request(request_id_of(page))
+ assert summary["client_class"] == "public_client"
+ assert summary["verified"] is False
+ assert summary["client_domain"] == ""
+ assert summary["redirect_host"] == "127.0.0.1:49152"
+ assert summary["resource"] == ELSEWHERE
+
+ tokens = await sign_in(world, client_id, "http://127.0.0.1:49152/callback", resource=ELSEWHERE)
+ # The service at a URL of its own reads the token's record, which says whose it is.
+ record = await world.shop.access_token_for(tokens["access_token"], ELSEWHERE)
+ assert record is not None and record.public is True
+ assert (record.client_id, record.account_id) == (client_id, "acct_ada")
+ assert record.scopes == ("orders:read",) and record.dpop_jkt is None
+ # Issued for that service, it is nothing at the company's own MCP server.
+ assert (await mcp(world, tokens["access_token"], LIST_TOOLS)).status_code == 401
+
+
+@pytest.mark.asyncio
+async def test_a_personal_agents_request_says_its_class_too() -> None:
+ """A hosted consent page tells the two classes apart for every request."""
+
+ world = public_world()
+ page = await authorize(
+ world,
+ world.atlas.client_id,
+ "https://atlas.example/oauth/callback",
+ resource=None,
+ )
+ summary = await world.shop.authorization_request(request_id_of(page))
+ assert summary["client_class"] == "personal_agent"
+ assert summary["verified"] is True
+ assert summary["redirect_host"] == "atlas.example"
+ assert "resource" not in summary
+
+
+def _error(response: httpx.Response) -> str:
+ """The refusal's code: the body's `error`, or UCP's own message code."""
+
+ body = response.json()
+ if "error" in body:
+ return str(body["error"])
+ return str(body["messages"][0]["code"])
+
+
+# The protocol's boundaries --------------------------------------------------------------------
+
+
+@pytest.mark.asyncio
+async def test_a_public_clients_token_is_refused_at_every_endpoint_of_the_protocol() -> None:
+ world = public_world()
+ session = await world.signed_out_session()
+ client_id = await registered(world)
+ tokens = await sign_in(world, client_id, scope="orders:read orders:write")
+ bearer = {"authorization": f"Bearer {tokens['access_token']}"}
+ as_json = {"content-type": "application/json"}
+ endpoints = [
+ ("POST", f"{SHOP}/poppy/conversations", b'{"message": {"text": "Hello"}}'),
+ ("GET", f"{SHOP}/poppy/conversations/conv_1", None),
+ ("POST", f"{SHOP}/poppy/operations", b"{}"),
+ ("GET", f"{SHOP}/poppy/tasks", None),
+ ("POST", f"{SHOP}/poppy/feedback", b'{"task": "Pay with a gift card"}'),
+ ("POST", f"{SHOP}/poppy/browser-session/authorize", b"{}"),
+ ("GET", f"{SHOP}/api/orders", None),
+ ]
+ for method, url, content in endpoints:
+ # Alone, as a public client sends it: there is no Session, so nothing is served.
+ alone = await world.http.request(
+ method, url, content=content, headers={**bearer, **as_json}
+ )
+ assert alone.status_code in {400, 401}, (url, alone.status_code, alone.text)
+ assert _error(alone) in {"invalid_session", "invalid_token"}, (url, alone.text)
+ # In a personal agent's Session: a public client's token signs no Session in.
+ borrowed = await world.transport.request(
+ method,
+ url,
+ session=session,
+ token=AccessToken(access_token=SecretStr(tokens["access_token"])),
+ headers=as_json,
+ content=content,
+ )
+ assert borrowed.status_code in {400, 401}, (url, borrowed.status_code)
+ assert _error(borrowed) in {"invalid_session", "invalid_token"}, (url, borrowed.text)
+ # The same at the MCP server once a Session header comes with it.
+ with_session = await world.transport.request(
+ "POST",
+ MCP,
+ session=session,
+ token=AccessToken(access_token=SecretStr(tokens["access_token"])),
+ headers=as_json,
+ content=json.dumps(LIST_TOOLS).encode(),
+ )
+ assert with_session.status_code == 401
+ # And no Session was started for the client, signed in or out.
+ assert not [
+ record
+ for record in await world.shop.store.records("session")
+ if record.value["client_id"] == client_id
+ ]
+
+
+@pytest.mark.asyncio
+async def test_a_public_client_never_gets_the_default_token() -> None:
+ world = public_world()
+ client_id = await registered(world)
+ for resource in (None, SHOP, f"{SHOP}/poppy/conversations", "https://other.example/mcp"):
+ page = await authorize(world, client_id, LOOPBACK, resource=resource)
+ assert page.status_code == 400, resource
+ code = await code_for(world, client_id, LOOPBACK)
+ form = {
+ "grant_type": "authorization_code",
+ "client_id": client_id,
+ "code": code,
+ "redirect_uri": LOOPBACK,
+ "code_verifier": pkce()[0],
+ }
+ # No `resource`, the default token's, or a service it was not asked for: nothing,
+ # and the code is still there for the request that names the right one.
+ assert (await token(world, **form)).json()["error"] == "invalid_target"
+ assert (await token(world, **form, resource=SHOP)).json()["error"] == "invalid_target"
+ other = await token(world, **form, resource=ELSEWHERE)
+ assert other.json()["error"] == "invalid_target"
+ # The code named the MCP server: asked for another service, it is spent and gives nothing.
+ assert (await token(world, **form, resource=MCP)).json()["error"] == "invalid_grant"
+
+ tokens = await sign_in(world, client_id)
+ assert (await refresh(world, client_id, tokens["refresh_token"], resource=SHOP)).json()[
+ "error"
+ ] == "invalid_target"
+ assert (await refresh(world, client_id, tokens["refresh_token"], resource=ELSEWHERE)).json()[
+ "error"
+ ] == "invalid_target"
+ # A token for the MCP server is nothing at the other service.
+ assert await world.shop.access_token_for(tokens["access_token"], ELSEWHERE) is None
+
+
+@pytest.mark.asyncio
+async def test_a_public_client_gets_only_its_own_grants_and_scopes() -> None:
+ world = public_world()
+ client_id = await registered(world)
+ # `poppy:browser-sign-in` is a personal agent's: never asked, never granted.
+ page = await authorize(world, client_id, LOOPBACK, scope="orders:read poppy:browser-sign-in")
+ assert page.status_code == 400
+ # The device and mediated grants are a personal agent's.
+ for grant in (DEVICE_CODE_GRANT, "urn:poppy:params:oauth:grant-type:mediated"):
+ refused = await token(world, grant_type=grant, client_id=client_id, resource=MCP)
+ assert refused.status_code == 400
+ assert refused.json()["error"] in {"unauthorized_client", "unsupported_grant_type"}
+ device = await world.http.post(
+ f"{SHOP}/oauth/device", data={"client_id": client_id, "scope": "orders:read"}
+ )
+ assert (device.status_code, device.json()["error"]) == (401, "invalid_client")
+
+ narrowed = public_world(public_client_scopes=("orders:read",))
+ narrow_client = await registered(narrowed)
+ page = await authorize(narrowed, narrow_client, LOOPBACK, scope="orders:read orders:write")
+ assert page.status_code == 400
+ assert (await authorize(narrowed, narrow_client, LOOPBACK)).status_code == 200
+
+
+@pytest.mark.asyncio
+async def test_a_public_client_approves_no_operation() -> None:
+ world = public_world()
+ client_id = await registered(world)
+ tokens = await sign_in(world, client_id, scope="orders:read orders:write")
+ called = await mcp(
+ world,
+ tokens["access_token"],
+ {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "tools/call",
+ "params": {
+ "name": "exchange_jacket",
+ "arguments": {},
+ # An approval a personal agent would send: read from no public client.
+ "_meta": {"poppy/approval": {"operation_id": "op_1", "revision": 1}},
+ },
+ },
+ )
+ result = called.json()["result"]
+ assert result["isError"] is True
+ assert "structuredContent" not in result
+ assert "personal agent" in result["content"][0]["text"]
+ assert not await world.shop.store.records("operation")
+
+
+@pytest.mark.asyncio
+async def test_a_personal_agent_cannot_become_a_public_client() -> None:
+ """Its assertion is never skipped: its sign-ins, codes and document stay its own."""
+
+ world = public_world()
+ await signed_in(world)
+ assert world.refresh_reference is not None
+ kept = await world.host.vault.get(world.refresh_reference)
+ agent_refresh = kept.get_secret_value() if isinstance(kept, SecretStr) else str(kept)
+ client_id = await registered(world)
+
+ # Its own `client_id`, no assertion: its document names its keys, so it is no public client.
+ bare = await refresh(world, world.atlas.client_id, agent_refresh)
+ assert (bare.status_code, bare.json()["error"]) == (401, "invalid_client")
+ # Its refresh token under a public client's `client_id`: not that class of sign-in.
+ borrowed = await refresh(world, client_id, agent_refresh)
+ assert (borrowed.status_code, borrowed.json()["error"]) == (400, "invalid_grant")
+ # Neither attempt ended its sign-in: it refreshes as before.
+ assert (await world.refreshed()).access_token
+
+ # Its authorization code is exchanged with its assertion only.
+ page = await authorize(
+ world, world.atlas.client_id, "https://atlas.example/oauth/callback", resource=None
+ )
+ back = await world.shop.approve_authorization(request_id_of(page), account_id="acct_ada")
+ agent_code = parse_qs(urlsplit(back).query)["code"][0]
+ for claimed in (world.atlas.client_id, client_id):
+ refused = await token(
+ world,
+ grant_type="authorization_code",
+ client_id=claimed,
+ code=agent_code,
+ redirect_uri="https://atlas.example/oauth/callback",
+ code_verifier=pkce()[0],
+ resource=MCP,
+ )
+ assert refused.status_code in {400, 401}
+ assert refused.json()["error"] in {"invalid_client", "invalid_grant"}
+
+ # Someone who only intercepted the code and posts it without an assertion gets
+ # nothing, and spent it: the agent's own exchange finds it used.
+ owned = await token(
+ world,
+ grant_type="authorization_code",
+ code=agent_code,
+ redirect_uri="https://atlas.example/oauth/callback",
+ code_verifier=pkce()[0],
+ **await SessionClient(reactor=world.reactor, http_client=world.http).client_authentication(
+ client_id=world.atlas.client_id, issuer=SHOP
+ ),
+ )
+ assert (owned.status_code, owned.json()["error"]) == (400, "invalid_grant")
+
+ # And a public client's code is nothing to a personal agent with a valid assertion.
+ public_code = await code_for(world, client_id, LOOPBACK)
+ assertion = await SessionClient(
+ reactor=world.reactor, http_client=world.http
+ ).client_authentication(client_id=world.atlas.client_id, issuer=SHOP)
+ crossed = await token(
+ world,
+ grant_type="authorization_code",
+ code=public_code,
+ redirect_uri=LOOPBACK,
+ code_verifier=pkce()[0],
+ **assertion,
+ )
+ assert (crossed.status_code, crossed.json()["error"]) == (400, "invalid_grant")
+
+
+@pytest.mark.asyncio
+async def test_a_document_is_one_class_of_client_and_never_both() -> None:
+ both = document(jwks_uri="https://client.example/jwks.json")
+ with pytest.raises(ValidationError):
+ PublicClientMetadata.model_validate(both)
+ with pytest.raises(ValidationError):
+ PublicClientMetadata.model_validate(
+ document(**{"token_endpoint_auth_method": "private_key_jwt"})
+ )
+ with pytest.raises(ValidationError):
+ # Said, never assumed: a document that leaves the method out is no public client's.
+ PublicClientMetadata.model_validate(
+ {k: v for k, v in document().items() if k != "token_endpoint_auth_method"}
+ )
+ with pytest.raises(ValidationError):
+ PublicClientMetadata.model_validate(document(client_secret="s3cret")) # noqa: S106
+ world = public_world(site=both)
+ page = await authorize(world, VERIFIED, VERIFIED_REDIRECT)
+ assert page.status_code == 400 and "location" not in page.headers
+
+ # A redirect on another host than the document's is never matched; loopback is.
+ world = public_world()
+ stray = await authorize(world, VERIFIED, "https://elsewhere.example/callback")
+ assert stray.status_code == 400 and "location" not in stray.headers
+ assert (await authorize(world, VERIFIED, "http://127.0.0.1:8123/callback")).status_code == 200
+
+
+@pytest.mark.asyncio
+async def test_a_document_at_a_private_address_is_never_fetched() -> None:
+ fetched: list[str] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ fetched.append(str(request.url))
+ return httpx.Response(200, json=document())
+
+ async def private(_host: str) -> list[str]:
+ return ["10.0.0.7"]
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
+ identity = AgentIdentityClient(http_client=http, address_resolver=private)
+ with pytest.raises(PersonalAgentProtocolError):
+ await identity.fetch_public_metadata(VERIFIED)
+ for literal in (
+ "https://127.0.0.1/client.json",
+ "https://169.254.169.254/latest/meta-data",
+ "https://[::1]/client.json",
+ "http://client.example/oauth/client.json",
+ ):
+ with pytest.raises(PersonalAgentProtocolError):
+ await identity.fetch_public_metadata(literal)
+ assert fetched == []
+
+
+@pytest.mark.asyncio
+async def test_a_document_that_redirects_or_names_another_url_is_refused() -> None:
+ def redirecting(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(302, headers={"location": "https://10.0.0.7/client.json"})
+
+ def another(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=document(client_id="https://other.example/client.json"))
+
+ async def public(_host: str) -> list[str]:
+ return ["93.184.216.34"]
+
+ for handler in (redirecting, another):
+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
+ identity = AgentIdentityClient(http_client=http, address_resolver=public)
+ with pytest.raises(PersonalAgentProtocolError):
+ await identity.fetch_public_metadata(VERIFIED)
+
+
+# PKCE, codes, redirects -----------------------------------------------------------------------
+
+
+@pytest.mark.asyncio
+async def test_pkce_is_the_only_proof_and_is_never_skipped() -> None:
+ world = public_world()
+ client_id = await registered(world)
+ for changes in (
+ {"code_challenge": None},
+ {"code_challenge_method": None},
+ {"code_challenge_method": "plain"},
+ {"code_challenge": "short"},
+ {"response_type": "token"},
+ ):
+ page = await authorize(world, client_id, LOOPBACK, **changes)
+ # An unverified client is answered a page, never a redirect.
+ assert page.status_code == 400 and "location" not in page.headers, changes
+
+ form = {
+ "grant_type": "authorization_code",
+ "client_id": client_id,
+ "redirect_uri": LOOPBACK,
+ "resource": MCP,
+ }
+ for verifier in (None, "", "w" * 43, "v" * 42, "v" * 129, "v" * 42 + "!"):
+ code = await code_for(world, client_id, LOOPBACK)
+ attempt = dict(form, code=code)
+ if verifier is not None:
+ attempt["code_verifier"] = verifier
+ refused = await token(world, **attempt)
+ assert (refused.status_code, refused.json()["error"]) == (400, "invalid_grant"), verifier
+ # A refused exchange spent the code: the right verifier gets nothing after it.
+ again = await token(world, **dict(form, code=code, code_verifier=pkce()[0]))
+ assert again.json()["error"] == "invalid_grant"
+
+ # A code is the client's it was issued to, for the redirect it was issued for, once.
+ other = await registered(world, client_name="Another")
+ code = await code_for(world, client_id, LOOPBACK)
+ stolen = await token(world, **dict(form, client_id=other, code=code, code_verifier=pkce()[0]))
+ assert stolen.json()["error"] == "invalid_grant"
+ code = await code_for(world, client_id, LOOPBACK)
+ moved = await token(
+ world,
+ **dict(
+ form, code=code, code_verifier=pkce()[0], redirect_uri="http://127.0.0.1:1/callback"
+ ),
+ )
+ assert moved.json()["error"] == "invalid_grant"
+ code = await code_for(world, client_id, LOOPBACK)
+ first = await token(world, **dict(form, code=code, code_verifier=pkce()[0]))
+ assert first.status_code == 200
+ second = await token(world, **dict(form, code=code, code_verifier=pkce()[0]))
+ assert second.json()["error"] == "invalid_grant"
+
+
+def test_a_redirect_uri_is_loopback_or_https_and_nothing_else() -> None:
+ for accepted in (
+ "https://client.example/callback",
+ "https://client.example:8443/callback?tenant=1",
+ "https://xn--bcher-kva.example/cb",
+ "http://127.0.0.1/callback",
+ "http://127.0.0.1:53211/callback",
+ "http://[::1]:53211/callback",
+ "http://localhost:53211/callback",
+ ):
+ assert public_redirect_uri(accepted) == accepted
+ for refused in (
+ "",
+ "HTTPS://client.example/callback",
+ "https:/client.example/callback",
+ "https://client.example.:443/callback",
+ "http://client.example/callback",
+ "https://user@client.example/callback",
+ "https://user:pw@client.example/callback",
+ "https://client.example@evil.example/callback",
+ "https://client.example/callback#fragment",
+ "https://client.example/callback#",
+ "https://Client.example/callback",
+ "https://client.example\\@evil.example/callback",
+ "https://client.example /callback",
+ "https://client.example/call\tback",
+ "https://client.example/call\nback",
+ "https:///callback",
+ "https://client.example:0/callback",
+ "https://client.example:70000/callback",
+ "https://[::1]/callback",
+ "https://bücher.example/cb",
+ "http://127.0.0.1.evil.example/callback",
+ "http://127.0.0.1:80@evil.example/callback",
+ "http://localhost.evil.example/callback",
+ "http://127.1/callback",
+ "http://2130706433/callback",
+ "http://0.0.0.0/callback",
+ "http://10.0.0.1/callback",
+ "http://localhost:99999/callback",
+ "cursor://callback",
+ "javascript:alert(1)",
+ "data:text/html,x",
+ "//client.example/callback",
+ "https://client.example/" + "a" * 2000,
+ ):
+ with pytest.raises(ValueError):
+ public_redirect_uri(refused)
+ assert is_public_loopback_redirect("http://localhost/cb")
+ assert not is_public_loopback_redirect("https://localhost/cb")
+
+
+def test_a_redirect_uri_matches_exactly_but_for_a_loopback_port() -> None:
+ https = "https://client.example/callback"
+ assert public_redirect_uri_matches(https, https)
+ for other in (
+ "https://client.example/callback/",
+ "https://client.example/callback?next=https://evil.example",
+ "https://client.example/callback/../evil",
+ "https://client.example:8443/callback",
+ "https://client.example/Callback",
+ "https://client.example.evil.example/callback",
+ "https://evil.example/callback",
+ "https://client.example/callback#x",
+ "https://client.example/callback%2f..",
+ ):
+ assert not public_redirect_uri_matches(https, other), other
+ loopback = "http://127.0.0.1/callback"
+ assert public_redirect_uri_matches(loopback, "http://127.0.0.1:53211/callback")
+ for other in (
+ "http://127.0.0.1:53211/other",
+ "http://127.0.0.1:53211/callback?x=1",
+ "http://localhost:53211/callback",
+ "http://[::1]:53211/callback",
+ "https://127.0.0.1:53211/callback",
+ "http://127.0.0.1:53211@evil.example/callback",
+ "http://127.0.0.1:99999/callback",
+ ):
+ assert not public_redirect_uri_matches(loopback, other), other
+
+
+@pytest.mark.asyncio
+async def test_a_request_with_another_redirect_is_never_redirected() -> None:
+ world = public_world()
+ client_id = await registered(world, redirect_uris=["https://pocket.example/callback"])
+ for redirect_uri in (
+ "https://pocket.example/callback?next=https://evil.example",
+ "https://pocket.example/callback/..%2fevil",
+ "https://user@pocket.example/callback",
+ "https://pocket.example.evil.example/callback",
+ "https://pocket.example/callback#x",
+ "https://evil.example/callback",
+ "http://127.0.0.1/callback",
+ "",
+ ):
+ page = await authorize(world, client_id, redirect_uri)
+ assert page.status_code == 400 and "location" not in page.headers, redirect_uri
+
+
+@pytest.mark.asyncio
+async def test_an_unverified_clients_errors_are_pages_and_a_verified_ones_redirects() -> None:
+ """Anyone registers any HTTPS redirect: answered with no one's consent, an error
+ would make the authorization endpoint an open redirector (RFC 9700 §4.11.2)."""
+
+ world = public_world()
+ client_id = await registered(world, redirect_uris=["https://pocket.example/callback"])
+ for changes in ({"scope": "nothing:here"}, {"scope": ""}, {"resource": SHOP}):
+ page = await authorize(world, client_id, "https://pocket.example/callback", **changes)
+ assert page.status_code == 400 and "location" not in page.headers, changes
+ # A client verified by its domain is answered at its own domain, with state and issuer.
+ answered = await authorize(world, VERIFIED, VERIFIED_REDIRECT, scope="nothing:here")
+ assert answered.status_code == 303
+ query = parse_qs(urlsplit(answered.headers["location"]).query)
+ assert answered.headers["location"].startswith(f"{VERIFIED_REDIRECT}?")
+ assert query == {"error": ["invalid_scope"], "state": ["st-1"], "iss": [SHOP]}
+ # A refusal by the person reaches either, after they decided.
+ page = await authorize(world, client_id, "https://pocket.example/callback")
+ denied = await world.shop.deny_authorization(request_id_of(page))
+ assert parse_qs(urlsplit(denied).query) == {
+ "error": ["access_denied"],
+ "state": ["st-1"],
+ "iss": [SHOP],
+ }
+
+
+@pytest.mark.asyncio
+async def test_a_decision_counts_once_and_the_name_is_shown_as_text() -> None:
+ world = public_world()
+ client_id = await registered(world, client_name="")
+ page = await authorize(world, client_id, LOOPBACK)
+ assert "
None:
+ world = public_world()
+ # Whatever the setting says for personal agents.
+ assert world.shop.config.refresh_reuse_revokes is False
+ client_id = await registered(world)
+ tokens = await sign_in(world, client_id)
+ first = await refresh(world, client_id, tokens["refresh_token"])
+ assert first.status_code == 200, first.text
+ rotated = first.json()
+ assert rotated["refresh_token"] != tokens["refresh_token"]
+ assert rotated["token_type"] == "Bearer"
+ assert (await mcp(world, rotated["access_token"], LIST_TOOLS)).status_code == 200
+
+ # The first one again: whoever holds a copy, the whole sign-in ends.
+ replayed = await refresh(world, client_id, tokens["refresh_token"])
+ assert (replayed.status_code, replayed.json()["error"]) == (400, "invalid_grant")
+ after = await refresh(world, client_id, rotated["refresh_token"])
+ assert after.json()["error"] == "invalid_grant"
+ for access_token in (tokens["access_token"], rotated["access_token"]):
+ assert (await mcp(world, access_token, LIST_TOOLS)).status_code == 401
+ assert await world.shop.public_client_sign_ins() == ()
+
+
+@pytest.mark.asyncio
+async def test_a_refresh_token_is_its_clients_and_lasts_thirty_days() -> None:
+ world = public_world()
+ client_id = await registered(world)
+ other = await registered(world, client_name="Another")
+ tokens = await sign_in(world, client_id)
+ stolen = await refresh(world, other, tokens["refresh_token"])
+ assert stolen.json()["error"] == "invalid_grant"
+ unknown = await refresh(world, "mcpc_AAAAAAAAAAAAAAAAAAAAAA", tokens["refresh_token"])
+ assert (unknown.status_code, unknown.json()["error"]) == (401, "invalid_client")
+ # Narrower scopes only.
+ wider = await refresh(world, client_id, tokens["refresh_token"], scope="orders:write")
+ assert wider.json()["error"] == "invalid_scope"
+
+ world.clock.advance(29 * 24 * 3600)
+ kept = await refresh(world, client_id, tokens["refresh_token"])
+ assert kept.status_code == 200
+ # Thirty days from the sign-in, not from the last refresh.
+ world.clock.advance(2 * 24 * 3600)
+ late = await refresh(world, client_id, kept.json()["refresh_token"])
+ assert late.json()["error"] == "invalid_grant"
+
+
+@pytest.mark.asyncio
+async def test_no_token_of_a_sign_in_outlives_it() -> None:
+ """Thirty days from the consent, exactly: refreshed a minute before they end, the
+ access token ends with them. Once the sign-in is over its owner can no longer list
+ or revoke it, so nothing of it works."""
+
+ world = public_world()
+ client_id = await registered(world)
+ tokens = await sign_in(world, client_id, resource=ELSEWHERE)
+ assert tokens["expires_in"] == 3600
+ world.clock.advance(30 * 24 * 3600 - 60)
+ last = await refresh(world, client_id, tokens["refresh_token"], resource=ELSEWHERE)
+ assert last.status_code == 200
+ assert 0 < last.json()["expires_in"] <= 60
+ late = last.json()["access_token"]
+ record = await world.shop.access_token_for(late, ELSEWHERE)
+ assert record is not None
+ assert record.expires_at == (await world.shop.public_client_sign_ins())[0].expires_at
+ world.clock.advance(59)
+ assert await world.shop.access_token_for(late, ELSEWHERE) is not None
+ # The deadline: refused at the resource server, and nothing is left to list.
+ world.clock.advance(1)
+ assert await world.shop.access_token_for(late, ELSEWHERE) is None
+ assert await world.shop.public_client_sign_ins() == ()
+ after = await refresh(world, client_id, last.json()["refresh_token"], resource=ELSEWHERE)
+ assert after.json()["error"] == "invalid_grant"
+ # The same at the company's own MCP server.
+ own = await sign_in(world, client_id)
+ world.clock.advance(30 * 24 * 3600 - 60)
+ last_own = (await refresh(world, client_id, own["refresh_token"])).json()
+ assert 0 < last_own["expires_in"] <= 60
+ assert (await mcp(world, last_own["access_token"], LIST_TOOLS)).status_code == 200
+ world.clock.advance(60)
+ assert (await mcp(world, last_own["access_token"], LIST_TOOLS)).status_code == 401
+
+
+@pytest.mark.asyncio
+async def test_a_token_whose_sign_in_record_is_gone_is_refused() -> None:
+ """Whatever the token's own record says: it is held to its sign-in, which the owner
+ lists and revokes. A personal agent's token is read as before."""
+
+ for kind in ("refresh_token", "account_family"):
+ world = public_world()
+ client_id = await registered(world)
+ elsewhere = await sign_in(world, client_id, resource=ELSEWHERE)
+ own = await sign_in(world, client_id)
+ assert await world.shop.access_token_for(elsewhere["access_token"], ELSEWHERE)
+ assert (await mcp(world, own["access_token"], LIST_TOOLS)).status_code == 200
+ for entry in await world.shop.public_client_sign_ins():
+ await world.shop.store.delete(kind, entry.sign_in_id)
+ assert await world.shop.access_token_for(elsewhere["access_token"], ELSEWHERE) is None, kind
+ assert (await mcp(world, own["access_token"], LIST_TOOLS)).status_code == 401, kind
+
+
+@pytest.mark.asyncio
+async def test_a_public_client_revokes_its_own_sign_in() -> None:
+ world = public_world()
+ client_id = await registered(world)
+ other = await registered(world, client_name="Another")
+ tokens = await sign_in(world, client_id)
+ # Another client's request ends nothing.
+ await world.http.post(
+ f"{SHOP}/oauth/revoke", data={"client_id": other, "token": tokens["refresh_token"]}
+ )
+ assert (await mcp(world, tokens["access_token"], LIST_TOOLS)).status_code == 200
+ done = await world.http.post(
+ f"{SHOP}/oauth/revoke", data={"client_id": client_id, "token": tokens["refresh_token"]}
+ )
+ assert done.status_code == 200
+ assert (await mcp(world, tokens["access_token"], LIST_TOOLS)).status_code == 401
+ assert (await refresh(world, client_id, tokens["refresh_token"])).json()[
+ "error"
+ ] == "invalid_grant"
+
+
+# Registration ---------------------------------------------------------------------------------
+
+
+@pytest.mark.asyncio
+async def test_only_a_public_client_registers() -> None:
+ world = public_world(client_registrations_per_hour=1000)
+ accepted = await register(world)
+ body = accepted.json()
+ assert accepted.status_code == 201 and accepted.headers["cache-control"] == "no-store"
+ assert body["token_endpoint_auth_method"] == "none"
+ assert body["grant_types"] == ["authorization_code", "refresh_token"]
+ assert body["response_types"] == ["code"]
+ assert "client_secret" not in body and "registration_access_token" not in body
+ assert (await register(world, client_name=None)).status_code == 400
+ # Another method, a null one, or a key or a secret of its own: told exactly what to send.
+ for changes in (
+ {"token_endpoint_auth_method": "private_key_jwt"},
+ {"token_endpoint_auth_method": None},
+ {"client_secret": "s3cret"},
+ ):
+ told = (await register(world, **changes)).json()
+ assert told["error"] == "invalid_client_metadata"
+ assert '"token_endpoint_auth_method": "none"' in told["error_description"]
+
+ refusals: list[tuple[dict[str, object], str]] = [
+ ({"token_endpoint_auth_method": "tls_client_auth"}, "invalid_client_metadata"),
+ ({"token_endpoint_auth_method": "NONE"}, "invalid_client_metadata"),
+ ({"token_endpoint_auth_method": "client_secret_jwt"}, "invalid_client_metadata"),
+ ({"token_endpoint_auth_method": "private_key_jwt"}, "invalid_client_metadata"),
+ ({"token_endpoint_auth_method": None}, "invalid_client_metadata"),
+ ({"jwks_uri": "https://pocket.example/jwks.json"}, "invalid_client_metadata"),
+ ({"jwks": {"keys": []}}, "invalid_client_metadata"),
+ ({"client_secret": "s3cret"}, "invalid_client_metadata"),
+ ({"grant_types": ["client_credentials"]}, "invalid_client_metadata"),
+ ({"grant_types": ["refresh_token"]}, "invalid_client_metadata"),
+ ({"grant_types": ["authorization_code", DEVICE_CODE_GRANT]}, "invalid_client_metadata"),
+ ({"grant_types": ["authorization_code", {}]}, "invalid_client_metadata"),
+ ({"grant_types": ["authorization_code", ["refresh_token"]]}, "invalid_client_metadata"),
+ ({"grant_types": {"authorization_code": 1}}, "invalid_client_metadata"),
+ ({"response_types": ["token"]}, "invalid_client_metadata"),
+ ({"response_types": [{}]}, "invalid_client_metadata"),
+ ({"redirect_uris": [{}]}, "invalid_redirect_uri"),
+ ({"redirect_uris": [[LOOPBACK]]}, "invalid_redirect_uri"),
+ ({"client_name": ""}, "invalid_client_metadata"),
+ ({"client_name": "x" * 101}, "invalid_client_metadata"),
+ ({"client_name": "Claude (verified)"}, "invalid_client_metadata"),
+ ({"client_name": "Claude\u0000"}, "invalid_client_metadata"),
+ ({"client_name": 7}, "invalid_client_metadata"),
+ ({"redirect_uris": []}, "invalid_redirect_uri"),
+ ({"redirect_uris": "https://pocket.example/callback"}, "invalid_redirect_uri"),
+ ({"redirect_uris": [LOOPBACK, LOOPBACK]}, "invalid_redirect_uri"),
+ (
+ {"redirect_uris": [f"https://pocket.example/{n}" for n in range(11)]},
+ "invalid_redirect_uri",
+ ),
+ ({"redirect_uris": ["http://pocket.example/callback"]}, "invalid_redirect_uri"),
+ ({"redirect_uris": ["cursor://callback"]}, "invalid_redirect_uri"),
+ ({"redirect_uris": ["https://user@pocket.example/cb"]}, "invalid_redirect_uri"),
+ ({"redirect_uris": ["https://pocket.example/cb#x"]}, "invalid_redirect_uri"),
+ ({"redirect_uris": [LOOPBACK, 7]}, "invalid_redirect_uri"),
+ ]
+ for changes, error in refusals:
+ refused = await register(world, **changes)
+ assert (refused.status_code, refused.json()["error"]) == (400, error), changes
+ for content in (b"[]", b"not json", b'{"a": 1, "a": 2}', b" " * (16 * 1024 + 1)):
+ refused = await world.http.post(
+ f"{SHOP}/oauth/register", content=content, headers={"content-type": "application/json"}
+ )
+ assert refused.status_code == 400, content[:10]
+
+
+@pytest.mark.asyncio
+async def test_whatever_method_a_registration_asks_for_it_is_registered_as_public() -> None:
+ """RFC 7591 §3.2.1: the server may replace what was requested, and the client uses
+ what is returned. Left out, `none`, or a method that only says how a secret would be
+ sent: a public client each time, told so, with no secret."""
+
+ world = public_world(client_registrations_per_hour=1000)
+ asked: tuple[dict[str, object], ...] = (
+ {},
+ {"token_endpoint_auth_method": "none"},
+ {"token_endpoint_auth_method": "client_secret_post"},
+ {"token_endpoint_auth_method": "client_secret_basic"},
+ )
+ for method in asked:
+ body = {"client_name": "Pocket MCP", "redirect_uris": [LOOPBACK], **method}
+ answer = await world.http.post(f"{SHOP}/oauth/register", json=body)
+ assert answer.status_code == 201, (method, answer.text)
+ said = answer.json()
+ assert said["token_endpoint_auth_method"] == "none", method
+ assert "client_secret" not in said and "client_secret_expires_at" not in said, method
+ assert said["grant_types"] == ["authorization_code", "refresh_token"]
+ # It signs in as any public client does: PKCE, and no secret.
+ tokens = await sign_in(world, said["client_id"])
+ assert tokens["token_type"] == "Bearer"
+ assert (await mcp(world, tokens["access_token"], LIST_TOOLS)).status_code == 200
+ # None of them is anything but a public client's record.
+ for record in await world.shop.store.records("public_client"):
+ assert set(record.value) == {"client_id", "client_name", "redirect_uris", "registered_at"}
+
+
+@pytest.mark.asyncio
+async def test_a_secret_sent_at_the_token_endpoint_is_refused_never_taken() -> None:
+ """No client has one. A request that sends one, in its form or as HTTP Basic, is
+ refused and told why: it is never served as if the secret had been right, and it
+ spends neither the code nor the refresh token."""
+
+ world = public_world()
+ client_id = await registered(world, **{"token_endpoint_auth_method": "client_secret_post"})
+ code = await code_for(world, client_id, LOOPBACK)
+ form = {
+ "grant_type": "authorization_code",
+ "client_id": client_id,
+ "code": code,
+ "redirect_uri": LOOPBACK,
+ "code_verifier": pkce()[0],
+ "resource": MCP,
+ }
+ basic = {"authorization": "Basic " + base64.b64encode(f"{client_id}:guess".encode()).decode()}
+ # Its `client_id` as HTTP Basic with an empty password, as some libraries send it.
+ empty = {"Authorization": "Basic " + base64.b64encode(f"{client_id}:".encode()).decode()}
+ for refused in (
+ await token(world, **form, **{"client_secret": "guess"}),
+ await world.http.post(f"{SHOP}/oauth/token", data=form, headers=basic),
+ await world.http.post(f"{SHOP}/oauth/token", data=form, headers=empty),
+ ):
+ assert (refused.status_code, refused.json()["error"]) == (401, "invalid_client")
+ assert "no secret" in refused.json()["error_description"]
+ # The code was not spent: the same request without a secret signs in.
+ signed_in_ = await token(world, **form)
+ assert signed_in_.status_code == 200, signed_in_.text
+ tokens = signed_in_.json()
+ with_secret = await refresh(
+ world, client_id, tokens["refresh_token"], **{"client_secret": "guess"}
+ )
+ assert (with_secret.status_code, with_secret.json()["error"]) == (401, "invalid_client")
+ revoking = await world.http.post(
+ f"{SHOP}/oauth/revoke",
+ data={"client_id": client_id, "token": tokens["refresh_token"], "client_secret": "guess"},
+ )
+ assert revoking.status_code == 401
+ # Neither spent the refresh token nor ended the sign-in.
+ assert (await mcp(world, tokens["access_token"], LIST_TOOLS)).status_code == 200
+ assert (await refresh(world, client_id, tokens["refresh_token"])).status_code == 200
+
+
+@pytest.mark.asyncio
+async def test_a_malformed_registration_is_the_callers_mistake_never_an_error_of_ours() -> None:
+ """Nobody signed the body: whatever is in it, the answer is 400 and says so."""
+
+ world = public_world(client_registrations_per_hour=1000)
+ nothing: Any = None
+ odd: list[Any] = [
+ nothing,
+ True,
+ 7,
+ 1.5,
+ "text",
+ [],
+ {},
+ [[]],
+ [{}],
+ {"a": {"b": []}},
+ [nothing],
+ ]
+ for member in (
+ "token_endpoint_auth_method",
+ "grant_types",
+ "response_types",
+ "redirect_uris",
+ "client_name",
+ "scope",
+ "jwks",
+ "jwks_uri",
+ "client_secret",
+ ):
+ for value in odd:
+ if value == "text" and member in {"scope", "client_name"}:
+ continue
+ answer = await register(world, **{member: value})
+ assert answer.status_code == 400, (member, value, answer.text)
+ assert answer.json()["error"] in {
+ "invalid_client_metadata",
+ "invalid_redirect_uri",
+ }, (member, value)
+ # Members a public client may send and the company does not read: taken, whatever they are.
+ for member in ("contacts", "client_uri", "logo_uri", "tos_uri", "software_id", "unknown"):
+ for value in odd:
+ assert (await register(world, **{member: value})).status_code == 201, (member, value)
+ # Entries of the wrong type, too many, too long, and bodies that are no registration.
+ for changes in (
+ {"redirect_uris": [LOOPBACK, None]},
+ {"redirect_uris": [LOOPBACK, {"uri": LOOPBACK}]},
+ {"redirect_uris": [LOOPBACK] * 2},
+ {"redirect_uris": ["https://pocket.example/" + "a" * 2000]},
+ {"redirect_uris": {"0": LOOPBACK}},
+ {"grant_types": ["authorization_code", None]},
+ {"grant_types": [["authorization_code"]]},
+ {"response_types": ["code", "code"]},
+ {"response_types": [None]},
+ {"client_name": ["Pocket"]},
+ ):
+ answer = await register(world, **changes)
+ assert answer.status_code == 400, changes
+ deep = b"[" * 8000 + b"]" * 8000
+ nested = b'{"redirect_uris": ' + deep + b', "token_endpoint_auth_method": "none"}'
+ for content in (
+ b"",
+ b"null",
+ b"7",
+ b'"text"',
+ b"[]",
+ b"{",
+ b"\xff\xfe",
+ b'{"token_endpoint_auth_method": "none", "token_endpoint_auth_method": "none"}',
+ b'{"redirect_uris": NaN}',
+ deep,
+ nested,
+ b" " * (16 * 1024 + 1),
+ ):
+ answer = await world.http.post(
+ f"{SHOP}/oauth/register", content=content, headers={"content-type": "application/json"}
+ )
+ assert answer.status_code == 400, content[:20]
+ assert answer.json()["error"] in {
+ "invalid_client_metadata",
+ "invalid_redirect_uri",
+ }, content[:20]
+
+
+@pytest.mark.asyncio
+async def test_what_no_check_foresaw_is_refused_and_logged(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ from personal_agent_protocol.company import service
+
+ def broken(_value: object) -> str:
+ raise TypeError("a bug of ours")
+
+ world = public_world()
+ monkeypatch.setattr(service, "public_client_name", broken)
+ with caplog.at_level("ERROR", logger=service.logger.name):
+ answer = await register(world)
+ assert (answer.status_code, answer.json()["error"]) == (400, "invalid_client_metadata")
+ assert "a bug of ours" in caplog.text
+ assert not await world.shop.store.records("public_client")
+
+
+@pytest.mark.asyncio
+async def test_a_document_of_any_shape_is_refused_not_raised() -> None:
+ nothing: Any = None
+ for changes in (
+ {"redirect_uris": "https://client.example/callback"},
+ {"redirect_uris": [7, nothing, {}]},
+ {"redirect_uris": []},
+ {"client_name": 7},
+ {"client_name": nothing},
+ {"client_id": 7},
+ {"grant_types": "authorization_code"},
+ {"grant_types": [{}]},
+ {"response_types": [[]]},
+ {"token_endpoint_auth_method": ["none"]},
+ {"logo_uri": 7},
+ ):
+ with pytest.raises(ValidationError):
+ PublicClientMetadata.model_validate(document(**changes))
+ world = public_world(site=document(**changes))
+ page = await authorize(world, VERIFIED, VERIFIED_REDIRECT)
+ assert page.status_code == 400 and "location" not in page.headers, changes
+ for site in ([], "text", 7, nothing, [document()]):
+ world = public_world()
+ world.network.add("client.example", json_site({"/oauth/client.json": site}))
+ assert (await authorize(world, VERIFIED, VERIFIED_REDIRECT)).status_code == 400, site
+ assert (await refresh(world, VERIFIED, "rt_x")).status_code == 401, site
+
+
+@pytest.mark.asyncio
+async def test_registration_is_limited_by_address() -> None:
+ world = public_world(client_registrations_per_hour=3)
+ for _ in range(3):
+ assert (await register(world)).status_code == 201
+ limited = await register(world)
+ assert limited.status_code == 429
+ assert 0 < int(limited.headers["retry-after"]) <= 3600
+ # A refused registration counts too: the limit is on asking, not on succeeding.
+ assert (await register(world, redirect_uris=[])).status_code == 429
+ world.clock.advance(3601)
+ assert (await register(world)).status_code == 201
+
+ # Another address has its own count; a request that names none shares one.
+ direct = [
+ await world.shop.handle(_registration(address))
+ for address in ("203.0.113.5", "203.0.113.5", None, None)
+ ]
+ assert [response.status for response in direct] == [201, 201, 201, 201]
+
+
+def _registration(address: str | None) -> CompanyRequest:
+ return CompanyRequest(
+ method="POST",
+ url=f"{SHOP}/oauth/register",
+ headers={"content-type": "application/json"},
+ body=json.dumps(
+ {"redirect_uris": [LOOPBACK], "token_endpoint_auth_method": "none"}
+ ).encode(),
+ client_address=address,
+ )
+
+
+@pytest.mark.asyncio
+async def test_the_hosts_rate_limit_is_asked_by_address_before_anything_is_read() -> None:
+ asked: list[tuple[str, str | None]] = []
+
+ class Limited:
+ async def admit(self, client_id: str, account_id: str | None) -> int | None:
+ asked.append((client_id, account_id))
+ return 120 if client_id.startswith("registration:") else None
+
+ class Plugin:
+ @hookimpl
+ def provide_contributions(self, contributions: object) -> None:
+ contributions.contribute(COMPANY_RATE_LIMITS, Limited(), contribution_id="limit") # type: ignore[attr-defined]
+
+ world = public_world()
+ world.shop.reactor.register_plugin(PluginManifest(name="limit", version="1"), Plugin())
+ refused = await world.http.post(f"{SHOP}/oauth/register", content=b"not json")
+ assert refused.status_code == 429 and refused.headers["retry-after"] == "120"
+ assert asked == [("registration:127.0.0.1", None)]
+ assert not await world.shop.store.records("public_client")
+
+
+@pytest.mark.asyncio
+async def test_a_registration_is_kept_briefly_until_it_is_used_and_long_after() -> None:
+ world = public_world()
+ # Never used: gone an hour after it registered, so registering alone fills nothing.
+ unused = await registered(world, client_name="Never used")
+ world.clock.advance(3599)
+ assert (await authorize(world, unused, LOOPBACK)).status_code == 200
+ world.clock.advance(2)
+ assert (await authorize(world, unused, LOOPBACK)).status_code == 400
+ assert not await world.shop.store.records("public_client")
+
+ # Signed in within the hour: kept ninety days from then, outliving the sign-in it gave.
+ client_id = await registered(world)
+ world.clock.advance(1800)
+ tokens = await sign_in(world, client_id)
+ world.clock.advance(20 * 24 * 3600)
+ assert (await refresh(world, client_id, tokens["refresh_token"])).status_code == 200
+ world.clock.advance(69 * 24 * 3600)
+ again = await sign_in(world, client_id)
+ assert again["access_token"]
+ world.clock.advance(91 * 24 * 3600)
+ assert (await authorize(world, client_id, LOOPBACK)).status_code == 400
+
+
+@pytest.mark.asyncio
+async def test_requests_without_an_assertion_are_limited_by_address() -> None:
+ """Each may make the company read a client's document: the host's limit is asked
+ first, by address, never by the `client_id` the request invents."""
+
+ asked: list[tuple[str, str | None]] = []
+ refusing = False
+
+ class Limited:
+ async def admit(self, client_id: str, account_id: str | None) -> int | None:
+ asked.append((client_id, account_id))
+ return 30 if refusing and client_id.startswith("public:") else None
+
+ class Plugin:
+ @hookimpl
+ def provide_contributions(self, contributions: object) -> None:
+ contributions.contribute(COMPANY_RATE_LIMITS, Limited(), contribution_id="limit") # type: ignore[attr-defined]
+
+ fetched: list[str] = []
+ site = json_site({"/oauth/client.json": document()})
+
+ async def watched(scope: Any, receive: Any, send: Any) -> None:
+ fetched.append(scope["path"])
+ await site(scope, receive, send)
+
+ world = public_world()
+ world.network.add("client.example", watched)
+ world.shop.reactor.register_plugin(PluginManifest(name="limit", version="1"), Plugin())
+ refusing = True
+ limited = await refresh(world, VERIFIED, "rt_x")
+ assert limited.status_code == 429 and limited.headers["retry-after"] == "30"
+ revoked = await world.http.post(
+ f"{SHOP}/oauth/revoke", data={"client_id": "https://anything.example/c", "token": "rt_x"}
+ )
+ assert revoked.status_code == 429
+ assert asked == [("public:127.0.0.1", None), ("public:127.0.0.1", None)]
+ # Refused before the client was looked at: nothing was fetched for it.
+ assert fetched == []
+ refusing = False
+ assert (await refresh(world, VERIFIED, "rt_x")).json()["error"] == "invalid_grant"
+ assert fetched == ["/oauth/client.json"]
+
+
+# The client policy, and what the company gives now -------------------------------------------
+
+
+class Policy:
+ """Blocks, refuses sign-in to, or leaves a service out for, the clients it is told."""
+
+ def __init__(self) -> None:
+ self.blocked: set[str] = set()
+ self.no_sign_in: set[str] = set()
+ self.no_resource: set[tuple[str, str]] = set()
+ self.asked: list[str] = []
+
+ async def allows(self, client_id: str) -> bool:
+ self.asked.append(client_id)
+ return client_id not in self.blocked
+
+ async def allows_sign_in(self, client_id: str, grant_type: str) -> bool:
+ return client_id not in self.no_sign_in
+
+ async def allows_resource(self, client_id: str, resource: str) -> bool:
+ return (client_id, resource) not in self.no_resource
+
+
+def with_policy(world: World) -> Policy:
+ policy = Policy()
+
+ class Plugin:
+ @hookimpl
+ def provide_contributions(self, contributions: object) -> None:
+ contributions.contribute(CLIENT_POLICIES, policy, contribution_id="p", order=-10) # type: ignore[attr-defined]
+
+ world.shop.reactor.register_plugin(PluginManifest(name="policy", version="1"), Plugin())
+ return policy
+
+
+@pytest.mark.asyncio
+async def test_the_client_policy_is_asked_each_time_and_before_anything_is_fetched() -> None:
+ world = public_world()
+ policy = with_policy(world)
+ client_id = await registered(world)
+ own = await sign_in(world, client_id)
+ elsewhere = await sign_in(world, client_id, resource=ELSEWHERE)
+ assert await world.shop.access_token_for(elsewhere["access_token"], ELSEWHERE) is not None
+
+ # Left out of one service: its token for it stops at once, the other still works.
+ policy.no_resource.add((client_id, ELSEWHERE))
+ assert await world.shop.access_token_for(elsewhere["access_token"], ELSEWHERE) is None
+ assert (await mcp(world, own["access_token"], LIST_TOOLS)).status_code == 200
+ assert (await refresh(world, client_id, elsewhere["refresh_token"], resource=ELSEWHERE)).json()[
+ "error"
+ ] == "invalid_target"
+ assert (await authorize(world, client_id, LOOPBACK, resource=ELSEWHERE)).status_code == 400
+ policy.no_resource.clear()
+
+ # Refused sign-in: nothing new, and a code already issued gives nothing.
+ code = await code_for(world, client_id, LOOPBACK)
+ policy.no_sign_in.add(client_id)
+ assert (await authorize(world, client_id, LOOPBACK)).status_code == 400
+ late = await token(
+ world,
+ grant_type="authorization_code",
+ client_id=client_id,
+ code=code,
+ redirect_uri=LOOPBACK,
+ code_verifier=pkce()[0],
+ resource=MCP,
+ )
+ assert late.json()["error"] == "unauthorized_client"
+ policy.no_sign_in.clear()
+
+ # Blocked: every token stops at once, everywhere.
+ policy.blocked.add(client_id)
+ assert (await mcp(world, own["access_token"], LIST_TOOLS)).status_code == 401
+ assert await world.shop.access_token_for(elsewhere["access_token"], ELSEWHERE) is None
+ blocked = await refresh(world, client_id, own["refresh_token"])
+ assert (blocked.status_code, blocked.json()["error"]) == (401, "invalid_client")
+ assert (await authorize(world, client_id, LOOPBACK)).status_code == 400
+
+ # A blocked URL is never fetched: the policy answers before the resolver is asked.
+ fetched: list[str] = []
+ site = json_site({"/oauth/client.json": document()})
+
+ async def watched(scope: Any, receive: Any, send: Any) -> None:
+ fetched.append(scope["path"])
+ await site(scope, receive, send)
+
+ fresh = public_world()
+ fresh_policy = with_policy(fresh)
+ fresh.network.add("client.example", watched)
+ fresh_policy.blocked.add(VERIFIED)
+ assert (await authorize(fresh, VERIFIED, VERIFIED_REDIRECT)).status_code == 400
+ assert (await refresh(fresh, VERIFIED, "rt_x")).status_code == 401
+ assert fetched == []
+
+
+@pytest.mark.asyncio
+async def test_a_verified_client_is_read_again_at_each_token_request() -> None:
+ """A document that became a personal agent's, or went away, gets nothing more."""
+
+ world = public_world()
+ tokens = await sign_in(world, VERIFIED, VERIFIED_REDIRECT)
+ assert (await refresh(world, VERIFIED, tokens["refresh_token"])).status_code == 200
+ # A new company process reads the document again, which now names keys.
+ restarted = World()
+ restarted.network.add(
+ "client.example",
+ json_site({"/oauth/client.json": document(jwks_uri="https://client.example/jwks.json")}),
+ )
+ restarted.shop, restarted.plugin = manzanita(
+ restarted.network,
+ restarted.clock,
+ store=world.shop.store,
+ config=world.shop.config,
+ )
+ refused = await refresh(restarted, VERIFIED, "rt_anything")
+ assert (refused.status_code, refused.json()["error"]) == (401, "invalid_client")
+
+
+@pytest.mark.asyncio
+async def test_turned_off_public_clients_tokens_stop() -> None:
+ world = public_world()
+ client_id = await registered(world)
+ own = await sign_in(world, client_id)
+ elsewhere = await sign_in(world, client_id, resource=ELSEWHERE)
+ world.shop.config = dataclasses.replace(
+ world.shop.config, public_client_scopes=("orders:write",)
+ )
+ # Outside what public clients are given now.
+ assert await world.shop.access_token_for(elsewhere["access_token"], ELSEWHERE) is None
+ assert (await mcp(world, own["access_token"], LIST_TOOLS)).status_code == 401
+ assert (await refresh(world, client_id, own["refresh_token"])).json()[
+ "error"
+ ] == "invalid_scope"
+ world.shop.config = dataclasses.replace(
+ world.shop.config,
+ public_clients=False,
+ client_registration=False,
+ public_client_scopes=None,
+ )
+ assert await world.shop.access_token_for(elsewhere["access_token"], ELSEWHERE) is None
+ assert (await mcp(world, own["access_token"], LIST_TOOLS)).status_code in {400, 401}
+ refused = await refresh(world, client_id, own["refresh_token"])
+ assert (refused.status_code, refused.json()["error"]) == (401, "invalid_client")
+
+
+@pytest.mark.asyncio
+async def test_sign_in_turned_off_for_personal_agents_leaves_public_clients() -> None:
+ world = public_world(sign_in_disabled=True, mediated_fields=(), ucp=False)
+ client_id = await registered(world)
+ tokens = await sign_in(world, client_id)
+ assert (await mcp(world, tokens["access_token"], LIST_TOOLS)).status_code == 200
+ # A personal agent is still refused there.
+ page = await authorize(
+ world, world.atlas.client_id, "https://atlas.example/oauth/callback", resource=None
+ )
+ assert page.status_code == 303
+ assert parse_qs(urlsplit(page.headers["location"]).query)["error"] == ["unauthorized_client"]
+
+
+# The owner's list -----------------------------------------------------------------------------
+
+
+@pytest.mark.asyncio
+async def test_the_owner_lists_and_revokes_public_clients_sign_ins() -> None:
+ world = public_world()
+ await signed_in(world) # A personal agent's sign-in is none of them.
+ client_id = await registered(world)
+ start = world.clock.now()
+ registered_tokens = await sign_in(world, client_id, "http://127.0.0.1:5000/callback")
+ verified_tokens = await sign_in(
+ world, VERIFIED, VERIFIED_REDIRECT, resource=ELSEWHERE, scope="orders:read orders:write"
+ )
+ listed = {entry.client_id: entry for entry in await world.shop.public_client_sign_ins()}
+ assert set(listed) == {client_id, VERIFIED}
+ unverified = listed[client_id]
+ assert (unverified.client_name, unverified.verified) == ("Pocket MCP", False)
+ assert unverified.redirect_host == "127.0.0.1:5000"
+ assert (unverified.resource, unverified.account_id) == (MCP, "acct_ada")
+ assert unverified.scopes == ("orders:read",)
+ assert unverified.signed_in_at == start and unverified.last_used_at == start
+ assert (unverified.expires_at - start).days == 30
+ verified = listed[VERIFIED]
+ assert (verified.client_name, verified.verified) == ("Deskmate", True)
+ assert verified.redirect_host == "client.example" and verified.resource == ELSEWHERE
+ assert verified.scopes == ("orders:read", "orders:write")
+
+ # A refresh is its last use.
+ world.clock.advance(3600)
+ rotated = (await refresh(world, client_id, registered_tokens["refresh_token"])).json()
+ again = {entry.client_id: entry for entry in await world.shop.public_client_sign_ins()}
+ assert (again[client_id].last_used_at - start).total_seconds() == 3600 # type: ignore[operator]
+ assert again[client_id].sign_in_id == unverified.sign_in_id
+ assert again[VERIFIED].last_used_at == start
+
+ assert await world.shop.revoke_public_client_sign_in(unverified.sign_in_id) is True
+ assert await world.shop.revoke_public_client_sign_in(unverified.sign_in_id) is False
+ assert await world.shop.revoke_public_client_sign_in("nothing") is False
+ assert (await mcp(world, rotated["access_token"], LIST_TOOLS)).status_code == 401
+ assert (await refresh(world, client_id, rotated["refresh_token"])).json()[
+ "error"
+ ] == "invalid_grant"
+ # The other one, and the personal agent's, go on.
+ assert [entry.client_id for entry in await world.shop.public_client_sign_ins()] == [VERIFIED]
+ fresh = await refresh(world, VERIFIED, verified_tokens["refresh_token"], resource=ELSEWHERE)
+ assert await world.shop.access_token_for(fresh.json()["access_token"], ELSEWHERE)
+ assert (await world.refreshed()).access_token
+ # A personal agent's sign-in is never ended from this list.
+ families = [
+ AccountFamily.from_json(record.value)
+ for record in await world.shop.store.records(ACCOUNT_FAMILY)
+ ]
+ personal = next(family for family in families if family.public is None)
+ assert await world.shop.revoke_public_client_sign_in(personal.tokens[0]) is False
+ assert (await world.refreshed()).access_token
+
+
+@pytest.mark.asyncio
+async def test_a_policy_may_answer_for_public_clients_apart() -> None:
+ """A company that lists the personal agents it serves takes public clients all the
+ same, or none: `allows_public`, where `allows` answers for personal agents."""
+
+ class Listed:
+ public = True
+
+ async def allows(self, client_id: str) -> bool:
+ return client_id == "https://atlas.example/agent.json"
+
+ async def allows_public(self, client_id: str) -> bool:
+ return self.public
+
+ listed = Listed()
+
+ class Plugin:
+ @hookimpl
+ def provide_contributions(self, contributions: object) -> None:
+ contributions.contribute(CLIENT_POLICIES, listed, contribution_id="p", order=-10) # type: ignore[attr-defined]
+
+ world = public_world()
+ world.shop.reactor.register_plugin(PluginManifest(name="listed", version="1"), Plugin())
+ client_id = await registered(world)
+ tokens = await sign_in(world, client_id)
+ verified = await sign_in(world, VERIFIED, VERIFIED_REDIRECT, resource=ELSEWHERE)
+ assert (await mcp(world, tokens["access_token"], LIST_TOOLS)).status_code == 200
+ assert await world.shop.access_token_for(verified["access_token"], ELSEWHERE) is not None
+ # The listed personal agent is one still; an unlisted one is not let in as one.
+ page = await authorize(
+ world, world.atlas.client_id, "https://atlas.example/oauth/callback", resource=None
+ )
+ summary = await world.shop.authorization_request(request_id_of(page))
+ assert summary["client_class"] == "personal_agent"
+ # Public clients turned away: their tokens stop at once, the personal agent goes on.
+ listed.public = False
+ assert (await mcp(world, tokens["access_token"], LIST_TOOLS)).status_code == 401
+ assert await world.shop.access_token_for(verified["access_token"], ELSEWHERE) is None
+ assert (await refresh(world, client_id, tokens["refresh_token"])).status_code == 401
+ assert (await authorize(world, client_id, LOOPBACK)).status_code == 400
+ assert (await authorize(world, VERIFIED, VERIFIED_REDIRECT)).status_code == 400
+ again = await authorize(
+ world, world.atlas.client_id, "https://atlas.example/oauth/callback", resource=None
+ )
+ assert again.status_code == 200
+
+
+def test_the_return_host_is_shown_with_its_port() -> None:
+ from personal_agent_protocol.models import redirect_host
+
+ assert redirect_host("https://client.example/callback") == "client.example"
+ assert redirect_host("https://client.example:8443/callback?x=1") == "client.example:8443"
+ assert redirect_host("http://127.0.0.1:49152/callback") == "127.0.0.1:49152"
+ assert redirect_host("http://[::1]:49152/callback") == "[::1]:49152"
+ assert redirect_host("http://localhost/callback") == "localhost"
+
+
+# Records and names ----------------------------------------------------------------------------
+
+
+def test_a_personal_agents_records_are_written_as_before() -> None:
+ now = datetime(2026, 11, 18, tzinfo=timezone.utc)
+ records = (
+ IssuedAccessToken("c", "a", ("s",), now, "f"),
+ AccountGrant("a", "c", ("s",), now),
+ AccountFamily("c", "a"),
+ PendingAuthorization("c", "https://c.example/cb", ("s",), "st", "ch", now),
+ IssuedCode("c", "https://c.example/cb", "ch", ("s",), "a", ("s",), now),
+ )
+ for record in records:
+ written = record.to_json()
+ assert "public" not in written and "last_used_at" not in written
+ assert type(record).from_json(written) == record
+
+
+def test_a_name_holds_nothing_that_hides_or_reorders_text() -> None:
+ assert public_client_name(" Pocket MCP ") == "Pocket MCP"
+ for refused in ("", " ", "x" * 101, "ab", "ab", "ab", "a\nb", "a\x7fb", None, 3):
+ with pytest.raises(ValueError):
+ public_client_name(refused)
+
+
+@pytest.mark.asyncio
+async def test_a_company_without_a_public_resolver_verifies_none_by_domain() -> None:
+ """A host's own resolver without `resolve_public`: only registered clients sign in."""
+
+ world = public_world()
+
+ class Plain:
+ async def resolve(self, client_id: str, *, kid: str | None = None) -> Any:
+ raise PersonalAgentProtocolError("invalid_client_metadata", "none here")
+
+ class Plugin:
+ @hookimpl
+ def provide_contributions(self, contributions: object) -> None:
+ contributions.contribute(CLIENT_RESOLVERS, Plain(), contribution_id="plain", order=-10) # type: ignore[attr-defined]
+
+ world.shop.reactor.register_plugin(PluginManifest(name="plain", version="1"), Plugin())
+ assert (await authorize(world, VERIFIED, VERIFIED_REDIRECT)).status_code == 400
+ client_id = await registered(world)
+ assert (await authorize(world, client_id, LOOPBACK)).status_code == 200
diff --git a/personal_agent_protocol/__version__.py b/personal_agent_protocol/__version__.py
index d47d673..66008cf 100644
--- a/personal_agent_protocol/__version__.py
+++ b/personal_agent_protocol/__version__.py
@@ -7,4 +7,4 @@
"""Personal Agent Protocol."""
-__version__ = "0.37.3"
+__version__ = "0.37.5"
diff --git a/personal_agent_protocol/company/__init__.py b/personal_agent_protocol/company/__init__.py
index 625b89c..8c16574 100644
--- a/personal_agent_protocol/company/__init__.py
+++ b/personal_agent_protocol/company/__init__.py
@@ -20,7 +20,7 @@
from reactor import PluginManifest, PluginPlatform, hookimpl # type: ignore[import-untyped]
from ..identity import AgentIdentityClient
-from ..models import ClientMetadata, JsonWebKeySet
+from ..models import ClientMetadata, JsonWebKeySet, PublicClientMetadata
from ..reactor import (
CLOCKS,
AddressResolver,
@@ -66,6 +66,7 @@
OperationOutcomeUnknown,
OperatorDirectory,
ProposedOperation,
+ PublicClientResolver,
RateLimit,
Reply,
SignInContext,
@@ -83,6 +84,7 @@
CompanyService,
ConsentDecision,
OpenWork,
+ PublicClientSignIn,
StaleConversationError,
resource_metadata_url,
)
@@ -105,6 +107,12 @@ async def resolve(
client_id, kid=kid
)
+ async def resolve_public(self, client_id: str) -> PublicClientMetadata:
+ """A public client's client ID metadata document, cached: fetched as a personal
+ agent's is, and refused when it names a key."""
+
+ return await self.identity.fetch_public_metadata(client_id)
+
class IdentityOperatorDirectory:
"""Read an operator's published keys over HTTPS (§5.3, Web Bot Auth §5.5)."""
@@ -183,7 +191,7 @@ def build_company(
reactor.register_plugin(
PluginManifest(
name="personal-agent-protocol.company",
- version="0.37.3",
+ version="0.37.5",
contribution_points=[
COMPANY_STORES.id,
COMPANY_ACCOUNTS.id,
@@ -259,6 +267,8 @@ def build_company(
"OperationOutcomeUnknown",
"OperatorDirectory",
"ProposedOperation",
+ "PublicClientResolver",
+ "PublicClientSignIn",
"RateLimit",
"ReactorClock",
"Reply",
diff --git a/personal_agent_protocol/company/asgi.py b/personal_agent_protocol/company/asgi.py
index 1d6ab66..ebef00f 100644
--- a/personal_agent_protocol/company/asgi.py
+++ b/personal_agent_protocol/company/asgi.py
@@ -90,7 +90,15 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
return
headers = _headers(scope["headers"])
response = await service.handle(
- CompanyRequest(method=scope["method"], url=url, headers=headers, body=body)
+ CompanyRequest(
+ method=scope["method"],
+ url=url,
+ headers=headers,
+ body=body,
+ # The peer's address, as the server saw it: what client registration is
+ # rate-limited by. Behind a proxy it is the proxy's, one count for all.
+ client_address=(scope.get("client") or (None,))[0],
+ )
)
if response.stream is not None:
await send(
diff --git a/personal_agent_protocol/company/points.py b/personal_agent_protocol/company/points.py
index aac9892..c2420a6 100644
--- a/personal_agent_protocol/company/points.py
+++ b/personal_agent_protocol/company/points.py
@@ -46,7 +46,14 @@
from pydantic import SecretStr
from reactor import define_contribution_point # type: ignore[import-untyped]
-from ..models import Approval, ClientMetadata, JsonWebKeySet, Link, Operation
+from ..models import (
+ Approval,
+ ClientMetadata,
+ JsonWebKeySet,
+ Link,
+ Operation,
+ PublicClientMetadata,
+)
from ..reactor import Clock, SystemClock
from .store import (
REPLAY,
@@ -279,6 +286,11 @@ class ClientPolicy(Protocol):
agent or by `client_id`, and a token request for it is `invalid_target`. `resource`
is the service's (the MCP server's `url`, the conversation endpoint), never the
default token's. Without the method, every agent gets a token for every service.
+
+ With `public_clients`, a policy may answer for clients that are no personal agents
+ apart, with `allows_public(client_id)`: a company that lists the personal agents it
+ serves takes public clients all the same, or none. Without the method, `allows`
+ answers for both classes.
"""
async def allows(self, client_id: str) -> bool: ...
@@ -324,6 +336,20 @@ async def resolve(
) -> tuple[ClientMetadata, JsonWebKeySet]: ...
+@runtime_checkable
+class PublicClientResolver(Protocol):
+ """What a `ClientResolver` adds to verify a public client by its domain.
+
+ `resolve_public` reads the client ID metadata document of a client that is no
+ personal agent (an MCP client): one that says `token_endpoint_auth_method` is `none`
+ and names no key. It fetches as `resolve` does, never a private address. A resolver
+ without it verifies no public client: with `public_clients`, only those that
+ registered themselves sign in.
+ """
+
+ async def resolve_public(self, client_id: str) -> PublicClientMetadata: ...
+
+
@runtime_checkable
class OperatorDirectory(Protocol):
"""The keys an operator publishes at a `Signature-Agent` URL (§5.3).
@@ -567,6 +593,7 @@ async def handle(self, call: WebCall) -> WebResult: ...
"PendingDevice",
"PendingMediated",
"ProposedOperation",
+ "PublicClientResolver",
"ReplayCache",
"Reply",
"SignInContext",
diff --git a/personal_agent_protocol/company/service.py b/personal_agent_protocol/company/service.py
index d0b9afd..da81aa8 100644
--- a/personal_agent_protocol/company/service.py
+++ b/personal_agent_protocol/company/service.py
@@ -71,6 +71,7 @@
import hmac
import html
import json
+import logging
import math
import re
import time
@@ -121,6 +122,7 @@
LinksContent,
Message,
Operation,
+ PublicClientMetadata,
_https_url,
compatible_versions,
domain_host,
@@ -128,6 +130,10 @@
operations_content,
parse_version,
protected_resource_metadata_url,
+ public_client_name,
+ public_redirect_uri,
+ public_redirect_uri_matches,
+ redirect_host,
redirect_uri_matches,
split_domain,
)
@@ -200,6 +206,7 @@
OperationOutcomeUnknown,
OperatorDirectory,
ProposedOperation,
+ PublicClientResolver,
RateLimit,
ReplayCache,
Reply,
@@ -227,8 +234,10 @@
MEDIATED,
OPERATION,
PROPOSAL,
+ PUBLIC_CLIENT,
PUSHED_REQUEST,
REFRESH_TOKEN,
+ REGISTRATION_COUNT,
REQUEST_ID,
SESSION,
SIGN_IN_ATTEMPTS,
@@ -252,7 +261,10 @@
PendingAuthorization,
PendingDevice,
PendingMediated,
+ PublicClient,
PushedAuthorization,
+ RegisteredClient,
+ RegistrationCount,
RequestReceipt,
SignInAttempts,
StoredConversation,
@@ -272,6 +284,8 @@
verify_session_jwt,
)
+logger = logging.getLogger(__name__)
+
_PAGE = 50
#: How often a compare-and-set is retried against concurrent writers before giving up.
_CAS_ATTEMPTS = 32
@@ -290,6 +304,46 @@
MAX_WAIT_SECONDS = 30
+#: The `client_id` a public client gets when it registers itself (RFC 7591): never a URL,
+#: so it is never taken for a client ID metadata document, or a personal agent.
+_REGISTERED_CLIENT_ID = re.compile(r"mcpc_[A-Za-z0-9_-]{22}")
+#: A PKCE S256 challenge: the 43 characters a SHA-256 digest encodes to (RFC 7636 §4.2).
+_CODE_CHALLENGE = re.compile(r"[A-Za-z0-9_-]{43}")
+#: A PKCE verifier (RFC 7636 §4.1).
+_CODE_VERIFIER = re.compile(r"[A-Za-z0-9._~-]{43,128}")
+#: The largest registration request read (RFC 7591), and the most redirect URIs it names.
+_REGISTRATION_MAX_BYTES = 16 * 1024
+_REGISTRATION_MAX_REDIRECTS = 10
+#: The window `client_registrations_per_hour` counts in.
+_REGISTRATION_WINDOW = timedelta(hours=1)
+#: How long a registration is kept before its client first signs in: long enough to
+#: register and then ask the person, short enough that clients nobody used don't pile up.
+_REGISTRATION_UNUSED = timedelta(hours=1)
+#: The methods a registration may ask for: each is registered as a public client, and
+#: the response says so (RFC 7591 §3.2.1: the server may replace what was requested, and
+#: the client uses what is returned). Left out, the same.
+_REGISTERED_AS_PUBLIC = frozenset({"none", "client_secret_post", "client_secret_basic"})
+#: What a registration that can't be a public client's is told: exactly what to send.
+_REGISTER_AS_PUBLIC = (
+ "Every client registered here is a public client: it gets no secret, whatever "
+ 'method it asked for, and the response says "token_endpoint_auth_method": "none". '
+ 'Leave the method out or send "none", with no "client_secret", "jwks" or '
+ '"jwks_uri"; sign in with the authorization code grant and PKCE (S256).'
+)
+#: What a request that carries a client secret is told: no client here has one.
+_PUBLIC_CLIENT_SENDS_NONE = (
+ "This client has no secret: it was registered as a public client "
+ '("token_endpoint_auth_method": "none"). Send its client_id and no client_secret, '
+ "with PKCE."
+)
+#: What a public client asking for an action that needs approval is told: operations are
+#: approved by a personal agent in its Session, and a public client has neither.
+_PUBLIC_NEEDS_APPROVAL = (
+ "Not done. This needs the person's approval, which only a personal agent can ask for: "
+ "this client can't do it."
+)
+
+
class _Record(Protocol):
def to_json(self) -> JsonObject: ...
@@ -615,6 +669,32 @@ class CompanyConfig:
operator_signatures: Literal["off", "optional", "required"] = "off"
#: How far in the future an operator signature's `created` may be.
operator_signature_window: timedelta = timedelta(seconds=60)
+ #: Whether clients that are no personal agents sign in: public clients, such as MCP
+ #: clients, which authenticate with nothing but PKCE (S256), by Direct Sign-In's
+ #: authorization endpoint. A client ID metadata document that names no key and says
+ #: `token_endpoint_auth_method` is `none` is one, verified by its domain. Their tokens
+ #: are for one service (`resource_servers`, the MCP server), never the default token:
+ #: they have no Session, and every endpoint of the protocol refuses them. Off by
+ #: default; needs an issuer and `direct`.
+ public_clients: bool = False
+ #: Whether a public client may register itself (RFC 7591) at `/oauth/register`, for
+ #: one that has no client ID metadata document: what it says of itself is never
+ #: verified, its redirect URIs are loopback or HTTPS, and its consent page says so.
+ #: Off by default; needs `public_clients`.
+ client_registration: bool = False
+ #: How long a public client's sign-in lasts: its refresh tokens are rotated at every
+ #: use, one used twice ends the sign-in whole whatever `refresh_reuse_revokes` says,
+ #: and after this long the person signs in again.
+ public_client_refresh_lifetime: timedelta = timedelta(days=30)
+ #: The scopes a public client may be granted, some of `scopes`; None, all of them.
+ #: Never `poppy:browser-sign-in`, which is a personal agent's.
+ public_client_scopes: tuple[str, ...] | None = None
+ #: How long a self-registered client is kept after it last signed in. One that never
+ #: signed in is forgotten an hour after it registered.
+ client_registration_lifetime: timedelta = timedelta(days=90)
+ #: How many clients one address registers in an hour, whatever the host's own
+ #: `pap.company.rateLimit` allows besides (RFC 7591 §5).
+ client_registrations_per_hour: int = 10
def __post_init__(self) -> None: # noqa: C901 - one branch per protocol rule
_check_aliases(self.domain, self.aliases)
@@ -645,7 +725,23 @@ def __post_init__(self) -> None: # noqa: C901 - one branch per protocol rule
dpop_proof_window=self.dpop_proof_window,
operator_signature_window=self.operator_signature_window,
pushed_request_lifetime=self.pushed_request_lifetime,
+ public_client_refresh_lifetime=self.public_client_refresh_lifetime,
+ client_registration_lifetime=self.client_registration_lifetime,
)
+ if self.public_clients and not (self.oauth and self.direct):
+ raise ValueError("public_clients sign in at the authorization endpoint: direct is on")
+ if self.public_clients and self.pushed_authorization_requests == "required":
+ # A pushed request carries a client assertion, which a public client has not.
+ raise ValueError("public_clients can't push requests: they are not required")
+ if self.client_registration and not self.public_clients:
+ raise ValueError("client_registration registers public clients: public_clients is on")
+ if self.public_client_scopes is not None and (
+ not self.public_client_scopes
+ or any(scope not in self.scopes for scope in self.public_client_scopes)
+ ):
+ raise ValueError("public_client_scopes are some of scopes")
+ if self.client_registrations_per_hour < 1:
+ raise ValueError("client_registrations_per_hour is at least 1")
if self.pushed_authorization_requests not in ("off", "offered", "required"):
raise ValueError("pushed_authorization_requests is off, offered or required")
if self.pushed_authorization_requests != "off" and not self.direct:
@@ -782,6 +878,17 @@ def api_description(self) -> str:
def revocation_endpoint(self) -> str:
return f"{self.base}/oauth/revoke"
+ @property
+ def registration_endpoint(self) -> str:
+ return f"{self.base}/oauth/register"
+
+ @property
+ def public_scopes(self) -> tuple[str, ...]:
+ """The scopes a public client may be granted: `public_client_scopes`, or every one
+ of the company's own. Never the protocol's `poppy:browser-sign-in`."""
+
+ return self.scopes if self.public_client_scopes is None else self.public_client_scopes
+
@property
def mediated_grant_scopes(self) -> tuple[str, ...]:
"""The extension's `scopes`: what Mediated Sign-In can grant."""
@@ -898,6 +1005,10 @@ class CompanyRequest:
url: str
headers: Mapping[str, str]
body: bytes = b""
+ #: The address the request came from, when the host knows it: what client
+ #: registration is rate-limited by. A host behind a proxy names the address its
+ #: proxy vouches for, never a header anyone can set.
+ client_address: str | None = None
@dataclass(frozen=True)
@@ -962,6 +1073,40 @@ def empty(self) -> bool:
return not self.operations and not self.sign_ins
+@dataclass(frozen=True)
+class PublicClientSignIn:
+ """One sign-in of a public client that has not ended, for the company's owner to list
+ and revoke (`CompanyService.public_client_sign_ins`, `revoke_public_client_sign_in`).
+
+ `sign_in_id` names it. `verified` says the client's `client_id` is a client ID
+ metadata document read from its own domain; otherwise it registered itself, and
+ `client_name` is only what it said. `last_used_at` is when it last got tokens.
+ """
+
+ sign_in_id: str
+ client_id: str
+ client_name: str
+ verified: bool
+ redirect_host: str
+ resource: str
+ account_id: str
+ scopes: tuple[str, ...]
+ signed_in_at: datetime | None
+ last_used_at: datetime | None
+ expires_at: datetime
+
+
+@dataclass(frozen=True)
+class _Client:
+ """Who asks at the authorization endpoint: a personal agent, or a public client that
+ is verified by its domain or registered itself."""
+
+ name: str
+ redirect_uris: tuple[str, ...]
+ public: bool = False
+ verified: bool = True
+
+
#: How long a request for an operation being performed waits before trying again.
_PERFORMING_RETRY_AFTER = "5"
@@ -1213,6 +1358,7 @@ def _with(items: tuple[str, ...], item: str | None) -> tuple[str, ...]:
"oauth_authorize",
"oauth_device",
"oauth_revoke",
+ "oauth_register",
"poppy_browser_session",
"poppy_conversations",
"poppy_feedback",
@@ -1489,6 +1635,8 @@ async def _dispatch(self, request: CompanyRequest) -> CompanyResponse: # noqa:
return await self._device(request)
if method == "POST" and path == "/oauth/revoke":
return await self._revoke(request)
+ if method == "POST" and path == "/oauth/register" and self.config.client_registration:
+ return await self._register(request)
if path == "/poppy/conversations" and method == "POST":
return await self._start_conversation(request)
if path.startswith("/poppy/conversations/"):
@@ -1829,7 +1977,7 @@ def protected_resource_metadata(self) -> dict[str, Any]:
metadata["dpop_signing_alg_values_supported"] = [DPOP_ALGORITHM]
return metadata
- def oauth_metadata(self) -> dict[str, Any]:
+ def oauth_metadata(self) -> dict[str, Any]: # noqa: C901 - one branch per member
config = self.config
grants = [REFRESH_TOKEN_GRANT]
metadata: dict[str, Any] = {
@@ -1873,6 +2021,13 @@ def oauth_metadata(self) -> dict[str, Any]:
# The issuer reads client ID metadata documents (§4.1): said for other clients,
# such as MCP clients, as the CIMD draft's §8 defines (guides).
metadata["client_id_metadata_document_supported"] = True
+ if config.public_clients:
+ # Public clients authenticate with nothing but PKCE; every answer of the
+ # authorization endpoint names the issuer (RFC 9207), said for them.
+ metadata["token_endpoint_auth_methods_supported"].append("none")
+ metadata["authorization_response_iss_parameter_supported"] = True
+ if config.client_registration:
+ metadata["registration_endpoint"] = config.registration_endpoint
return metadata
# OAuth -------------------------------------------------------------------------
@@ -1982,6 +2137,8 @@ async def _token(self, request: CompanyRequest) -> CompanyResponse:
form = dict(parse_qsl(request.body.decode()))
grant = form.get("grant_type")
+ if self._unauthenticated(form):
+ return await self._public_token(request, form)
if grant == REFRESH_TOKEN_GRANT and await self._never_issued():
# No tokens to protect: every refresh is `invalid_grant`, the client assertion
# unverified (§3.2).
@@ -1994,7 +2151,7 @@ async def _token(self, request: CompanyRequest) -> CompanyResponse:
# Before any grant is used: a proof refused spends no code.
jkt = await self._token_binding(request, resource)
if grant == REFRESH_TOKEN_GRANT:
- return await self._refresh_grant(form, client_id, jkt)
+ return await self._refresh_grant(form, client_id, jkt, resource)
if grant == AUTHORIZATION_CODE_GRANT and self.config.direct:
return await self._code_grant(form, client_id, jkt)
if grant == DEVICE_CODE_GRANT and self.config.device:
@@ -2005,6 +2162,254 @@ async def _token(self, request: CompanyRequest) -> CompanyResponse:
return await self._mediated_grant(form, client_id, jkt)
raise _RefusedError(400, "unsupported_grant_type")
+ def _unauthenticated(self, form: Mapping[str, str]) -> bool:
+ """Whether a token or revocation request is a public client's: the company takes
+ them, and the request carries no client assertion at all. One that carries any
+ is a personal agent's, and is verified as one."""
+
+ return (
+ self.config.public_clients
+ and "client_assertion" not in form
+ and "client_assertion_type" not in form
+ )
+
+ async def _public_token(
+ self, request: CompanyRequest, form: Mapping[str, str]
+ ) -> CompanyResponse:
+ """The token endpoint for a public client: the code and refresh grants, for the
+ one service its sign-in names, never bound, never the default token.
+
+ In order: the host's rate limit, the client (the policy, then that it is a
+ public client still: its registration, or its document read again), the grant
+ type, the `resource`, and only then the grant itself. A request refused by one
+ of those spends nothing. Once the code is taken it is spent, whatever is wrong
+ with the rest of the request: a code is used once (RFC 6749 §4.1.2).
+ """
+
+ await self._public_admitted(request)
+ self._no_client_secret(request, form)
+ client_id = form.get("client_id", "")
+ client = await self._public_client(client_id)
+ grant = form.get("grant_type")
+ if grant in {DEVICE_CODE_GRANT, MEDIATED_GRANT}:
+ # A personal agent's sign-ins: never a public client's.
+ raise _RefusedError(400, "unauthorized_client")
+ if grant not in {AUTHORIZATION_CODE_GRANT, REFRESH_TOKEN_GRANT}:
+ raise _RefusedError(400, "unsupported_grant_type")
+ resource = form.get("resource")
+ if (
+ resource is None
+ or resource not in self._public_resources()
+ or not await self._resource_allowed(client_id, resource)
+ ):
+ # Named in every request, and one of the services a public client gets tokens
+ # for: never the default token, which is the protocol's.
+ raise _RefusedError(400, "invalid_target")
+ if grant == REFRESH_TOKEN_GRANT:
+ return await self._refresh_grant(form, client_id, None, resource, public=True)
+ return await self._public_code_grant(form, client_id, client, resource)
+
+ async def _public_admitted(self, request: CompanyRequest) -> None:
+ """The host's rate limit on requests that carry no client assertion, or HTTP 429.
+
+ Asked with `public:{address}` where it is asked a `client_id`, before the
+ client is looked at: such a request names any `client_id` it likes, and each
+ may make the company read a document from the network. Counted by address, so
+ the names a caller invents cost the limiter nothing. None contributed: no limit.
+ """
+
+ limit = optional_contribution(self.reactor, COMPANY_RATE_LIMITS, "rate limit")
+ if limit is None:
+ return
+ wait = await cast(RateLimit, limit).admit(
+ f"public:{request.client_address or 'unknown'}", None
+ )
+ if wait is not None:
+ raise _RateLimitedError(max(1, int(wait)))
+
+ @staticmethod
+ def _no_client_secret(request: CompanyRequest, form: Mapping[str, str]) -> None:
+ """Refuse a request without an assertion that carries a client secret, in its form
+ (`client_secret_post`) or as HTTP Basic (`client_secret_basic`).
+
+ No client here has a secret, and none is ever checked: a request that sends one
+ is refused, never served as if the secret had been right. A client that
+ registered asking for a secret was told `none`, and uses what it was told.
+ HTTP Basic is refused whatever its password, an empty one too: some libraries
+ send a public client's `client_id` that way, and it goes in the form here.
+
+ The 401 carries no `WWW-Authenticate` (RFC 6749 §5.2 asks for one naming the
+ scheme the client used): naming `Basic` would say Basic works, which it never does.
+ """
+
+ scheme = request.headers.get("authorization", "").partition(" ")[0].lower()
+ if "client_secret" in form or scheme == "basic":
+ raise _RefusedError(401, "invalid_client", error_description=_PUBLIC_CLIENT_SENDS_NONE)
+
+ def _public_resources(self) -> tuple[str, ...]:
+ """The services a public client gets tokens for: `resource_servers`, and the MCP
+ server when the company has one. Never the default token's, nor the conversation
+ endpoint."""
+
+ own = (self.config.mcp_url,) if self._mcp() is not None else ()
+ return (*own, *self.config.resource_servers)
+
+ def _public_token_within(self, issued: IssuedAccessToken | AccountGrant) -> bool:
+ """Whether a public client's token or sign-in is within what the company gives
+ public clients now: it still takes them, for that service, with those scopes."""
+
+ resource = issued.resource if isinstance(issued, IssuedAccessToken) else None
+ if isinstance(issued, AccountGrant) and issued.public is not None:
+ resource = issued.public.resource
+ return (
+ self.config.public_clients
+ and resource in self._public_resources()
+ and all(scope in self.config.public_scopes for scope in issued.scopes)
+ )
+
+ async def _public_client(self, client_id: str) -> _Client:
+ """The public client a token or revocation request names, or `invalid_client`.
+
+ The company's policy is asked first, so a blocked `client_id` is never fetched;
+ then a registered client is read from its record and a URL from its document,
+ again at each request: a client whose registration is gone, or whose document
+ became a personal agent's, gets nothing more.
+ """
+
+ if not client_id or not await self._public_allowed(client_id):
+ raise _RefusedError(401, "invalid_client")
+ client = (
+ await self._verified_public_client(client_id)
+ if client_id.startswith("https://")
+ else await self._registered_client(client_id)
+ )
+ if client is None:
+ raise _RefusedError(401, "invalid_client")
+ exchange = _EXCHANGE.get()
+ if exchange is not None:
+ exchange.client_id = client_id
+ return client
+
+ async def _verified_public_client(self, client_id: str) -> _Client | None:
+ """A public client verified by its domain: its client ID metadata document, read by
+ the resolver; `None` when there is none, or it is not a public client's."""
+
+ resolver = first_contribution(self.reactor, CLIENT_RESOLVERS, "client resolver")
+ if not self.config.public_clients or not isinstance(resolver, PublicClientResolver):
+ return None
+ try:
+ metadata = await resolver.resolve_public(client_id)
+ except (PersonalAgentProtocolError, ValueError, TypeError, RecursionError):
+ # Not a document a public client's metadata can be read from.
+ return None
+ if not isinstance(metadata, PublicClientMetadata) or metadata.client_id != client_id:
+ return None
+ return _Client(
+ name=metadata.client_name,
+ redirect_uris=metadata.usable_redirect_uris,
+ public=True,
+ verified=True,
+ )
+
+ async def _registered_client(self, client_id: str) -> _Client | None:
+ """A public client that registered itself, by the `client_id` it was given."""
+
+ if not self.config.client_registration or not _REGISTERED_CLIENT_ID.fullmatch(client_id):
+ return None
+ record = await self._read(PUBLIC_CLIENT, client_id, RegisteredClient.from_json)
+ if record is None:
+ return None
+ return _Client(
+ name=record.client_name,
+ redirect_uris=record.redirect_uris,
+ public=True,
+ verified=False,
+ )
+
+ async def _public_allowed(self, client_id: str) -> bool:
+ """The company's policy on this public client, asked before anything is fetched
+ or read for it: `allows_public`, when the policy has it, so a company that lists
+ the personal agents it serves can still take public clients, or none; `allows`
+ otherwise, one answer for both classes."""
+
+ policy = first_contribution(self.reactor, CLIENT_POLICIES, "policy")
+ decide = getattr(policy, "allows_public", None)
+ if decide is None:
+ return await self._allowed(client_id)
+ return bool(await decide(client_id))
+
+ async def _public_sign_in_allowed(self, client_id: str) -> bool:
+ """Whether the client policy lets this public client sign in (`allows_sign_in`).
+ `sign_in_disabled` is about personal agents, and is not asked here."""
+
+ policy = first_contribution(self.reactor, CLIENT_POLICIES, "policy")
+ decide = getattr(policy, "allows_sign_in", None)
+ return True if decide is None else bool(await decide(client_id, AUTHORIZATION_CODE_GRANT))
+
+ async def _public_code_grant(
+ self, form: Mapping[str, str], client_id: str, client: _Client, resource: str
+ ) -> CompanyResponse:
+ """A public client's code for its tokens: PKCE is its only proof, so the verifier
+ is checked as RFC 7636 writes it, and the code is the one issued to this client,
+ for this redirect and this service.
+
+ The code is taken first, and so spent, whatever the request then gets wrong:
+ another client, redirect, service or verifier gets `invalid_grant` or
+ `invalid_target`, and the code gives nothing to anyone after it.
+ """
+
+ taken = await self.store.take(CODE, _digest(form.get("code", "")))
+ issued = None if taken is None else IssuedCode.from_json(taken)
+ if (
+ issued is None
+ or self._now() >= issued.expires_at
+ or issued.public is None
+ or issued.client_id != client_id
+ or issued.redirect_uri != form.get("redirect_uri")
+ ):
+ # Expired, reused, a personal agent's, another client's, or another redirect.
+ raise _RefusedError(400, "invalid_grant")
+ if issued.public.resource != resource:
+ raise _RefusedError(400, "invalid_target")
+ verifier = form.get("code_verifier", "")
+ if not _CODE_VERIFIER.fullmatch(verifier):
+ raise _RefusedError(400, "invalid_grant")
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(
+ b"="
+ )
+ if not hmac.compare_digest(challenge.decode(), issued.code_challenge):
+ raise _RefusedError(400, "invalid_grant")
+ if not self._offers(issued.scopes) or any(
+ scope not in self.config.public_scopes for scope in issued.scopes
+ ):
+ raise _RefusedError(400, "invalid_scope")
+ if not await self._public_sign_in_allowed(client_id):
+ raise _RefusedError(400, "unauthorized_client")
+ if not client.verified:
+ await self._keep_registration(client_id)
+ return await self._sign_in(
+ client_id,
+ issued.account_id,
+ issued.scopes,
+ requested=issued.requested,
+ jkt=None,
+ resource=resource,
+ public=issued.public,
+ )
+
+ async def _keep_registration(self, client_id: str) -> None:
+ """A registered client that signs in is kept `client_registration_lifetime` more."""
+
+ entry = await self.store.get(PUBLIC_CLIENT, client_id)
+ if entry is not None:
+ await self.store.replace(
+ PUBLIC_CLIENT,
+ client_id,
+ entry.version,
+ entry.value,
+ expires_at=self._now() + self.config.client_registration_lifetime,
+ )
+
async def _token_binding(self, request: CompanyRequest, resource: str | None) -> str | None:
"""The thumbprint the tokens of this request are bound to, or `None` for Bearer.
@@ -2111,21 +2516,33 @@ def _account_scopes(self) -> tuple[str, ...]:
read = tuple(scope for scope in self.config.scopes if scope not in self.config.write_scopes)
return read or self.config.scopes
- async def _refresh_grant(
- self, form: Mapping[str, str], client_id: str, jkt: str | None
+ async def _refresh_grant( # noqa: C901 - the checks of §4.4, in order
+ self,
+ form: Mapping[str, str],
+ client_id: str,
+ jkt: str | None,
+ resource: str | None,
+ *,
+ public: bool = False,
) -> CompanyResponse:
"""An access token from a refresh token, which is rotated (§4.4).
Narrower scopes only; `resource` for one service. Exactly one refresh claims
- the presented token, which stops working the moment it is claimed.
+ the presented token, which stops working the moment it is claimed. `public`
+ says the request is a public client's: it refreshes only a public client's
+ sign-in, for the service that sign-in names, and a token used twice ends the
+ sign-in whole, whatever `refresh_reuse_revokes` says for personal agents.
"""
- resource = self._resource(form)
presented = _digest(form.get("refresh_token", ""))
entry = await self.store.get(REFRESH_TOKEN, presented)
grant = None if entry is None else AccountGrant.from_json(entry.value)
now = self._now()
- if grant is not None and grant.revoked and self.config.refresh_reuse_revokes:
+ if grant is not None and (grant.public is not None) != public:
+ # A sign-in is refreshed by the class of client it is of: a personal agent's
+ # never without its assertion, a public client's never as a personal agent.
+ raise _RefusedError(400, "invalid_grant")
+ if grant is not None and grant.revoked and (public or self.config.refresh_reuse_revokes):
# A rotated-away token used again: whoever holds the other copy loses it too.
await self._sign_out((grant.family,))
if (
@@ -2138,6 +2555,12 @@ async def _refresh_grant(
raise _RefusedError(400, "invalid_grant")
if await self._sign_in_ended(grant):
raise _RefusedError(400, "invalid_grant")
+ if grant.public is not None:
+ if grant.public.resource != resource:
+ # A public client's sign-in is for one service, for as long as it lasts.
+ raise _RefusedError(400, "invalid_target")
+ if not self._public_token_within(grant):
+ raise _RefusedError(400, "invalid_scope")
if grant.dpop_jkt is not None and (
jkt is None or not hmac.compare_digest(jkt, grant.dpop_jkt)
):
@@ -2166,7 +2589,9 @@ async def _refresh_grant(
replace(grant, revoked=False).to_json(),
expires_at=grant.expires_at,
)
- if not await self._join_family(grant.family, refresh_token=_digest(rotated)):
+ if not await self._join_family(
+ grant.family, refresh_token=_digest(rotated), used_at=now if public else None
+ ):
# The sign-in was revoked meanwhile: its new token is too.
await self._revoke_grants((_digest(rotated),))
raise _RefusedError(400, "invalid_grant")
@@ -2180,6 +2605,7 @@ async def _refresh_grant(
# A refresh naming no scope gets them in the response: the agent can't know.
requested=requested,
jkt=jkt,
+ public=public,
)
family = await self._read(ACCOUNT_FAMILY, grant.family, AccountFamily.from_json)
if family is None or family.revoked:
@@ -2412,13 +2838,26 @@ async def _never_issued(self) -> bool:
async def _revoke(self, request: CompanyRequest) -> CompanyResponse:
form = dict(parse_qsl(request.body.decode()))
- if await self._never_issued():
- return CompanyResponse(200, {}, {"Cache-Control": "no-store"})
- client_id = await self._client(form)
+ if self._unauthenticated(form):
+ # A public client revokes its own sign-in with the refresh token it holds.
+ await self._public_admitted(request)
+ self._no_client_secret(request, form)
+ client_id = form.get("client_id", "")
+ await self._public_client(client_id)
+ public = True
+ else:
+ if await self._never_issued():
+ return CompanyResponse(200, {}, {"Cache-Control": "no-store"})
+ client_id = await self._client(form)
+ public = False
grant = await self._read(
REFRESH_TOKEN, _digest(form.get("token", "")), AccountGrant.from_json
)
- if grant is not None and grant.client_id == client_id:
+ if (
+ grant is not None
+ and grant.client_id == client_id
+ and (grant.public is not None) == public
+ ):
# The token and every one rotated from the same sign-in, and the access tokens
# they gave (RFC 7009 §2.1): the Sessions continue signed out (§5.5).
await self._sign_out((grant.family,))
@@ -2467,8 +2906,10 @@ async def _join_family(
*,
refresh_token: str | None = None,
access_token: str | None = None,
+ used_at: datetime | None = None,
) -> bool:
- """Add a refresh or an access token to a sign-in; `False` once it is revoked."""
+ """Add a refresh or an access token to a sign-in; `False` once it is revoked.
+ `used_at` notes when a public client's sign-in last got tokens."""
changed = await self._change(
ACCOUNT_FAMILY,
@@ -2481,6 +2922,7 @@ async def _join_family(
family,
tokens=_with(family.tokens, refresh_token),
access_tokens=_with(family.access_tokens, access_token),
+ last_used_at=family.last_used_at if used_at is None else used_at,
)
),
)
@@ -2527,6 +2969,7 @@ async def _sign_in(
requested: tuple[str, ...],
jkt: str | None,
resource: str | None,
+ public: PublicClient | None = None,
) -> CompanyResponse:
"""A sign-in: a new refresh token, and an access token (§4.7).
@@ -2541,7 +2984,11 @@ async def _sign_in(
raise _RefusedError(400, "access_denied")
refresh_token = self._id("rt")
family = _digest(refresh_token)
- expires_at = self._now() + self.config.refresh_token_lifetime
+ expires_at = self._now() + (
+ self.config.refresh_token_lifetime
+ if public is None
+ else self.config.public_client_refresh_lifetime
+ )
await self.store.put(
REFRESH_TOKEN,
family,
@@ -2553,13 +3000,20 @@ async def _sign_in(
family=family,
signed_in_at=self._now(),
dpop_jkt=jkt if self.config.bind_refresh_tokens else None,
+ public=public,
).to_json(),
expires_at=expires_at,
)
await self.store.put(
ACCOUNT_FAMILY,
family,
- AccountFamily(client_id=client_id, account_id=account_id, tokens=(family,)).to_json(),
+ AccountFamily(
+ client_id=client_id,
+ account_id=account_id,
+ tokens=(family,),
+ public=public,
+ last_used_at=None if public is None else self._now(),
+ ).to_json(),
expires_at=expires_at,
)
await self._remember_family(client_id, account_id, family)
@@ -2572,6 +3026,7 @@ async def _sign_in(
refresh_token=refresh_token,
requested=requested,
jkt=jkt,
+ public=public is not None,
)
async def _remember_family(self, client_id: str, account_id: str, family: str) -> None:
@@ -2600,6 +3055,7 @@ async def _issue(
refresh_token: str | None,
requested: tuple[str, ...],
jkt: str | None,
+ public: bool = False,
) -> CompanyResponse:
"""A token response (§4.7): an access token, and the refresh token if any.
@@ -2608,6 +3064,10 @@ async def _issue(
follows RFC 6749: left out when it grants exactly the scopes requested.
"""
+ if public and (resource is None or jkt is not None):
+ # Never the default token, never bound: a public client has no Session to
+ # use the first in, and no key the company knows for the second.
+ raise _RefusedError(400, "invalid_target")
if resource is not None and not self._takes_dpop(resource):
# A server that takes only Bearer gets a Bearer token, even after a proof that a
# bound refresh token needed (§4.4, §4.5).
@@ -2615,6 +3075,13 @@ async def _issue(
access_token = self._id("at")
digest = _digest(access_token)
expires_at = self._now() + self.config.access_token_lifetime
+ if public:
+ # Never past its sign-in: once that has ended its owner can no longer list
+ # or revoke it, so no token of it works any more.
+ signed_in = await self._read(REFRESH_TOKEN, family, AccountGrant.from_json)
+ if signed_in is None or self._now() >= signed_in.expires_at:
+ raise _RefusedError(400, "invalid_grant")
+ expires_at = min(expires_at, signed_in.expires_at)
await self.store.put(
ACCESS_TOKEN,
digest,
@@ -2626,6 +3093,7 @@ async def _issue(
family=family,
resource=resource,
dpop_jkt=jkt,
+ public=public,
).to_json(),
expires_at=expires_at,
)
@@ -2635,7 +3103,7 @@ async def _issue(
body: dict[str, object] = {
"access_token": access_token,
"token_type": "Bearer" if jkt is None else "DPoP",
- "expires_in": int(self.config.access_token_lifetime.total_seconds()),
+ "expires_in": max(1, int((expires_at - self._now()).total_seconds())),
}
if set(scopes) != set(requested):
body["scope"] = " ".join(scopes)
@@ -2662,6 +3130,12 @@ async def _access_token(self, token: str) -> IssuedAccessToken | None:
if issued is None or self._now() >= issued.expires_at:
return None
grant = await self._read(REFRESH_TOKEN, issued.family, AccountGrant.from_json)
+ if issued.public:
+ # A public client's token is held to its sign-in, which its owner lists and
+ # revokes: one whose sign-in is gone, over or ended works no more.
+ family = await self._read(ACCOUNT_FAMILY, issued.family, AccountFamily.from_json)
+ if grant is None or self._now() >= grant.expires_at or family is None or family.revoked:
+ return None
if grant is None:
# Its sign-in's records are gone (expired, deleted): nothing to hold it to.
if await self._signed_out_before(issued.account_id) is not None:
@@ -2680,7 +3154,9 @@ async def access_token_for(self, token: str, resource: str) -> IssuedAccessToken
default token among them, is `None`: the service answers `invalid_token` with
its `resource_metadata` (`resource_metadata_url`). The record says whose it is
(`account_id`), which agent holds it (`client_id`) and its `scopes`, which the
- service enforces.
+ service enforces. With `public_clients`, the record's `public` says the token is
+ a public client's (an MCP client's), never a personal agent's: the service gives
+ it no Session and takes no operation approval from it.
"""
if resource not in self.config.resource_servers:
@@ -2688,12 +3164,19 @@ async def access_token_for(self, token: str, resource: str) -> IssuedAccessToken
issued = await self._access_token(token)
if issued is None or issued.resource != resource or not self._offers(issued.scopes):
return None
+ if issued.public and not self._public_token_within(issued):
+ # A public client's (`public` on the record): only while the company takes
+ # public clients, for a service and scopes it gives them.
+ return None
# The client policy, asked now and not only when the token was issued: a blocked
# agent's tokens stop working at once, and so does one for a service the policy
# has since left out for this agent (§4.5).
- if not await self._allowed(issued.client_id) or not await self._resource_allowed(
- issued.client_id, resource
- ):
+ allowed = (
+ await self._public_allowed(issued.client_id)
+ if issued.public
+ else await self._allowed(issued.client_id)
+ )
+ if not allowed or not await self._resource_allowed(issued.client_id, resource):
return None
return issued
@@ -2716,6 +3199,212 @@ async def _sign_in_ended(self, grant: AccountGrant) -> bool:
await self._sign_out((grant.family,))
return True
+ # Public clients: registration, and the owner's list -------------------------------
+
+ async def _register(self, request: CompanyRequest) -> CompanyResponse:
+ """`POST /oauth/register` (RFC 7591): a public client registers itself.
+
+ Rate-limited by address before anything is read. Every client registered is a
+ public client, whatever it asked for: `token_endpoint_auth_method` left out,
+ `none`, `client_secret_post` or `client_secret_basic` is answered `none`, with
+ no secret (RFC 7591 §3.2.1). One that names a key or a secret of its own, or
+ another method, is refused. Its redirect URIs are loopback or HTTPS
+ (`models.public_redirect_uri`). It gets a `client_id`; what it said of itself
+ is kept, never verified, and shown as such.
+ """
+
+ await self._registration_admitted(request.client_address)
+ try:
+ return await self._registered(request)
+ except _RefusedError:
+ raise
+ except Exception:
+ # Whatever a body nobody signed made go wrong (nesting too deep to read,
+ # a member of a type no check foresaw) is the caller's mistake to them,
+ # never a 500; and a bug of ours to us, so it is logged whole.
+ logger.exception("A client registration was refused for a reason no check names")
+ raise _RefusedError(
+ 400,
+ "invalid_client_metadata",
+ error_description="the registration could not be read",
+ ) from None
+
+ async def _registered( # noqa: C901 - one check per member of the registration
+ self, request: CompanyRequest
+ ) -> CompanyResponse:
+ """The registration itself, once the address was admitted (`_register`)."""
+
+ def invalid(description: str, error: str = "invalid_client_metadata") -> _RefusedError:
+ return _RefusedError(400, error, error_description=description)
+
+ if len(request.body) > _REGISTRATION_MAX_BYTES:
+ raise invalid("the registration is too large")
+ try:
+ body = loads_strict(request.body)
+ except (ValueError, PersonalAgentProtocolError) as exc:
+ raise invalid("the registration is a JSON object") from exc
+ if not isinstance(body, dict):
+ raise invalid("the registration is a JSON object")
+ # A key or a secret of its own is no public client's: a personal agent can't pass
+ # itself off as one. Any method that only says how a secret would be sent is
+ # registered as public all the same, and told so; any other is refused.
+ method = body.get("token_endpoint_auth_method", "none")
+ if (
+ any(member in body for member in ("jwks", "jwks_uri", "client_secret"))
+ or not isinstance(method, str)
+ or method not in _REGISTERED_AS_PUBLIC
+ ):
+ raise invalid(_REGISTER_AS_PUBLIC)
+ grants = body.get("grant_types", [AUTHORIZATION_CODE_GRANT])
+ if (
+ not isinstance(grants, list)
+ # Each a string, before any is looked up: what is not one is no grant.
+ or not all(isinstance(grant, str) for grant in grants)
+ or AUTHORIZATION_CODE_GRANT not in grants
+ or any(grant not in {AUTHORIZATION_CODE_GRANT, REFRESH_TOKEN_GRANT} for grant in grants)
+ ):
+ raise invalid("grant_types are authorization_code and refresh_token")
+ if "scope" in body and not isinstance(body["scope"], str):
+ raise invalid("scope is text")
+ if body.get("response_types", ["code"]) != ["code"]:
+ raise invalid("response_types is code")
+ redirects = body.get("redirect_uris")
+ if (
+ not isinstance(redirects, list)
+ or not 0 < len(redirects) <= _REGISTRATION_MAX_REDIRECTS
+ or not all(isinstance(uri, str) for uri in redirects)
+ or len(set(redirects)) != len(redirects)
+ ):
+ raise invalid("redirect_uris names 1 to 10 redirect URIs", "invalid_redirect_uri")
+ try:
+ for uri in redirects:
+ public_redirect_uri(uri)
+ name = public_client_name(body.get("client_name", "MCP client"))
+ except ValueError as exc:
+ named = "client_name" in str(exc)
+ error = "invalid_client_metadata" if named else "invalid_redirect_uri"
+ raise invalid(str(exc), error) from exc
+ now = self._now()
+ client_id = self._id("mcpc")
+ record = RegisteredClient(
+ client_id=client_id,
+ client_name=name,
+ redirect_uris=tuple(redirects),
+ registered_at=now,
+ )
+ await self.store.put(
+ PUBLIC_CLIENT,
+ client_id,
+ record.to_json(),
+ # Kept briefly until its first sign-in, which keeps it for long
+ # (`_keep_registration`): registering alone costs the company an hour's record.
+ expires_at=now + _REGISTRATION_UNUSED,
+ )
+ return CompanyResponse(
+ 201,
+ {
+ "client_id": client_id,
+ "client_id_issued_at": int(now.timestamp()),
+ "client_name": name,
+ "redirect_uris": list(redirects),
+ "token_endpoint_auth_method": "none",
+ "grant_types": [AUTHORIZATION_CODE_GRANT, REFRESH_TOKEN_GRANT],
+ "response_types": ["code"],
+ },
+ {"Cache-Control": "no-store"},
+ )
+
+ async def _registration_admitted(self, address: str | None) -> None:
+ """Whether this address may register one more client now, or HTTP 429.
+
+ The host's `pap.company.rateLimit` is asked first, with `registration:{address}`
+ where it is asked a `client_id` and no account; then the company's own count,
+ `client_registrations_per_hour` for each address. A host that names no address
+ has one count for everyone, so registration stays bounded.
+ """
+
+ key = address or "unknown"
+ limit = optional_contribution(self.reactor, COMPANY_RATE_LIMITS, "rate limit")
+ if limit is not None:
+ wait = await cast(RateLimit, limit).admit(f"registration:{key}", None)
+ if wait is not None:
+ raise _RateLimitedError(max(1, int(wait)))
+ now = self._now()
+ for _ in range(_CAS_ATTEMPTS):
+ if await self.store.create(
+ REGISTRATION_COUNT,
+ key,
+ RegistrationCount(count=1).to_json(),
+ expires_at=now + _REGISTRATION_WINDOW,
+ ):
+ return
+ entry = await self.store.get(REGISTRATION_COUNT, key)
+ if entry is None:
+ continue
+ count = RegistrationCount.from_json(entry.value).count
+ if count >= self.config.client_registrations_per_hour:
+ until = entry.expires_at or now + _REGISTRATION_WINDOW
+ raise _RateLimitedError(max(1, math.ceil((until - now).total_seconds())))
+ if await self.store.replace(
+ REGISTRATION_COUNT,
+ key,
+ entry.version,
+ RegistrationCount(count=count + 1).to_json(),
+ expires_at=entry.expires_at,
+ ):
+ return
+ raise _RefusedError(503, "temporarily_unavailable")
+
+ async def public_client_sign_ins(self) -> tuple[PublicClientSignIn, ...]:
+ """The sign-ins of public clients that have not ended, for the company's owner.
+
+ One for each time a person allowed a public client (an MCP client): which
+ client, verified by its domain or not, where the browser went back, for which
+ service and account, with which scopes, since when, when it last got tokens,
+ and until when. Each is ended whole by `revoke_public_client_sign_in`.
+
+ Read from every sign-in the company keeps, a personal agent's among them
+ (`store.records`): a company with very many reads them all each time.
+ """
+
+ now = self._now()
+ sign_ins = []
+ for record in await self.store.records(ACCOUNT_FAMILY):
+ family = AccountFamily.from_json(record.value)
+ if family.public is None or family.revoked or not family.tokens:
+ continue
+ # A sign-in is kept by its first refresh token's digest, which keeps its terms.
+ grant = await self._read(REFRESH_TOKEN, family.tokens[0], AccountGrant.from_json)
+ if grant is None or now >= grant.expires_at:
+ continue
+ sign_ins.append(
+ PublicClientSignIn(
+ sign_in_id=family.tokens[0],
+ client_id=family.client_id,
+ client_name=family.public.name,
+ verified=family.public.verified,
+ redirect_host=family.public.redirect_host,
+ resource=family.public.resource,
+ account_id=family.account_id,
+ scopes=grant.scopes,
+ signed_in_at=grant.signed_in_at,
+ last_used_at=family.last_used_at,
+ expires_at=grant.expires_at,
+ )
+ )
+ return tuple(sign_ins)
+
+ async def revoke_public_client_sign_in(self, sign_in_id: str) -> bool:
+ """The company's owner, or the person, ends one public client's sign-in: its
+ refresh and access tokens stop working at once. `False` when there is no such
+ sign-in of a public client, or it had ended."""
+
+ family = await self._read(ACCOUNT_FAMILY, sign_in_id, AccountFamily.from_json)
+ if family is None or family.public is None or family.revoked:
+ return False
+ await self._sign_out((sign_in_id,))
+ return True
+
# Direct Sign-In (§4.5) -------------------------------------------------------------
async def _pushed_request(self, request: CompanyRequest) -> CompanyResponse:
@@ -2815,35 +3504,66 @@ async def _authorize( # noqa: C901 - the checks of §4.2, then the page
return self._page(400, "This sign-in request is not valid.")
client_id = query.get("client_id", "")
redirect_uri = query.get("redirect_uri", "")
- if not client_id or not await self._allowed(client_id):
+ if not client_id:
return self._page(400, "This sign-in request is not valid.")
- resolver = cast(
- ClientResolver, first_contribution(self.reactor, CLIENT_RESOLVERS, "client")
- )
- try:
- metadata, _ = await resolver.resolve(client_id)
- except (PersonalAgentProtocolError, ValueError):
+ client = await self._authorizing_client(client_id)
+ if client is None:
return self._page(400, "This agent could not be verified.")
# An unknown client or redirect is never redirected to: that would be an open redirector.
# Exactly, but a loopback redirect URI matches with any port (§4.5, RFC 8252 §7.3).
- if not any(redirect_uri_matches(entry, redirect_uri) for entry in metadata.redirect_uris):
+ matches = public_redirect_uri_matches if client.public else redirect_uri_matches
+ if not any(matches(entry, redirect_uri) for entry in client.redirect_uris):
return self._page(400, "This sign-in request is not valid.")
state = query.get("state", "")
+
+ verified = client.verified
+
+ def refuse(error: str) -> CompanyResponse:
+ if not verified:
+ # Anyone registers a client with any HTTPS redirect: answering it an error
+ # with no one's consent would make this endpoint an open redirector
+ # (RFC 9700 §4.11.2). The person sees a page instead.
+ return self._page(400, "This sign-in request is not valid.")
+ return self._redirect(redirect_uri, error=error, state=state)
+
scopes = tuple(scope for scope in query.get("scope", "").split(" ") if scope)
if query.get("response_type") != "code":
- return self._redirect(redirect_uri, error="unsupported_response_type", state=state)
+ return refuse("unsupported_response_type")
if query.get("code_challenge_method") != "S256" or not query.get("code_challenge"):
- return self._redirect(redirect_uri, error="invalid_request", state=state)
- if not scopes or any(scope not in self.config.offered_scopes for scope in scopes):
- return self._redirect(redirect_uri, error="invalid_scope", state=state)
- if not await self._sign_in_allowed(client_id, AUTHORIZATION_CODE_GRANT):
- # Refused sign-in, or this type of it: served signed out (§4.1).
- return self._redirect(redirect_uri, error="unauthorized_client", state=state)
+ return refuse("invalid_request")
+ offered = self.config.public_scopes if client.public else self.config.offered_scopes
+ if not scopes or any(scope not in offered for scope in scopes):
+ return refuse("invalid_scope")
asked = scopes
- try:
- scopes = self._granted_to_agents(asked)
- except _RefusedError:
- return self._redirect(redirect_uri, error="invalid_scope", state=state)
+ public: PublicClient | None = None
+ if client.public:
+ if pushed_by is not None or not _CODE_CHALLENGE.fullmatch(query["code_challenge"]):
+ return refuse("invalid_request")
+ resource = query.get("resource")
+ if (
+ resource is None
+ or resource not in self._public_resources()
+ or not await self._resource_allowed(client_id, resource)
+ ):
+ # The one service the sign-in is for, named here and at the token
+ # endpoint (RFC 8707): never the default token.
+ return refuse("invalid_target")
+ if not await self._public_sign_in_allowed(client_id):
+ return refuse("unauthorized_client")
+ public = PublicClient(
+ name=client.name,
+ verified=client.verified,
+ resource=resource,
+ redirect_host=redirect_host(redirect_uri),
+ )
+ else:
+ if not await self._sign_in_allowed(client_id, AUTHORIZATION_CODE_GRANT):
+ # Refused sign-in, or this type of it: served signed out (§4.1).
+ return refuse("unauthorized_client")
+ try:
+ scopes = self._granted_to_agents(asked)
+ except _RefusedError:
+ return refuse("invalid_scope")
request_id = self._id("authz")
expires_at = self._now() + timedelta(minutes=10)
# The company's own page binds the request to this browser: its consent cookie
@@ -2861,10 +3581,11 @@ async def _authorize( # noqa: C901 - the checks of §4.2, then the page
state=state,
code_challenge=query["code_challenge"],
expires_at=expires_at,
- client_name=metadata.client_name,
+ client_name=client.name,
browser_binding=None if hosted is not None else _digest(browser),
prompt=query.get("prompt"),
dpop_jkt=pushed_by,
+ public=public,
).to_json(),
expires_at=expires_at,
)
@@ -2878,12 +3599,37 @@ async def _authorize( # noqa: C901 - the checks of §4.2, then the page
"Cache-Control": "no-store",
},
)
- agent = html.escape(metadata.client_name)
+ agent = html.escape(client.name)
agent_domain = html.escape(urlsplit(client_id).hostname or "")
described = "".join(
f"
{agent} ({agent_domain}) asks to:
" + if public.verified + else f"Unverified app. It calls itself " + f"{agent}, and nothing confirms that. It asks to:
" + ) + return self._page( + 200, + f"Only continue if you asked {agent} to do this just now.
" + f"{who}If you allow, your browser goes back to " + f"{html.escape(public.redirect_host)}.
" + f'', + cookie=f"{CONSENT_COOKIE}={browser}; Path=/; Secure; HttpOnly; SameSite=Strict", + ) # The heading names the agent and says it wants to connect, never "Sign in with", # and the page says to go on only if the person just asked it to (§10.8; guides, # consent pages): anyone can start a sign-in and send someone else the link. @@ -2901,6 +3647,39 @@ async def _authorize( # noqa: C901 - the checks of §4.2, then the page cookie=f"{CONSENT_COOKIE}={browser}; Path=/; Secure; HttpOnly; SameSite=Strict", ) + async def _authorizing_client(self, client_id: str) -> _Client | None: + """Who asks at the authorization endpoint, by its `client_id`; `None` when it can't + be verified. + + A URL is a client ID metadata document: a personal agent's when it names its + keys, and otherwise, with `public_clients`, a public client's when it says it + authenticates with nothing. No document is both, so which class a client is of + is its own domain's to say, and never the request's. Anything else is the + `client_id` of a client that registered itself. + """ + + if not client_id.startswith("https://"): + if not self.config.client_registration or not await self._public_allowed(client_id): + return None + return await self._registered_client(client_id) + # The policy before anything is fetched: as a personal agent, then as a public + # client. A `client_id` neither allows is never resolved. + if await self._allowed(client_id): + resolver = cast( + ClientResolver, first_contribution(self.reactor, CLIENT_RESOLVERS, "client") + ) + try: + metadata, _ = await resolver.resolve(client_id) + except (PersonalAgentProtocolError, ValueError): + pass + else: + return _Client( + name=metadata.client_name, redirect_uris=tuple(metadata.redirect_uris) + ) + if not self.config.public_clients or not await self._public_allowed(client_id): + return None + return await self._verified_public_client(client_id) + async def consent_decision(self, request: CompanyRequest) -> ConsentDecision: """The decision the company's own consent form posted, once it is shown to be the user's. @@ -2940,9 +3719,15 @@ async def authorization_request( Who asks (the agent's `client_name` and its `client_id` domain), for what (each requested scope with its `custom_scopes` words), until when, and the - request's `prompt`. No `state`, PKCE challenge, or redirect: nothing that helps + request's `prompt`. No `state`, PKCE challenge, or redirect URI: nothing that helps answer it. Raises `KeyError` for an unknown, used, or expired request. + `client_class` says who asks: a `personal_agent`, or with `public_clients` a + `public_client` (an MCP client). `verified` is false for a public client that + registered itself: its `client_name` is only what it said, and the page says so. + `redirect_host` is where the person's browser goes back to, which the page shows + prominently for a public client, with the `resource` the sign-in is for. + The page lists every scope in `scopes`, the ones the account granted this agent before too, and is shown even when it granted them all (§4.2, §10.8): every User of an agent shares its `client_id`. With `account_id`, the person signed in on @@ -2958,8 +3743,13 @@ async def authorization_request( if account_id is not None else None ) + public = pending.public return { "request_id": request_id, + "client_class": "personal_agent" if public is None else "public_client", + "verified": public is None or public.verified, + "redirect_host": redirect_host(pending.redirect_uri), + **({} if public is None else {"resource": public.resource}), "client_name": pending.client_name, "client_domain": urlsplit(pending.client_id).hostname or "", # What the page starts with and says before the person goes on (§10.8). @@ -3026,6 +3816,7 @@ async def approve_authorization( scopes=granted, expires_at=expires_at, dpop_jkt=pending.dpop_jkt, + public=pending.public, ).to_json(), expires_at=expires_at, ) @@ -3054,10 +3845,12 @@ async def _code_grant( if ( issued is None or self._now() >= issued.expires_at + or issued.public is not None or issued.client_id != client_id or issued.redirect_uri != form.get("redirect_uri") ): - # Expired, reused, another agent's, or for another redirect (§4.2). + # Expired, reused, a public client's, another agent's, or for another + # redirect (§4.2). raise _RefusedError(400, "invalid_grant") verifier = form.get("code_verifier", "") challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip( @@ -3324,6 +4117,10 @@ async def resolve(agent: str, kid: str | None) -> tuple[ClientMetadata, JsonWebK issued: IssuedAccessToken | None = None if presented is not None: issued = await self._access_token(presented) + if issued is not None and issued.public: + # A public client's token is for its one service, used without a Session: + # the protocol's endpoints take it from no one, whatever header comes with it. + raise _RefusedError(401, "invalid_token") if issued is not None and issued.client_id != verified.client_id: # Issued to another agent than the Session JWT's (§5.3). raise SessionError("invalid_session", "Token of another agent", status_code=400) @@ -5048,10 +5845,16 @@ def _offers(self, scopes: Sequence[str]) -> bool: async def _mcp_route( # noqa: C901 - the JSON-RPC methods self, request: CompanyRequest ) -> CompanyResponse: - session = await self._mcp_caller(request) - if isinstance(session, CompanyResponse): - # An expired or other-resource token. - return session + public = await self._public_mcp_caller(request) + if isinstance(public, CompanyResponse): + return public + session: CallerSession | None = None + if public is None: + caller = await self._mcp_caller(request) + if isinstance(caller, CompanyResponse): + # An expired or other-resource token. + return caller + session = caller if request.method.upper() != "POST": return CompanyResponse(405, {"error": "method_not_allowed"}, {"Allow": "POST"}) try: @@ -5077,7 +5880,11 @@ async def _mcp_route( # noqa: C901 - the JSON-RPC methods elif method == "tools/list": result = {"tools": mcp.tools()} elif method == "tools/call": - outcome = await self._mcp_tool(session, mcp, cast(dict, params)) + outcome = ( + await self._public_mcp_tool(public, mcp, cast(dict, params)) + if public is not None + else await self._mcp_tool(cast(CallerSession, session), mcp, cast(dict, params)) + ) if isinstance(outcome, CompanyResponse): return outcome result = outcome @@ -5085,6 +5892,87 @@ async def _mcp_route( # noqa: C901 - the JSON-RPC methods return _rpc_error(request_id, -32601, "Method not found") return CompanyResponse(200, {"jsonrpc": "2.0", "id": request_id, "result": result}) + async def _public_mcp_caller( + self, request: CompanyRequest + ) -> IssuedAccessToken | CompanyResponse | None: + """A public client at the MCP server: its token alone, and no Session (§7). + + `None` for any other request, which is a personal agent's and is checked as one: + one with a Session header, whatever token it carries, and one whose token is not + a public client's. A public client's token works here only when it was issued + for this server, within what the company gives public clients now, and the + client policy still allows its client and this service for it. + """ + + if not (self.config.public_clients and self.config.oauth): + return None + if request.headers.get(SESSION_HEADER): + return None + scheme, _, presented = request.headers.get("authorization", "").partition(" ") + if scheme.lower() != "bearer" or not presented: + return None + issued = await self._access_token(presented) + if issued is None or not issued.public: + return None + if ( + issued.resource != self.config.mcp_url + or not self._offers(issued.scopes) + or not self._public_token_within(issued) + or not await self._public_allowed(issued.client_id) + or not await self._resource_allowed(issued.client_id, self.config.mcp_url) + ): + return self._mcp_refusal(401, "invalid_token") + exchange = _EXCHANGE.get() + if exchange is not None: + exchange.client_id = issued.client_id + limit = optional_contribution(self.reactor, COMPANY_RATE_LIMITS, "rate limit") + if limit is not None: + wait = await cast(RateLimit, limit).admit(issued.client_id, issued.account_id) + if wait is not None: + raise _RateLimitedError(max(1, int(wait))) + return issued + + async def _public_mcp_tool( + self, issued: IssuedAccessToken, mcp: CompanyMcp, params: dict[str, Any] + ) -> dict[str, Any] | CompanyResponse: + """A tool called by a public client: with its account and scopes, and no Session. + + An action that needs the person's approval is not done and returns no operation: + operations are approved by a personal agent in its Session (Operations 6), and a + public client has neither. + """ + + name = params.get("name") + arguments = params.get("arguments") or {} + if not isinstance(name, str) or not isinstance(arguments, dict): + return _rpc_error(None, -32602, "Invalid params") + answer = await mcp.call( + name, + arguments, + ApiCall( + method="TOOL", + path=name, + query={}, + body=arguments, + account_id=issued.account_id, + scopes=issued.scopes, + client_id=issued.client_id, + carries_approval=False, + ), + ) + if answer.refusal is not None: + status, error, scope = answer.refusal + return self._mcp_refusal(status, error, scope) + if answer.operation is not None: + return {"content": [{"type": "text", "text": _PUBLIC_NEEDS_APPROVAL}], "isError": True} + text = answer.text if answer.text is not None else json.dumps(answer.structured or {}) + result: dict[str, Any] = {"content": [{"type": "text", "text": text}]} + if answer.structured is not None: + result["structuredContent"] = answer.structured + if answer.is_error: + result["isError"] = True + return result + async def _mcp_tool( self, session: CallerSession, mcp: CompanyMcp, params: dict[str, Any] ) -> dict[str, Any] | CompanyResponse: diff --git a/personal_agent_protocol/company/store.py b/personal_agent_protocol/company/store.py index 8a756c6..80170df 100644 --- a/personal_agent_protocol/company/store.py +++ b/personal_agent_protocol/company/store.py @@ -72,6 +72,11 @@ #: The User ID a delegated key signed for, by agent and key thumbprint, while its delegation #: lasts: a key that signs for another User ID is refused (§5.2). DELEGATED_KEY = "delegated_key" +#: A public client that registered itself (RFC 7591), by the `client_id` it was given: its +#: name and redirect URIs, as it stated them. Nothing verifies them. +PUBLIC_CLIENT = "public_client" +#: How many clients one address registered in the current window (RFC 7591 §5). +REGISTRATION_COUNT = "registration_count" RECORD_KINDS = ( SESSION, @@ -99,6 +104,8 @@ DPOP_NONCE, IDEMPOTENCY, DELEGATED_KEY, + PUBLIC_CLIENT, + REGISTRATION_COUNT, ) @@ -276,6 +283,96 @@ def _maybe_parse(value: str | None) -> datetime | None: return None if value is None else datetime.fromisoformat(value) +@dataclass(frozen=True) +class PublicClient: + """What a sign-in by a public client carries, from its request to its tokens. + + A public client is another client than a personal agent (an MCP client): it + authenticates with nothing but PKCE, and its tokens work at one service and never + at the protocol's own endpoints. `verified` says its `client_id` is a client ID + metadata document read from its own domain; a client that registered itself + (RFC 7591) is not, and its `name` is only what it said. `resource` is the one + service the sign-in is for; `redirect_host` where the person's browser was sent back. + """ + + name: str + verified: bool + resource: str + redirect_host: str + + def to_json(self) -> JsonObject: + return { + "name": self.name, + "verified": self.verified, + "resource": self.resource, + "redirect_host": self.redirect_host, + } + + @classmethod + def from_json(cls, value: JsonObject) -> PublicClient: + return cls( + name=value["name"], + verified=value["verified"], + resource=value["resource"], + redirect_host=value["redirect_host"], + ) + + +def _maybe_public(value: JsonObject) -> PublicClient | None: + public = value.get("public") + return None if public is None else PublicClient.from_json(public) + + +def _with_public(record: JsonObject, public: PublicClient | None) -> JsonObject: + """`record`, naming its public client when it has one: a personal agent's record is + written exactly as before.""" + + if public is not None: + record["public"] = public.to_json() + return record + + +@dataclass(frozen=True) +class RegisteredClient: + """A public client that registered itself (RFC 7591): what it said, never verified.""" + + client_id: str + client_name: str + redirect_uris: tuple[str, ...] + registered_at: datetime + + def to_json(self) -> JsonObject: + return { + "client_id": self.client_id, + "client_name": self.client_name, + "redirect_uris": list(self.redirect_uris), + "registered_at": _time(self.registered_at), + } + + @classmethod + def from_json(cls, value: JsonObject) -> RegisteredClient: + return cls( + client_id=value["client_id"], + client_name=value["client_name"], + redirect_uris=tuple(value["redirect_uris"]), + registered_at=_parse(value["registered_at"]), + ) + + +@dataclass(frozen=True) +class RegistrationCount: + """The clients one address registered in the window its record lasts.""" + + count: int + + def to_json(self) -> JsonObject: + return {"count": self.count} + + @classmethod + def from_json(cls, value: JsonObject) -> RegistrationCount: + return cls(count=value["count"]) + + @dataclass(frozen=True) class IssuedAccessToken: """An access token the company issued: for whom, which account, which service (§4.5). @@ -293,9 +390,12 @@ class IssuedAccessToken: family: str resource: str | None = None dpop_jkt: str | None = None + #: Issued to a public client (an MCP client), never a personal agent: it works at + #: its `resource` alone, and belongs to no Session. + public: bool = False def to_json(self) -> JsonObject: - return { + record: JsonObject = { "client_id": self.client_id, "account_id": self.account_id, "scopes": list(self.scopes), @@ -304,6 +404,9 @@ def to_json(self) -> JsonObject: "resource": self.resource, "dpop_jkt": self.dpop_jkt, } + if self.public: + record["public"] = True + return record @classmethod def from_json(cls, value: JsonObject) -> IssuedAccessToken: @@ -315,6 +418,7 @@ def from_json(cls, value: JsonObject) -> IssuedAccessToken: family=value["family"], resource=value["resource"], dpop_jkt=value["dpop_jkt"], + public=value.get("public") is True, ) @@ -380,18 +484,24 @@ class AccountGrant: #: issued it, carried by every token rotated from it: a refresh proves with that #: key, or is `invalid_grant` (§4.4). `None`: not bound. dpop_jkt: str | None = None + #: The public client the sign-in is of, carried by every token rotated from it; + #: `None` for a personal agent's. + public: PublicClient | None = None def to_json(self) -> JsonObject: - return { - "account_id": self.account_id, - "client_id": self.client_id, - "scopes": list(self.scopes), - "expires_at": _time(self.expires_at), - "revoked": self.revoked, - "family": self.family, - "signed_in_at": _maybe_time(self.signed_in_at), - "dpop_jkt": self.dpop_jkt, - } + return _with_public( + { + "account_id": self.account_id, + "client_id": self.client_id, + "scopes": list(self.scopes), + "expires_at": _time(self.expires_at), + "revoked": self.revoked, + "family": self.family, + "signed_in_at": _maybe_time(self.signed_in_at), + "dpop_jkt": self.dpop_jkt, + }, + self.public, + ) @classmethod def from_json(cls, value: JsonObject) -> AccountGrant: @@ -404,6 +514,7 @@ def from_json(cls, value: JsonObject) -> AccountGrant: family=value["family"], signed_in_at=_maybe_parse(value.get("signed_in_at")), dpop_jkt=value.get("dpop_jkt"), + public=_maybe_public(value), ) @@ -417,15 +528,25 @@ class AccountFamily: access_tokens: tuple[str, ...] = () #: Revoked (§4.6) or disconnected: no token joins it any more. revoked: bool = False + #: The public client the sign-in is of; `None` for a personal agent's. + public: PublicClient | None = None + #: When a public client's sign-in last got tokens: at the sign-in, then each refresh. + last_used_at: datetime | None = None def to_json(self) -> JsonObject: - return { - "client_id": self.client_id, - "account_id": self.account_id, - "tokens": list(self.tokens), - "access_tokens": list(self.access_tokens), - "revoked": self.revoked, - } + record = _with_public( + { + "client_id": self.client_id, + "account_id": self.account_id, + "tokens": list(self.tokens), + "access_tokens": list(self.access_tokens), + "revoked": self.revoked, + }, + self.public, + ) + if self.last_used_at is not None: + record["last_used_at"] = _time(self.last_used_at) + return record @classmethod def from_json(cls, value: JsonObject) -> AccountFamily: @@ -435,6 +556,8 @@ def from_json(cls, value: JsonObject) -> AccountFamily: tokens=tuple(value["tokens"]), access_tokens=tuple(value["access_tokens"]), revoked=value["revoked"], + public=_maybe_public(value), + last_used_at=_maybe_parse(value.get("last_used_at")), ) @@ -539,21 +662,27 @@ class PendingAuthorization: #: The thumbprint of the DPoP key that pushed the request (RFC 9449 §10.1): the code is #: exchanged only with a proof by that key. dpop_jkt: str | None = None + #: The public client that asks, with whether it is verified and where the browser + #: goes back, for the consent page to show; `None` when a personal agent asks. + public: PublicClient | None = None def to_json(self) -> JsonObject: - return { - "client_id": self.client_id, - "redirect_uri": self.redirect_uri, - "scopes": list(self.scopes), - "state": self.state, - "code_challenge": self.code_challenge, - "expires_at": _time(self.expires_at), - "client_name": self.client_name, - "browser_binding": self.browser_binding, - "requested": None if self.requested is None else list(self.requested), - "prompt": self.prompt, - "dpop_jkt": self.dpop_jkt, - } + return _with_public( + { + "client_id": self.client_id, + "redirect_uri": self.redirect_uri, + "scopes": list(self.scopes), + "state": self.state, + "code_challenge": self.code_challenge, + "expires_at": _time(self.expires_at), + "client_name": self.client_name, + "browser_binding": self.browser_binding, + "requested": None if self.requested is None else list(self.requested), + "prompt": self.prompt, + "dpop_jkt": self.dpop_jkt, + }, + self.public, + ) @classmethod def from_json(cls, value: JsonObject) -> PendingAuthorization: @@ -569,6 +698,7 @@ def from_json(cls, value: JsonObject) -> PendingAuthorization: requested=None if value.get("requested") is None else tuple(value["requested"]), prompt=value.get("prompt"), dpop_jkt=value.get("dpop_jkt"), + public=_maybe_public(value), ) @@ -628,18 +758,24 @@ class IssuedCode: expires_at: datetime #: The DPoP key that pushed the request (RFC 9449 §10.1): the exchange proves with it. dpop_jkt: str | None = None + #: The public client the code was issued to; `None` for a personal agent's. A code + #: is exchanged only by the class of client it was issued to. + public: PublicClient | None = None def to_json(self) -> JsonObject: - return { - "requested": list(self.requested), - "client_id": self.client_id, - "redirect_uri": self.redirect_uri, - "code_challenge": self.code_challenge, - "account_id": self.account_id, - "scopes": list(self.scopes), - "expires_at": _time(self.expires_at), - "dpop_jkt": self.dpop_jkt, - } + return _with_public( + { + "requested": list(self.requested), + "client_id": self.client_id, + "redirect_uri": self.redirect_uri, + "code_challenge": self.code_challenge, + "account_id": self.account_id, + "scopes": list(self.scopes), + "expires_at": _time(self.expires_at), + "dpop_jkt": self.dpop_jkt, + }, + self.public, + ) @classmethod def from_json(cls, value: JsonObject) -> IssuedCode: @@ -652,6 +788,7 @@ def from_json(cls, value: JsonObject) -> IssuedCode: scopes=tuple(value["scopes"]), expires_at=_parse(value["expires_at"]), dpop_jkt=value.get("dpop_jkt"), + public=_maybe_public(value), ) @@ -1202,4 +1339,6 @@ def from_json(cls, value: JsonObject) -> IdempotencyRecord: DPOP_NONCE: IssuedNonce.from_json, IDEMPOTENCY: IdempotencyRecord.from_json, DELEGATED_KEY: DelegatedKeyUse.from_json, + PUBLIC_CLIENT: RegisteredClient.from_json, + REGISTRATION_COUNT: RegistrationCount.from_json, } diff --git a/personal_agent_protocol/company/testing.py b/personal_agent_protocol/company/testing.py index 3f81be0..3debdb4 100644 --- a/personal_agent_protocol/company/testing.py +++ b/personal_agent_protocol/company/testing.py @@ -58,10 +58,12 @@ async def test_my_replay_cache_conforms() -> None: MEDIATED, OPERATION, PROPOSAL, + PUBLIC_CLIENT, PUSHED_REQUEST, RECORD_KINDS, RECORD_TYPES, REFRESH_TOKEN, + REGISTRATION_COUNT, REPLAY, REQUEST_ID, SESSION, @@ -86,6 +88,8 @@ async def test_my_replay_cache_conforms() -> None: PendingDevice, PendingMediated, PushedAuthorization, + RegisteredClient, + RegistrationCount, ReplayMark, RequestReceipt, SignInAttempts, @@ -222,6 +226,13 @@ def record_samples(now: datetime) -> dict[str, Any]: ), IDEMPOTENCY: IdempotencyRecord("digest", 200, {"summary": "Exchanged."}), DELEGATED_KEY: DelegatedKeyUse("usr_1"), + PUBLIC_CLIENT: RegisteredClient( + client_id="mcpc_Yx2b7Qd_Kp8mR3vT1nWc4A", + client_name="An MCP client", + redirect_uris=("http://127.0.0.1/callback", "https://client.example/callback"), + registered_at=now, + ), + REGISTRATION_COUNT: RegistrationCount(count=3), } diff --git a/personal_agent_protocol/identity.py b/personal_agent_protocol/identity.py index 288cedf..196b20a 100644 --- a/personal_agent_protocol/identity.py +++ b/personal_agent_protocol/identity.py @@ -23,7 +23,7 @@ ProtocolValidationError, ) from .json import loads_strict -from .models import ClientMetadata, JsonWebKeySet +from .models import ClientMetadata, JsonWebKeySet, PublicClientMetadata from .operator_signatures import OPERATOR_DIRECTORY_MEDIA_TYPE from .reactor import ( DISCOVERY_TRANSPORTS, @@ -141,18 +141,7 @@ async def aclose(self) -> None: async def fetch_metadata(self, client_id: str) -> ClientMetadata: """Fetch client metadata without redirects and bind it to ``client_id``.""" - requested = self._fetchable_url(client_id) - now = self._cache.now() - remembered = self._unfetchable.get(requested) - if remembered is not None and now < remembered[0]: - raise type(remembered[1])(remembered[1].code, "Client metadata could not be fetched") - try: - data = await self._cached_json( - f"pap.client-metadata:{requested}", requested, max_redirects=0, required_host=None - ) - except (DiscoveryError, IdentityError) as error: - _remember(self._unfetchable, requested, (now + self._unfetchable_for, error), now) - raise + requested, data = await self._client_document(client_id) try: metadata = ClientMetadata.model_validate(data) except ValidationError as exc: @@ -166,6 +155,48 @@ async def fetch_metadata(self, client_id: str) -> ClientMetadata: ) return metadata + async def fetch_public_metadata(self, client_id: str) -> PublicClientMetadata: + """Fetch a public client's client ID metadata document, bound to ``client_id``. + + The document a personal agent's metadata is read from, fetched the same way: + HTTPS, no redirect, bounded, and only at an address `pap.urlSafetyPolicy` approves, + so a `client_id` naming a private address is never fetched. It is a public + client's only when it says `token_endpoint_auth_method` is `none` and names no + key; a personal agent's document is refused here, as a public client's is by + `fetch_metadata`. + """ + + requested, data = await self._client_document(client_id) + try: + metadata = PublicClientMetadata.model_validate(data) + except ValidationError as exc: + raise ProtocolValidationError( + "invalid_client_metadata", "Client metadata is not a public client's" + ) from exc + if metadata.client_id != requested: + raise IdentityError( + "client_id_mismatch", + "Client metadata client_id does not match the URL that was fetched", + ) + return metadata + + async def _client_document(self, client_id: str) -> tuple[str, object]: + """The document at a `client_id`, cached, and the URL it was fetched at.""" + + requested = self._fetchable_url(client_id) + now = self._cache.now() + remembered = self._unfetchable.get(requested) + if remembered is not None and now < remembered[0]: + raise type(remembered[1])(remembered[1].code, "Client metadata could not be fetched") + try: + data = await self._cached_json( + f"pap.client-metadata:{requested}", requested, max_redirects=0, required_host=None + ) + except (DiscoveryError, IdentityError) as error: + _remember(self._unfetchable, requested, (now + self._unfetchable_for, error), now) + raise + return requested, data + async def fetch_jwks(self, client_id: str, *, kid: str | None = None) -> JsonWebKeySet: """Fetch a verified client's bounded, public-only signing key set. diff --git a/personal_agent_protocol/models.py b/personal_agent_protocol/models.py index 8f81cdc..1555def 100644 --- a/personal_agent_protocol/models.py +++ b/personal_agent_protocol/models.py @@ -199,6 +199,118 @@ def redirect_uri_matches(registered: str, given: str) -> bool: return (one.hostname, one.path, one.query) == (other.hostname, other.path, other.query) +#: A public client's HTTPS redirect URI: a host of DNS labels in small ASCII letters (an +#: internationalized name as its A-labels), a port when it is not 443, then a path or a +#: query. Read as text, never through a URL parser: what is compared is what was written. +_PUBLIC_HTTPS_REDIRECT = re.compile( + r"https://([a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?)" + r"([/?].*)?" +) +#: A public client's loopback redirect URI: `127.0.0.1`, `[::1]` or `localhost`, any port. +_PUBLIC_LOOPBACK_REDIRECT = re.compile( + r"http://((127\.0\.0\.1|\[::1\]|localhost)(:[0-9]{1,5})?)([/?].*)?" +) +#: The longest redirect URI a public client names, and the longest name it shows. +PUBLIC_REDIRECT_URI_MAX = 2000 +PUBLIC_CLIENT_NAME_MAX = 100 +#: Characters a client's name never holds: controls, and the marks that reorder or hide +#: text on the consent page (bidirectional overrides and isolates, zero-width marks). +_UNSHOWABLE = re.compile( + "[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]" +) +#: What no redirect URI holds: a space, a control character, a backslash, a fragment. +_UNSAFE_IN_REDIRECT = re.compile("[\u0000-\u0020\u007f-\u009f\\\\#]") + + +def _port_is_a_port(authority: str) -> bool: + """Whether the authority's port, if it names one, is a port (1 to 65535).""" + + port = authority.rpartition(":")[2] if not authority.endswith("]") else "" + if ":" not in authority or not port: + return True + return port.isdigit() and 0 < int(port) <= 65535 + + +def _public_redirect(value: str) -> tuple[bool, str, str, str] | None: + """A public client's redirect URI, as `(loopback, authority, host, rest)`; `None` for + anything else.""" + + if not value or len(value) > PUBLIC_REDIRECT_URI_MAX or _UNSAFE_IN_REDIRECT.search(value): + return None + loopback = _PUBLIC_LOOPBACK_REDIRECT.fullmatch(value) + if loopback is not None and _port_is_a_port(loopback.group(1)): + return True, loopback.group(1), loopback.group(2), loopback.group(4) or "" + https = _PUBLIC_HTTPS_REDIRECT.fullmatch(value) + if https is not None and _port_is_a_port(https.group(1)): + authority = https.group(1) + return False, authority, authority.partition(":")[0], https.group(6) or "" + return None + + +def is_public_loopback_redirect(value: str) -> bool: + """A public client's loopback redirect URI (RFC 8252 §7.3, §8.3): `http` to + `127.0.0.1`, `[::1]` or `localhost`, any port, no user information, no fragment. + + `localhost` is taken here, though a personal agent's loopback redirect is an IP + literal (`is_loopback_redirect`): the apps that are MCP clients name it. + """ + + parsed = _public_redirect(value) + return parsed is not None and parsed[0] + + +def public_redirect_uri(value: str) -> str: + """A redirect URI a public client may name: loopback, or HTTPS (`ValueError` otherwise). + + HTTPS to a host in small ASCII letters, a port allowed; or `http` to the User's own + computer (`is_public_loopback_redirect`). Never user information, a fragment, a + backslash, a space or a control character, each a way to make two readers of one URL + see two hosts; never another scheme. Read as text, as written: nothing is normalized. + """ + + if not isinstance(value, str) or _public_redirect(value) is None: + raise ValueError( + "a redirect URI is HTTPS to a host in small letters, or http to the loopback, " + "with no user information, fragment, backslash or space" + ) + return value + + +def public_redirect_uri_matches(registered: str, given: str) -> bool: + """Whether `given` is the redirect URI a public client `registered`. + + Exactly, except that a loopback redirect URI matches with any port (RFC 8252 §7.3): + an app listens on whichever port is free. Nothing else is compared loosely: no + prefix, no other path, no added query, no other host. + """ + + one, other = _public_redirect(registered), _public_redirect(given) + if one is None or other is None: + return False + if registered == given: + return True + return one[0] and other[0] and (one[2], one[3]) == (other[2], other[3]) + + +def redirect_host(redirect_uri: str) -> str: + """Where a redirect URI sends the browser back, for a consent page to show: its host, + with its port when it names one.""" + + return urlsplit(redirect_uri).netloc.rpartition("@")[2] + + +def public_client_name(value: object) -> str: + """A public client's name as a consent page shows it (`ValueError` otherwise): text of + 1 to 100 characters, with no control character and none that reorders or hides text.""" + + if not isinstance(value, str): + raise ValueError("client_name is text") + name = value.strip() + if not name or len(name) > PUBLIC_CLIENT_NAME_MAX or _UNSHOWABLE.search(name): + raise ValueError("client_name is 1 to 100 characters, none of them a control character") + return name + + def _domain(value: str) -> str: normalized = value.lower() host, port = split_domain(normalized) @@ -871,6 +983,68 @@ def validate_same_domain_urls(self) -> ClientMetadata: return self +#: What a client's metadata holds when it authenticates with something: never a public +#: client's. +_CONFIDENTIAL_MEMBERS = frozenset({"jwks_uri", "jwks", "client_secret"}) + + +class PublicClientMetadata(ProtocolModel): + """The client ID metadata document of a public client: an MCP client, never a + personal agent. + + It says `token_endpoint_auth_method` is `none`, and names no key: a document with a + `jwks_uri` is a personal agent's (`ClientMetadata`), and no document is both. Its + redirect URIs a company uses are the loopback ones and the HTTPS ones on the + `client_id`'s own host (`usable_redirect_uris`); any other it names is never matched. + """ + + client_id: str + client_name: str + logo_uri: str | None = None + redirect_uris: list[str] = Field(min_length=1) + token_endpoint_auth_method: Literal["none"] + grant_types: list[str] | None = None + response_types: list[str] | None = None + + @model_validator(mode="before") + @classmethod + def reject_confidential_members(cls, value: Any) -> Any: + if isinstance(value, dict) and _CONFIDENTIAL_MEMBERS.intersection(value): + raise ValueError("a public client's metadata names no key and no secret") + return value + + @field_validator("client_id") + @classmethod + def validate_client_id(cls, value: str) -> str: + return _https_url(value, "client_id") + + @field_validator("client_name") + @classmethod + def validate_name(cls, value: str) -> str: + return public_client_name(value) + + @model_validator(mode="after") + def validate_grants(self) -> PublicClientMetadata: + if self.grant_types is not None and AUTHORIZATION_CODE_GRANT not in self.grant_types: + raise ValueError("a public client signs in with the authorization code grant") + if self.response_types is not None and "code" not in self.response_types: + raise ValueError("a public client asks for response_type code") + return self + + @property + def usable_redirect_uris(self) -> tuple[str, ...]: + """The redirect URIs a company sends this client's answers to: loopback, or HTTPS + on the `client_id`'s own host.""" + + host = urlsplit(self.client_id).hostname + usable = [] + for uri in self.redirect_uris: + parsed = _public_redirect(uri) if isinstance(uri, str) else None + if parsed is not None and (parsed[0] or parsed[2] == host): + usable.append(uri) + return tuple(usable) + + _PRIVATE_JWK_MEMBERS = frozenset({"d", "p", "q", "dp", "dq", "qi", "oth", "k"}) diff --git a/personal_agent_protocol/reactor.py b/personal_agent_protocol/reactor.py index f9dd2fc..c03bf40 100644 --- a/personal_agent_protocol/reactor.py +++ b/personal_agent_protocol/reactor.py @@ -1088,7 +1088,7 @@ def build_pap_reactor( platform.register_plugin( PluginManifest( name="personal-agent-protocol.core", - version="0.37.3", + version="0.37.5", contribution_points=[ DISCOVERY_TRANSPORTS.id, URL_SAFETY_POLICIES.id, diff --git a/src/__tests__/company.test.mjs b/src/__tests__/company.test.mjs index 1cf7699..107bcfd 100644 --- a/src/__tests__/company.test.mjs +++ b/src/__tests__/company.test.mjs @@ -1327,7 +1327,9 @@ test("authorize redirects to the hosted consent page, which reads the request ba // What the page starts with and says before the person goes on (§10.8). assert.equal(summary.heading, "Atlas wants to connect to your Manzanita Outfitters account"); assert.equal(summary.caution, "Only continue if you asked Atlas to do this just now."); - assert.deepEqual(Object.keys(summary).sort(), ["caution", "client_domain", "client_name", "expires_at", "heading", "prompt", "request_id", "scopes"]); + // Who asks, as a class of client, and where the browser goes back to. + assert.deepEqual([summary.client_class, summary.verified, summary.redirect_host], ["personal_agent", true, "atlas.example"]); + assert.deepEqual(Object.keys(summary).sort(), ["caution", "client_class", "client_domain", "client_name", "expires_at", "heading", "prompt", "redirect_host", "request_id", "scopes", "verified"]); // The agent asked for the consent page whatever the account granted before (spec 4.2). assert.equal(summary.prompt, "consent"); const callbackUrl = await w.shop.approveAuthorization(requestId, { accountId: "acct_ada" }); diff --git a/src/__tests__/public-clients.test.mjs b/src/__tests__/public-clients.test.mjs new file mode 100644 index 0000000..21a4f18 --- /dev/null +++ b/src/__tests__/public-clients.test.mjs @@ -0,0 +1,1410 @@ +/* + * Copyright (c) 2025-2026 Datalayer, Inc. + * + * BSD 3-Clause License + */ + +// Public clients: clients that are no personal agents (MCP clients) sign in with PKCE alone. +// Off by default. On, a public client is verified by its domain (a client ID metadata document +// that names no key) or registered itself (RFC 7591); it gets tokens for one service, rotated +// at every refresh, and nothing of the protocol: no Session, no default token, no approval. +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import test from "node:test"; + +import { + AgentIdentityClient, + DeviceSignInClient, + DiscoveryError, + RefreshTokenClient, + SecretValue, + SessionClient, + SessionFetchClient, + discoverCompany, + firstContribution, + negotiateExtensions, +} from "../../lib/index.js"; +import { + isPublicLoopbackRedirect, + parsePublicClientMetadata, + publicClientName, + publicRedirectUri, + publicRedirectUriMatches, + redirectHost, +} from "../../lib/models.js"; +import { ClientPolicies, ClientResolvers, CompanyConfig, CompanyRateLimits } from "../../lib/server.js"; +import { CONFIG_OPTIONS, manzanita } from "../../lib/demo/manzanita.js"; +import { MutableClock, agentHost, agentIdentity, inProcessFetch } from "./support/world.mjs"; + +const TENANT = "atlas-demo"; +const PAIRWISE = "usr_ada_at_manzanita_000000"; +const SHOP = "https://manzanita.example"; +const MCP = `${SHOP}/mcp`; +/** The company's MCP server on a host of its own. */ +const ELSEWHERE = "https://mcp.manzanita.example/mcp"; +/** A public client verified by its domain: its client ID metadata document. */ +const VERIFIED = "https://client.example/oauth/client.json"; +const VERIFIED_REDIRECT = "https://client.example/callback"; +const LOOPBACK = "http://127.0.0.1/callback"; +const LIST_TOOLS = { jsonrpc: "2.0", id: 1, method: "tools/list" }; +const VERIFIER = "v".repeat(43); +const CHALLENGE = createHash("sha256").update(VERIFIER).digest("base64url"); +const DAY = 24 * 3600; + +const document = (changes = {}) => ({ + client_id: VERIFIED, + client_name: "Deskmate", + redirect_uris: [VERIFIED_REDIRECT, LOOPBACK, "https://elsewhere.example/callback"], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + ...changes, +}); + +/** Manzanita with public clients and registration on, a verified client's site, and Atlas. */ +async function world({ site, plugins, off = false, ...config } = {}) { + const clock = new MutableClock(); + const sites = {}; + const fetch = inProcessFetch(sites); + const identity = await agentIdentity({ domain: "atlas.example", name: "Atlas" }); + sites["atlas.example"] = identity.documents; + sites["client.example"] = { "/oauth/client.json": site ?? document() }; + const settings = off + ? config + : { publicClients: true, clientRegistration: true, resourceServers: [ELSEWHERE], ...config }; + const { service: shop } = manzanita({ fetch, clock, config: settings, ...(plugins ? { plugins } : {}) }); + sites["manzanita.example"] = shop; + const call = async (method, path, { form, json, headers = {}, raw, clientAddress = "127.0.0.1" } = {}) => { + const body = raw ?? (form ? new URLSearchParams(form).toString() : json ? JSON.stringify(json) : undefined); + return shop.handle({ + method, + url: path.startsWith("https://") ? path : `${SHOP}${path}`, + headers, + ...(body === undefined ? {} : { body }), + ...(clientAddress === null ? {} : { clientAddress }), + }); + }; + const w = { clock, sites, fetch, identity, shop, call }; + w.register = (changes = {}, options = {}) => + call("POST", "/oauth/register", { + json: { + client_name: "Pocket MCP", + redirect_uris: [LOOPBACK, "https://pocket.example/callback"], + token_endpoint_auth_method: "none", + ...changes, + }, + ...options, + }); + w.registered = async (changes = {}) => { + const answer = await w.register(changes); + assert.equal(answer.status, 201, JSON.stringify(answer.body)); + return answer.body.client_id; + }; + w.authorize = (clientId, redirectUri, changes = {}) => { + const query = { + response_type: "code", + client_id: clientId, + redirect_uri: redirectUri, + scope: "orders:read", + state: "st-1", + code_challenge: CHALLENGE, + code_challenge_method: "S256", + resource: MCP, + ...changes, + }; + for (const [name, value] of Object.entries(query)) if (value === null) delete query[name]; + return call("GET", `/oauth/authorize?${new URLSearchParams(query)}`); + }; + w.token = (form) => call("POST", "/oauth/token", { form }); + w.codeFor = async (clientId, redirectUri, changes = {}) => { + const shown = await w.authorize(clientId, redirectUri, changes); + const back = await shop.approveAuthorization(requestIdOf(shown), { accountId: "acct_ada" }); + return new URL(back).searchParams.get("code"); + }; + w.signIn = async (clientId, redirectUri = LOOPBACK, { resource = MCP, scope = "orders:read" } = {}) => { + const code = await w.codeFor(clientId, redirectUri, { resource, scope }); + const answer = await w.token({ + grant_type: "authorization_code", + client_id: clientId, + code, + redirect_uri: redirectUri, + code_verifier: VERIFIER, + resource, + }); + assert.equal(answer.status, 200, JSON.stringify(answer.body)); + return answer.body; + }; + w.refresh = (clientId, refreshToken, more = {}) => + w.token({ grant_type: "refresh_token", client_id: clientId, refresh_token: refreshToken, resource: MCP, ...more }); + w.mcp = (accessToken, message) => + call("POST", "/mcp", { json: message, headers: { authorization: `Bearer ${accessToken}` } }); + return w; +} + +function requestIdOf(shown) { + assert.equal(shown.status, 200, String(shown.body)); + return /data-request-id="([^"]+)"/.exec(shown.body)[1]; +} + +const refusedPage = (answer) => answer.status === 400 && answer.headers.Location === undefined; + +/** Atlas, a personal agent, with a Session at the company, and signed in when asked. */ +async function personalAgent(w, { signIn = false } = {}) { + const host = await agentHost({ identity: w.identity, fetch: w.fetch, clock: w.clock }); + const reactor = host.reactor; + const company = await discoverCompany("manzanita.example", { reactor }); + const metadata = company.oauthMetadata; + const sessions = new SessionClient({ reactor, fetch: w.fetch }); + const session = await sessions.start({ + clientId: w.identity.clientId, + pairwiseUserId: PAIRWISE, + issuer: metadata.issuer, + tenantId: TENANT, + extensions: negotiateExtensions(company.document.extensions, w.identity.supportedExtensions), + }); + const transport = new SessionFetchClient({ reactor, fetch: w.fetch }); + const agent = { host, reactor, metadata, sessions, session, transport }; + if (signIn) { + const device = new DeviceSignInClient({ reactor, fetch: w.fetch }); + const started = await device.begin({ + deviceAuthorizationEndpoint: metadata.device_authorization_endpoint, + tokenEndpoint: metadata.token_endpoint, + issuer: metadata.issuer, + clientId: w.identity.clientId, + scopes: ["orders:read", "orders:write"], + tenantId: TENANT, + organization: company.document.organization, + }); + await w.shop.approveDevice(started.userCode, { accountId: "acct_ada" }); + w.clock.advance(started.pollInterval); + const done = await device.poll(started.reference); + assert.equal(done.status, "complete"); + const context = { + tokenEndpoint: metadata.token_endpoint, + revocationEndpoint: metadata.revocation_endpoint, + issuer: metadata.issuer, + clientId: w.identity.clientId, + tenantId: TENANT, + }; + agent.reference = done.refreshTokenReference; + agent.refreshed = () => + new RefreshTokenClient({ reactor, fetch: w.fetch }).refresh(done.refreshTokenReference, { context }); + } + return agent; +} + +// Off by default ------------------------------------------------------------------------ + +test("off, a company answers as before", async () => { + const w = await world({ off: true }); + assert.equal(w.shop.config.publicClients, false); + assert.equal(w.shop.config.clientRegistration, false); + assert.equal(w.shop.config.publicClientRefreshLifetimeSeconds, 30 * DAY); + const metadata = w.shop.oauthMetadata(); + assert.deepEqual(metadata.token_endpoint_auth_methods_supported, ["private_key_jwt"]); + assert.ok(!("registration_endpoint" in metadata)); + assert.ok(!("authorization_response_iss_parameter_supported" in metadata)); + assert.equal((await w.register()).status, 404); + // A public client's document is no personal agent's: nothing verifies it. + assert.ok(refusedPage(await w.authorize(VERIFIED, VERIFIED_REDIRECT))); + // A token request with no assertion is `invalid_client`, as it always was. + const refused = await w.refresh(VERIFIED, "rt_x"); + assert.deepEqual([refused.status, refused.body.error], [401, "invalid_client"]); +}); + +test("the settings are checked", () => { + const config = (changes) => new CompanyConfig({ ...CONFIG_OPTIONS, ...changes }); + assert.throws(() => config({ publicClients: true, direct: false, ucp: false }), /direct/); + assert.throws(() => config({ clientRegistration: true }), /publicClients is on/); + assert.throws(() => config({ publicClients: true, pushedAuthorizationRequests: "required" }), /push/); + assert.throws(() => config({ publicClients: true, publicClientScopes: ["poppy:browser-sign-in"] }), /publicClientScopes/); + assert.throws(() => config({ publicClients: true, publicClientScopes: [] }), /publicClientScopes/); + assert.throws(() => config({ publicClientRefreshLifetimeSeconds: 0 }), /positive/); + assert.throws(() => config({ clientRegistrationsPerHour: 0 }), /at least 1/); +}); + +test("on, the issuer says so", async () => { + const w = await world(); + const metadata = w.shop.oauthMetadata(); + assert.deepEqual(metadata.token_endpoint_auth_methods_supported, ["private_key_jwt", "none"]); + assert.equal(metadata.registration_endpoint, `${SHOP}/oauth/register`); + assert.equal(metadata.authorization_response_iss_parameter_supported, true); + assert.deepEqual(metadata.code_challenge_methods_supported, ["S256"]); + // Public clients without registration: `none`, and no endpoint to register at. + const without = await world({ clientRegistration: false }); + assert.ok(without.shop.oauthMetadata().token_endpoint_auth_methods_supported.includes("none")); + assert.ok(!("registration_endpoint" in without.shop.oauthMetadata())); + assert.equal((await without.register()).status, 404); +}); + +// The two ways to be a public client --------------------------------------------------------- + +test("a client verified by its domain signs in and calls the MCP server", async () => { + const w = await world(); + const shown = await w.authorize(VERIFIED, VERIFIED_REDIRECT); + const requestId = requestIdOf(shown); + // The page is never framed, and says where the browser goes back to. + assert.equal(shown.headers["X-Frame-Options"], "DENY"); + assert.match(shown.headers["Content-Security-Policy"], /frame-ancestors 'none'/); + assert.match(shown.body, /client\.example<\/strong>/); + assert.doesNotMatch(shown.body, /Unverified/); + assert.match(shown.body, /Only continue if you asked Deskmate to do this just now\./); + + const summary = await w.shop.authorizationRequest(requestId); + assert.equal(summary.client_class, "public_client"); + assert.equal(summary.verified, true); + assert.equal(summary.client_name, "Deskmate"); + assert.equal(summary.client_domain, "client.example"); + assert.equal(summary.redirect_host, "client.example"); + assert.equal(summary.resource, MCP); + assert.ok(!("state" in summary) && !("code_challenge" in summary)); + + const back = new URL(await w.shop.approveAuthorization(requestId, { accountId: "acct_ada" })); + // The answer names the issuer and gives the state back (RFC 9207, RFC 6749 §4.1.2). + assert.equal(`${back.origin}${back.pathname}`, VERIFIED_REDIRECT); + assert.equal(back.searchParams.get("iss"), SHOP); + assert.equal(back.searchParams.get("state"), "st-1"); + + const answer = await w.token({ + grant_type: "authorization_code", + client_id: VERIFIED, + code: back.searchParams.get("code"), + redirect_uri: VERIFIED_REDIRECT, + code_verifier: VERIFIER, + resource: MCP, + }); + assert.equal(answer.status, 200, JSON.stringify(answer.body)); + assert.equal(answer.body.token_type, "Bearer"); + assert.ok(answer.body.refresh_token && answer.body.access_token); + assert.equal(answer.headers["Cache-Control"], "no-store"); + + // At the MCP server: its token alone, and no Session header. + const listed = await w.mcp(answer.body.access_token, LIST_TOOLS); + assert.equal(listed.status, 200); + assert.ok(listed.body.result.tools.length > 0); + const called = await w.mcp(answer.body.access_token, { + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { name: "list_orders" }, + }); + assert.equal(called.status, 200); + assert.ok(!("isError" in called.body.result)); +}); + +test("a client that registered itself is shown as unverified", async () => { + const w = await world(); + const clientId = await w.registered(); + assert.match(clientId, /^mcpc_[A-Za-z0-9_-]{22}$/); + const shown = await w.authorize(clientId, "http://127.0.0.1:49152/callback", { resource: ELSEWHERE }); + assert.match(shown.body, /Unverified app\./); + assert.match(shown.body, /127\.0\.0\.1:49152<\/strong>/); + const summary = await w.shop.authorizationRequest(requestIdOf(shown)); + assert.equal(summary.client_class, "public_client"); + assert.equal(summary.verified, false); + assert.equal(summary.client_domain, ""); + assert.equal(summary.redirect_host, "127.0.0.1:49152"); + assert.equal(summary.resource, ELSEWHERE); + + const tokens = await w.signIn(clientId, "http://127.0.0.1:49152/callback", { resource: ELSEWHERE }); + // The service at a URL of its own reads the token's record, which says whose it is. + const record = await w.shop.accessTokenFor(tokens.access_token, ELSEWHERE); + assert.equal(record.public, true); + assert.deepEqual([record.clientId, record.accountId], [clientId, "acct_ada"]); + assert.deepEqual(record.scopes, ["orders:read"]); + assert.equal(record.dpopJkt, undefined); + // Issued for that service, it is nothing at the company's own MCP server. + assert.equal((await w.mcp(tokens.access_token, LIST_TOOLS)).status, 401); +}); + +test("a personal agent's request says its class too", async () => { + const w = await world(); + const shown = await w.authorize(w.identity.clientId, "https://atlas.example/oauth/callback", { resource: null }); + const summary = await w.shop.authorizationRequest(requestIdOf(shown)); + assert.equal(summary.client_class, "personal_agent"); + assert.equal(summary.verified, true); + assert.equal(summary.redirect_host, "atlas.example"); + assert.ok(!("resource" in summary)); +}); + +// The protocol's boundaries -------------------------------------------------------------------- + +test("a public client's token is refused at every endpoint of the protocol", async () => { + const w = await world(); + const agent = await personalAgent(w); + const clientId = await w.registered(); + const tokens = await w.signIn(clientId, LOOPBACK, { scope: "orders:read orders:write" }); + const endpoints = [ + ["POST", "/poppy/conversations", '{"message": {"text": "Hello"}}'], + ["GET", "/poppy/conversations/conv_1", undefined], + ["POST", "/poppy/operations", "{}"], + ["GET", "/poppy/tasks", undefined], + ["POST", "/poppy/feedback", '{"task": "Pay with a gift card"}'], + ["POST", "/poppy/browser-session/authorize", "{}"], + ["GET", "/api/orders", undefined], + ]; + const borrowedToken = { accessToken: new SecretValue(tokens.access_token), tokenType: "Bearer" }; + for (const [method, path, body] of endpoints) { + // Alone, as a public client sends it: there is no Session, so nothing is served. + const alone = await w.call(method, path, { + raw: body, + headers: { authorization: `Bearer ${tokens.access_token}`, "content-type": "application/json" }, + }); + assert.ok([400, 401].includes(alone.status), `${path} ${alone.status}`); + assert.ok(["invalid_session", "invalid_token"].includes(alone.body.error), `${path} ${alone.body.error}`); + // In a personal agent's Session: a public client's token signs no Session in. + const borrowed = await agent.transport.request(method, `${SHOP}${path}`, { + session: agent.session, + token: borrowedToken, + headers: { "content-type": "application/json" }, + ...(body === undefined ? {} : { body }), + }); + assert.ok([400, 401].includes(borrowed.status), `${path} ${borrowed.status}`); + assert.ok(["invalid_session", "invalid_token"].includes((await borrowed.json()).error), path); + } + // The same at the MCP server once a Session header comes with it. + const withSession = await agent.transport.request("POST", MCP, { + session: agent.session, + token: borrowedToken, + headers: { "content-type": "application/json" }, + body: JSON.stringify(LIST_TOOLS), + }); + assert.equal(withSession.status, 401); + // And no Session was started for the client, signed in or out. + const sessions = await w.shop.store.records("session"); + assert.ok(sessions.every((record) => record.value.clientId !== clientId)); +}); + +test("a public client never gets the default token", async () => { + const w = await world(); + const clientId = await w.registered(); + for (const resource of [null, SHOP, `${SHOP}/poppy/conversations`, "https://other.example/mcp"]) { + assert.ok(refusedPage(await w.authorize(clientId, LOOPBACK, { resource })), String(resource)); + } + const code = await w.codeFor(clientId, LOOPBACK); + const form = { + grant_type: "authorization_code", + client_id: clientId, + code, + redirect_uri: LOOPBACK, + code_verifier: VERIFIER, + }; + // No `resource`, the default token's, or a service it was not asked for: nothing. + assert.equal((await w.token(form)).body.error, "invalid_target"); + assert.equal((await w.token({ ...form, resource: SHOP })).body.error, "invalid_target"); + assert.equal((await w.token({ ...form, resource: ELSEWHERE })).body.error, "invalid_target"); + // The code named the MCP server: asked for another service, it is spent and gives nothing. + assert.equal((await w.token({ ...form, resource: MCP })).body.error, "invalid_grant"); + + const tokens = await w.signIn(clientId); + assert.equal((await w.refresh(clientId, tokens.refresh_token, { resource: SHOP })).body.error, "invalid_target"); + assert.equal( + (await w.refresh(clientId, tokens.refresh_token, { resource: ELSEWHERE })).body.error, + "invalid_target", + ); + // A token for the MCP server is nothing at the other service. + assert.equal(await w.shop.accessTokenFor(tokens.access_token, ELSEWHERE), undefined); +}); + +test("a public client gets only its own grants and scopes", async () => { + const w = await world(); + const clientId = await w.registered(); + // `poppy:browser-sign-in` is a personal agent's: never asked, never granted. + assert.ok(refusedPage(await w.authorize(clientId, LOOPBACK, { scope: "orders:read poppy:browser-sign-in" }))); + // The device and mediated grants are a personal agent's. + for (const grant of [ + "urn:ietf:params:oauth:grant-type:device_code", + "urn:poppy:params:oauth:grant-type:mediated", + "client_credentials", + ]) { + const refused = await w.token({ grant_type: grant, client_id: clientId, resource: MCP }); + assert.equal(refused.status, 400); + assert.ok(["unauthorized_client", "unsupported_grant_type"].includes(refused.body.error)); + } + const device = await w.call("POST", "/oauth/device", { form: { client_id: clientId, scope: "orders:read" } }); + assert.deepEqual([device.status, device.body.error], [401, "invalid_client"]); + + const narrowed = await world({ publicClientScopes: ["orders:read"] }); + const narrowClient = await narrowed.registered(); + assert.ok(refusedPage(await narrowed.authorize(narrowClient, LOOPBACK, { scope: "orders:read orders:write" }))); + assert.equal((await narrowed.authorize(narrowClient, LOOPBACK)).status, 200); +}); + +test("a public client approves no operation", async () => { + const w = await world(); + const clientId = await w.registered(); + const tokens = await w.signIn(clientId, LOOPBACK, { scope: "orders:read orders:write" }); + const called = await w.mcp(tokens.access_token, { + jsonrpc: "2.0", + id: 3, + method: "tools/call", + params: { + name: "exchange_jacket", + arguments: {}, + // An approval a personal agent would send: read from no public client. + _meta: { "poppy/approval": { operation_id: "op_1", revision: 1 } }, + }, + }); + const result = called.body.result; + assert.equal(result.isError, true); + assert.ok(!("structuredContent" in result)); + assert.match(result.content[0].text, /personal agent/); + assert.deepEqual(await w.shop.store.records("operation"), []); +}); + +test("a personal agent cannot become a public client", async () => { + // Its assertion is never skipped: its sign-ins, codes and document stay its own. + const w = await world(); + const agent = await personalAgent(w, { signIn: true }); + const kept = agent.host.tokens.get(agent.reference); + const agentRefresh = typeof kept === "string" ? kept : kept.reveal(); + const clientId = await w.registered(); + + // Its own `client_id`, no assertion: its document names its keys, so it is no public client. + const bare = await w.refresh(w.identity.clientId, agentRefresh); + assert.deepEqual([bare.status, bare.body.error], [401, "invalid_client"]); + // Its refresh token under a public client's `client_id`: not that class of sign-in. + const borrowed = await w.refresh(clientId, agentRefresh); + assert.deepEqual([borrowed.status, borrowed.body.error], [400, "invalid_grant"]); + // Neither attempt ended its sign-in: it refreshes as before. + assert.ok((await agent.refreshed()).token); + + // Its authorization code is exchanged with its assertion only. + const shown = await w.authorize(w.identity.clientId, "https://atlas.example/oauth/callback", { resource: null }); + const back = await w.shop.approveAuthorization(requestIdOf(shown), { accountId: "acct_ada" }); + const agentCode = new URL(back).searchParams.get("code"); + for (const claimed of [w.identity.clientId, clientId]) { + const refused = await w.token({ + grant_type: "authorization_code", + client_id: claimed, + code: agentCode, + redirect_uri: "https://atlas.example/oauth/callback", + code_verifier: VERIFIER, + resource: MCP, + }); + assert.ok([400, 401].includes(refused.status)); + assert.ok(["invalid_client", "invalid_grant"].includes(refused.body.error)); + } + + // Someone who only intercepted the code and posts it without an assertion gets nothing, and + // spent it: the agent's own exchange finds it used. + const owned = await w.token({ + grant_type: "authorization_code", + code: agentCode, + redirect_uri: "https://atlas.example/oauth/callback", + code_verifier: VERIFIER, + ...(await agent.sessions.clientAuthentication({ clientId: w.identity.clientId, issuer: SHOP })), + }); + assert.deepEqual([owned.status, owned.body.error], [400, "invalid_grant"]); + + // And a public client's code is nothing to a personal agent with a valid assertion. + const publicCode = await w.codeFor(clientId, LOOPBACK); + const crossed = await w.token({ + grant_type: "authorization_code", + code: publicCode, + redirect_uri: LOOPBACK, + code_verifier: VERIFIER, + ...(await agent.sessions.clientAuthentication({ clientId: w.identity.clientId, issuer: SHOP })), + }); + assert.deepEqual([crossed.status, crossed.body.error], [400, "invalid_grant"]); +}); + +test("a document is one class of client and never both", async () => { + const both = document({ jwks_uri: "https://client.example/jwks.json" }); + assert.throws(() => parsePublicClientMetadata(both)); + assert.throws(() => parsePublicClientMetadata(document({ token_endpoint_auth_method: "private_key_jwt" }))); + // Said, never assumed: a document that leaves the method out is no public client's. + const { token_endpoint_auth_method: _method, ...silent } = document(); + assert.throws(() => parsePublicClientMetadata(silent)); + assert.throws(() => parsePublicClientMetadata(document({ client_secret: "s3cret" }))); + assert.throws(() => parsePublicClientMetadata(document({ grant_types: ["client_credentials"] }))); + assert.throws(() => parsePublicClientMetadata(document({ client_name: "ab" }))); + const w = await world({ site: both }); + assert.ok(refusedPage(await w.authorize(VERIFIED, VERIFIED_REDIRECT))); + + // A redirect on another host than the document's is never matched; loopback is. + const plain = await world(); + assert.ok(refusedPage(await plain.authorize(VERIFIED, "https://elsewhere.example/callback"))); + assert.equal((await plain.authorize(VERIFIED, "http://127.0.0.1:8123/callback")).status, 200); +}); + +test("a document at a private address is never fetched", async () => { + const fetched = []; + const fetch = async (input) => { + fetched.push(String(input)); + return new Response(JSON.stringify(document()), { headers: { "content-type": "application/json" } }); + }; + // The portable check refuses what a URL says of itself; where a name resolves is the + // company's transport's to check on Node (`createResolvingFetch`), or the host's policy. + const refusing = new AgentIdentityClient({ + fetch, + assertSafeUrl: () => { + throw new DiscoveryError("unsafe_address", "resolves to a private address"); + }, + }); + await assert.rejects(refusing.fetchPublicMetadata(VERIFIED)); + const identity = new AgentIdentityClient({ fetch }); + for (const literal of [ + "https://127.0.0.1/client.json", + "https://169.254.169.254/latest/meta-data", + "https://[::1]/client.json", + "https://10.0.0.7/client.json", + "https://localhost/client.json", + "https://client.internal/client.json", + "http://client.example/oauth/client.json", + ]) { + await assert.rejects(identity.fetchPublicMetadata(literal), literal); + } + assert.deepEqual(fetched, []); +}); + +test("a document that redirects or names another URL is refused", async () => { + const redirecting = async () => new Response(null, { status: 302, headers: { location: "https://10.0.0.7/c.json" } }); + const another = async () => + new Response(JSON.stringify(document({ client_id: "https://other.example/client.json" })), { + headers: { "content-type": "application/json" }, + }); + for (const fetch of [redirecting, another]) { + const identity = new AgentIdentityClient({ fetch }); + await assert.rejects(identity.fetchPublicMetadata(VERIFIED)); + } +}); + +// PKCE, codes, redirects ----------------------------------------------------------------------- + +test("PKCE is the only proof and is never skipped", async () => { + const w = await world(); + const clientId = await w.registered(); + for (const changes of [ + { code_challenge: null }, + { code_challenge_method: null }, + { code_challenge_method: "plain" }, + { code_challenge: "short" }, + { response_type: "token" }, + ]) { + // An unverified client is answered a page, never a redirect. + assert.ok(refusedPage(await w.authorize(clientId, LOOPBACK, changes)), JSON.stringify(changes)); + } + const form = { grant_type: "authorization_code", client_id: clientId, redirect_uri: LOOPBACK, resource: MCP }; + for (const verifier of [undefined, "", "w".repeat(43), "v".repeat(42), "v".repeat(129), `${"v".repeat(42)}!`]) { + const code = await w.codeFor(clientId, LOOPBACK); + const refused = await w.token({ ...form, code, ...(verifier === undefined ? {} : { code_verifier: verifier }) }); + assert.deepEqual([refused.status, refused.body.error], [400, "invalid_grant"], String(verifier)); + // A refused exchange spent the code: the right verifier gets nothing after it. + assert.equal((await w.token({ ...form, code, code_verifier: VERIFIER })).body.error, "invalid_grant"); + } + // A code is the client's it was issued to, for the redirect it was issued for, once. + const other = await w.registered({ client_name: "Another" }); + let code = await w.codeFor(clientId, LOOPBACK); + assert.equal( + (await w.token({ ...form, client_id: other, code, code_verifier: VERIFIER })).body.error, + "invalid_grant", + ); + code = await w.codeFor(clientId, LOOPBACK); + const moved = await w.token({ ...form, code, code_verifier: VERIFIER, redirect_uri: "http://127.0.0.1:1/callback" }); + assert.equal(moved.body.error, "invalid_grant"); + code = await w.codeFor(clientId, LOOPBACK); + assert.equal((await w.token({ ...form, code, code_verifier: VERIFIER })).status, 200); + assert.equal((await w.token({ ...form, code, code_verifier: VERIFIER })).body.error, "invalid_grant"); +}); + +test("a redirect URI is loopback or HTTPS and nothing else", () => { + for (const accepted of [ + "https://client.example/callback", + "https://client.example:8443/callback?tenant=1", + "https://xn--bcher-kva.example/cb", + "http://127.0.0.1/callback", + "http://127.0.0.1:53211/callback", + "http://[::1]:53211/callback", + "http://localhost:53211/callback", + ]) { + assert.equal(publicRedirectUri(accepted), accepted); + } + for (const refused of [ + "", + "HTTPS://client.example/callback", + "https:/client.example/callback", + "https://client.example.:443/callback", + "http://client.example/callback", + "https://user@client.example/callback", + "https://user:pw@client.example/callback", + "https://client.example@evil.example/callback", + "https://client.example/callback#fragment", + "https://client.example/callback#", + "https://Client.example/callback", + "https://client.example\\@evil.example/callback", + "https://client.example /callback", + "https://client.example/call\tback", + "https://client.example/call\nback", + "https:///callback", + "https://client.example:0/callback", + "https://client.example:70000/callback", + "https://[::1]/callback", + "https://bücher.example/cb", + "http://127.0.0.1.evil.example/callback", + "http://127.0.0.1:80@evil.example/callback", + "http://localhost.evil.example/callback", + "http://127.1/callback", + "http://2130706433/callback", + "http://0.0.0.0/callback", + "http://10.0.0.1/callback", + "http://localhost:99999/callback", + "cursor://callback", + "javascript:alert(1)", + "data:text/html,x", + "//client.example/callback", + `https://client.example/${"a".repeat(2000)}`, + 7, + undefined, + ]) { + assert.throws(() => publicRedirectUri(refused), RangeError, String(refused)); + } + assert.ok(isPublicLoopbackRedirect("http://localhost/cb")); + assert.ok(!isPublicLoopbackRedirect("https://localhost/cb")); +}); + +test("a redirect URI matches exactly but for a loopback port", () => { + const https = "https://client.example/callback"; + assert.ok(publicRedirectUriMatches(https, https)); + for (const other of [ + "https://client.example/callback/", + "https://client.example/callback?next=https://evil.example", + "https://client.example/callback/../evil", + "https://client.example:8443/callback", + "https://client.example/Callback", + "https://client.example.evil.example/callback", + "https://evil.example/callback", + "https://client.example/callback#x", + "https://client.example/callback%2f..", + ]) { + assert.ok(!publicRedirectUriMatches(https, other), other); + } + const loopback = "http://127.0.0.1/callback"; + assert.ok(publicRedirectUriMatches(loopback, "http://127.0.0.1:53211/callback")); + for (const other of [ + "http://127.0.0.1:53211/other", + "http://127.0.0.1:53211/callback?x=1", + "http://localhost:53211/callback", + "http://[::1]:53211/callback", + "https://127.0.0.1:53211/callback", + "http://127.0.0.1:53211@evil.example/callback", + "http://127.0.0.1:99999/callback", + ]) { + assert.ok(!publicRedirectUriMatches(loopback, other), other); + } +}); + +test("a request with another redirect is never redirected", async () => { + const w = await world(); + const clientId = await w.registered({ redirect_uris: ["https://pocket.example/callback"] }); + for (const redirectUri of [ + "https://pocket.example/callback?next=https://evil.example", + "https://pocket.example/callback/..%2fevil", + "https://user@pocket.example/callback", + "https://pocket.example.evil.example/callback", + "https://pocket.example/callback#x", + "https://evil.example/callback", + "http://127.0.0.1/callback", + "", + ]) { + assert.ok(refusedPage(await w.authorize(clientId, redirectUri)), redirectUri); + } +}); + +test("an unverified client's errors are pages and a verified one's redirects", async () => { + // Anyone registers any HTTPS redirect: answered with no one's consent, an error would make + // the authorization endpoint an open redirector (RFC 9700 §4.11.2). + const w = await world(); + const clientId = await w.registered({ redirect_uris: ["https://pocket.example/callback"] }); + for (const changes of [{ scope: "nothing:here" }, { scope: "" }, { resource: SHOP }]) { + assert.ok( + refusedPage(await w.authorize(clientId, "https://pocket.example/callback", changes)), + JSON.stringify(changes), + ); + } + // A client verified by its domain is answered at its own domain, with state and issuer. + const answered = await w.authorize(VERIFIED, VERIFIED_REDIRECT, { scope: "nothing:here" }); + assert.equal(answered.status, 303); + const location = new URL(answered.headers.Location); + assert.equal(`${location.origin}${location.pathname}`, VERIFIED_REDIRECT); + assert.deepEqual(Object.fromEntries(location.searchParams), { + error: "invalid_scope", + state: "st-1", + iss: SHOP, + }); + // A refusal by the person reaches either, after they decided. + const shown = await w.authorize(clientId, "https://pocket.example/callback"); + const denied = new URL(await w.shop.denyAuthorization(requestIdOf(shown))); + assert.deepEqual(Object.fromEntries(denied.searchParams), { error: "access_denied", state: "st-1", iss: SHOP }); +}); + +test("a decision counts once and the name is shown as text", async () => { + const w = await world(); + const clientId = await w.registered({ client_name: "${agent} (${agentDomain}) asks to:
` + : `Unverified app. It calls itself ${agent}, ` + + "and nothing confirms that. It asks to:
"; + return page( + 200, + `Only continue if you asked ${agent} to do this just now.
` + + `${who}If you allow, your browser goes back to " + + `${escapeHtml(publicClient.redirectHost)}.
` + + `', + `${CONSENT_COOKIE}=${browser}; Path=/; Secure; HttpOnly; SameSite=Strict`, + ); + } // The heading names the agent and says it wants to connect, never "Sign in with", and the // page says to go on only if the person just asked it to (§10.8; guides, consent pages): // anyone can start a sign-in and send someone else the link. @@ -3088,6 +3829,35 @@ export class CompanyService { ); } + /** + * Who asks at the authorization endpoint, by its `client_id`; `undefined` when it can't be + * verified. + * + * A URL is a client ID metadata document: a personal agent's when it names its keys, and + * otherwise, with `publicClients`, a public client's when it says it authenticates with + * nothing. No document is both, so which class a client is of is its own domain's to say, and + * never the request's. Anything else is the `client_id` of a client that registered itself. + */ + async #authorizingClient(clientId: string): Promise