From a4c08261125ee05eed5f02311c30311c78f14d37 Mon Sep 17 00:00:00 2001 From: Eric Charles Date: Wed, 18 Nov 2026 10:40:04 +0100 Subject: [PATCH 1/4] =?UTF-8?q?0.37.3:=20a=20company's=20services=20at=20U?= =?UTF-8?q?RLs=20of=20their=20own=20(spec=203.2,=204.5,=207)=20=E2=80=94?= =?UTF-8?q?=20CompanyConfig.resource=5Fservers=20(resourceServers):=20an?= =?UTF-8?q?=20MCP=20server=20on=20another=20host=20than=20the=20issuer's?= =?UTF-8?q?=20is=20listed=20in=20the=20issuer's=20protected=5Fresources=20?= =?UTF-8?q?and=20gets=20Bearer=20tokens=20issued=20for=20it=20(RFC=208707)?= =?UTF-8?q?,=20at=20the=20request=20that=20completes=20a=20sign-in=20or=20?= =?UTF-8?q?at=20refresh,=20where=20it=20was=20invalid=5Ftarget;=20CompanyS?= =?UTF-8?q?ervice.access=5Ftoken=5Ffor=20(accessTokenFor)=20for=20such=20a?= =?UTF-8?q?=20service=20to=20verify=20a=20token=20issued=20for=20it,=20and?= =?UTF-8?q?=20only=20for=20it;=20resource=5Fmetadata=5Furl=20(resourceMeta?= =?UTF-8?q?dataUrl),=20where=20its=20RFC=209728=20metadata=20is.=20In=20bo?= =?UTF-8?q?th=20SDKs,=20additive:=20a=20company=20that=20names=20none=20be?= =?UTF-8?q?haves=20as=20before.=20Docs:=20guides/company,=20A=20service=20?= =?UTF-8?q?at=20a=20URL=20of=20its=20own.=20Tests:=20test=5Fresource=5Fser?= =?UTF-8?q?vers=20(14),=20resource-servers.test.mjs=20(5),=20a=20docs=20ex?= =?UTF-8?q?ample=20case?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 27 ++++ docs/docs/guides/company.mdx | 54 +++++++ docs/docs/protocol/conformance-report.mdx | 2 +- docs/docs/releases/compatibility.mdx | 3 +- package.json | 2 +- .../__tests__/test_docs_examples.py | 19 +++ .../__tests__/test_resource_servers.py | 153 ++++++++++++++++++ personal_agent_protocol/__version__.py | 2 +- personal_agent_protocol/company/__init__.py | 4 +- personal_agent_protocol/company/service.py | 68 ++++++++ personal_agent_protocol/reactor.py | 2 +- src/__tests__/resource-servers.test.mjs | 135 ++++++++++++++++ src/company/index.ts | 2 +- src/company/service.ts | 64 ++++++++ src/reactor.ts | 2 +- 15 files changed, 531 insertions(+), 8 deletions(-) create mode 100644 personal_agent_protocol/__tests__/test_resource_servers.py create mode 100644 src/__tests__/resource-servers.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 115974b..6be4b8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,33 @@ # Changelog +## 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 +names none behaves exactly as before. + +- **`resource_servers` (`resourceServers`) on `CompanyConfig`** (spec 3.2, 4.5, 7). The SDK's + company issued a token for one MCP `resource`, its own `https://{domain}/mcp`, and listed only + that in `protected_resources`. A company whose MCP server answers on another host than its + issuer's (`https://mcp.example.com/mcp`) had no way to offer it signed in: a Personal Agent + that asked for a token with `resource` set to the server's `url`, as section 7 requires, got + `invalid_target`. Each URL named here is listed in the issuer's `protected_resources` and gets + Bearer tokens issued for it, at the request that completes a sign-in or at refresh (RFC 8707), + subject to the client policy's `allows_resource` like every other service. A sign-in that + named no `resource` covers them, those added after it too (4.5). +- **`CompanyService.access_token_for(token, resource)` (`accessTokenFor`)**: for such a service + to verify what it is sent. The token's record when it was issued for that service, is + unexpired, its sign-in has not ended and its scopes are still offered; nothing otherwise, the + default token and a token for another service among them (4.5: a token issued for a + `resource` is accepted only at that service). The service enforces the record's `scopes`. +- **`resource_metadata_url(resource)` (`resourceMetadataUrl`)**: where a service's protected + resource metadata is (RFC 9728 §3.1), for the `resource_metadata` of its challenges (7). +- Each resource server is an HTTPS URL without query or fragment, its host in small letters, + named once, and not one of the company's own (`https://{domain}`, an alias, its `/mcp`, its + conversation endpoint); a company with no issuer has none. A service named here gets Bearer + tokens even from an issuer that binds its own with DPoP (7: a company whose MCP server + doesn't accept DPoP returns Bearer tokens for it). + ## 0.37.2 (2026-11-17) Fixes from the review of 0.37.1, and what a host needs to push a Direct Sign-In whose redirect diff --git a/docs/docs/guides/company.mdx b/docs/docs/guides/company.mdx index c0100fb..d4b8a2d 100644 --- a/docs/docs/guides/company.mdx +++ b/docs/docs/guides/company.mdx @@ -249,6 +249,10 @@ implements, of version 0.4 and Operations version 3: `resource`); the endpoint takes only those, answering the default token with `invalid_token` and `resource_metadata`, and a signed-out request with the Session header alone. Session JWT audiences and User IDs stay the company's; +- with `resource_servers` (`resourceServers`), the company's services at URLs of + their own, such as an MCP server on another host than the issuer's + (`https://mcp.example.com/mcp`): see [A service at a URL of its + own](#a-service-at-a-url-of-its-own); - Bearer access tokens, or tokens bound with DPoP (`dpop_binding`, in TypeScript `dpopBinding`: `off` by default, `optional` binds when a proof comes, `required` refuses a token request with none; `dpop_nonces`, `dpopNonces`, asks for server @@ -638,6 +642,56 @@ same issuer: one company, never a second identity. Every endpoint stays on `/.well-known/poppy.json` answers `404 not_found`. An alias is a DNS name in small letters, another than `domain`, named once. +### A service at a URL of its own + +The reference company serves its MCP server at `https://{domain}/mcp`, on the +issuer's own host. A company whose MCP server answers elsewhere, such as +`https://mcp.example.com/mcp` beside an issuer at `https://example.com`, names it +in `resource_servers` (`resourceServers`): + +```python +from personal_agent_protocol.company import resource_metadata_url + +config = CompanyConfig( + name="Example", + domain="example.com", + scopes=("orders:read",), + agent_description="Your orders", + scope_descriptions={"orders:read": "See your orders"}, + operations=False, + resource_servers=("https://mcp.example.com/mcp",), +) +print(resource_metadata_url(config.resource_servers[0])) +``` + +The URL is the server's `url` as `poppy.json` lists it in `apis`, since that is the +`resource` a Personal Agent asks a token for (§7). For each one: + +- the issuer's metadata lists it in `protected_resources`, after `https://{domain}` + (§3.2: it MAY list other resources, such as the Company's MCP servers); +- the token endpoint issues a token for it when a request names it as `resource`, + the request that completes a sign-in or a refresh (§4.5, RFC 8707). A sign-in that + named no `resource` covers it, a service added after the sign-in too. Any other + `resource` is still `invalid_target`, and the client policy's `allows_resource` + can leave a service out for an agent; +- the token is a Bearer token, even when the issuer binds its own with DPoP (§7: a + Company whose MCP server doesn't accept DPoP returns Bearer tokens for it). + +The service does its own half (§7). It publishes protected resource metadata whose +`resource` equals its `url` and whose `authorization_servers` includes the company's +issuer, at `resource_metadata_url(url)` (`resourceMetadataUrl`, RFC 9728 §3.1), which +the example prints. It verifies each token it is sent with +`await service.access_token_for(token, url)` (`accessTokenFor`), which answers the +token's record only when it was issued for that service, is unexpired, its sign-in +has not ended and its scopes are still offered. The default token and a token for +another service answer `None` (`undefined`): the Company accepts a token issued for +a `resource` only at that service (§4.5), and a service that gets a token not issued +for it returns `invalid_token` with `resource_metadata` in its challenge. The +record's `account_id`, `client_id` and `scopes` are what the service acts on, and it +enforces the scopes on every call. + +A company that names no resource server behaves as before. + ### 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 4cbb2e0..7fd34c7 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.2**, 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.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. ## Pairings diff --git a/docs/docs/releases/compatibility.mdx b/docs/docs/releases/compatibility.mdx index 7eb76a2..0cb0512 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.2**. +This page is versioned with the SDK: it describes **SDK 0.37.3**. ## The PAP version implemented @@ -35,6 +35,7 @@ profile, never picked up from an unattended fetch. | SDK (PyPI and npm) | PAP profile | Specification revision | Operations | Breaking changes | | --- | --- | --- | --- | --- | +| `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 | | `0.37.0` | `0.4` | 2026-11-10 | v3 | [0.36 → 0.37](/releases/migration/#036--037): 1.0 as published (`8c02b42`): required conversation protocol descriptions (`agent_description`), Pushed Authorization Requests, `prompt=consent`, refresh tokens bound to their DPoP key, ports in `organization.domain`, one sign-in for every resource, and unknown values read safely | diff --git a/package.json b/package.json index 58f799f..04064ca 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@datalayer/personal-agent-protocol", - "version": "0.37.2", + "version": "0.37.3", "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/__tests__/test_docs_examples.py b/personal_agent_protocol/__tests__/test_docs_examples.py index a3ca786..5edd6e2 100644 --- a/personal_agent_protocol/__tests__/test_docs_examples.py +++ b/personal_agent_protocol/__tests__/test_docs_examples.py @@ -788,6 +788,25 @@ async def check(namespace: dict[str, Any], out: str) -> None: return {"CompanyConfig": CompanyConfig}, check +@case("docs/docs/guides/company.mdx#4") +async def _resource_servers(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://mcp.example.com/.well-known/oauth-protected-resource/mcp" + async with httpx.AsyncClient() as http: + service = build_company(config, http_client=http) + assert service.oauth_metadata()["protected_resources"] == [ + "https://example.com", + "https://mcp.example.com/mcp", + ] + + return {"CompanyConfig": CompanyConfig}, check + + # CLI and extensions ----------------------------------------------------------------------- diff --git a/personal_agent_protocol/__tests__/test_resource_servers.py b/personal_agent_protocol/__tests__/test_resource_servers.py new file mode 100644 index 0000000..34ab7e0 --- /dev/null +++ b/personal_agent_protocol/__tests__/test_resource_servers.py @@ -0,0 +1,153 @@ +# Copyright (c) 2025-2026 Datalayer, Inc. +# +# BSD 3-Clause License + +"""A service of the company at a URL of its own: listed, issued for, verified (§4.5, §7).""" + +from __future__ import annotations + +import dataclasses + +import pytest + +from personal_agent_protocol.accounts import RefreshTokenClient +from personal_agent_protocol.company import CompanyConfig, resource_metadata_url +from personal_agent_protocol.demo.manzanita import CONFIG, manzanita +from personal_agent_protocol.errors import PersonalAgentProtocolError +from personal_agent_protocol.models import ProtectedResourceMetadata + +from .test_company_end_to_end import World +from .test_company_refusals import signed_in +from .test_mcp_and_web import MCP, context + +#: The company's MCP server on a host of its own. +ELSEWHERE = "https://mcp.manzanita.example/mcp" + + +def world_with(*servers: str, **options: object) -> World: + world = World() + world.shop, world.plugin = manzanita( + world.network, + world.clock, + config=dataclasses.replace(CONFIG, resource_servers=servers, **options), # type: ignore[arg-type] + ) + return world + + +async def token_for(world: World, resource: str): # type: ignore[no-untyped-def] + result = await RefreshTokenClient(reactor=world.reactor, http_client=world.http).token_for_mcp( + world.refresh_reference, # type: ignore[arg-type] + context=context(world), + server=ProtectedResourceMetadata(resource=resource), + ) + assert result.status == "signed_in" and result.token is not None + return result.token + + +def test_a_company_lists_none_unless_configured() -> None: + assert CONFIG.resource_servers == () + + +@pytest.mark.asyncio +async def test_without_any_the_issuer_lists_and_issues_as_before() -> None: + world = World() + await signed_in(world) + listed = world.company.oauth_metadata.protected_resources # type: ignore[union-attr] + assert ELSEWHERE not in listed + with pytest.raises(PersonalAgentProtocolError) as refused: + await token_for(world, ELSEWHERE) + assert refused.value.code == "invalid_target" + + +@pytest.mark.asyncio +async def test_the_issuer_lists_it_and_issues_a_bearer_token_for_it() -> None: + """§3.2: `protected_resources` MAY list the company's MCP servers. §4.5: a token + request names one `resource` and gets a token for that service; §7: the token's + `resource` is the MCP server's `url`.""" + + world = world_with(ELSEWHERE) + default = await signed_in(world) + listed = world.company.oauth_metadata.protected_resources # type: ignore[union-attr] + assert listed[0] == "https://manzanita.example" and ELSEWHERE in listed and MCP in listed + + token = await token_for(world, ELSEWHERE) + assert (token.resource, token.token_type) == (ELSEWHERE, "Bearer") + + issued = await world.shop.access_token_for(token.access_token.get_secret_value(), ELSEWHERE) + assert issued is not None + assert (issued.account_id, issued.client_id) == ("acct_ada", world.atlas.client_id) + assert set(issued.scopes) == {"orders:read", "orders:write"} + + # §4.5: the company accepts a token issued for a `resource` only at that service. + assert ( + await world.shop.access_token_for(default.access_token.get_secret_value(), ELSEWHERE) + is None + ) + own = await token_for(world, MCP) + assert await world.shop.access_token_for(own.access_token.get_secret_value(), ELSEWHERE) is None + assert await world.shop.access_token_for("invented", ELSEWHERE) is None + with pytest.raises(ValueError): + await world.shop.access_token_for( + token.access_token.get_secret_value(), "https://other.example/mcp" + ) + + +@pytest.mark.asyncio +async def test_a_token_stops_working_there_when_it_expires() -> None: + world = world_with(ELSEWHERE) + await signed_in(world) + token = await token_for(world, ELSEWHERE) + world.clock.advance(int(CONFIG.access_token_lifetime.total_seconds()) + 1) + assert ( + await world.shop.access_token_for(token.access_token.get_secret_value(), ELSEWHERE) is None + ) + + +@pytest.mark.asyncio +async def test_it_gets_bearer_tokens_from_an_issuer_that_binds_its_own() -> None: + """§7: a company whose MCP server doesn't accept DPoP returns Bearer tokens for it.""" + + world = world_with(ELSEWHERE, dpop_binding="optional") + await signed_in(world) + assert (await token_for(world, ELSEWHERE)).token_type == "Bearer" + + +def test_its_metadata_is_where_rfc_9728_puts_it() -> None: + assert resource_metadata_url(ELSEWHERE) == ( + "https://mcp.manzanita.example/.well-known/oauth-protected-resource/mcp" + ) + assert resource_metadata_url("https://mcp.manzanita.example") == ( + "https://mcp.manzanita.example/.well-known/oauth-protected-resource" + ) + + +@pytest.mark.parametrize( + "servers", + [ + ("http://mcp.manzanita.example/mcp",), + ("https://mcp.manzanita.example/mcp?x=1",), + ("https://mcp.manzanita.example/mcp#x",), + ("https://MCP.manzanita.example/mcp",), + ("https://manzanita.example",), + ("https://manzanita.example/mcp",), + (ELSEWHERE, ELSEWHERE), + ], +) +def test_each_is_an_https_url_of_its_own_named_once(servers: tuple[str, ...]) -> None: + with pytest.raises(ValueError): + dataclasses.replace(CONFIG, resource_servers=servers) + + +def test_a_company_with_no_issuer_has_none() -> None: + with pytest.raises(ValueError): + CompanyConfig( + name="Open", + domain="open.example", + scopes=(), + agent_description="Anything", + oauth=False, + device=False, + direct=False, + operations=False, + resource_servers=(ELSEWHERE,), + ) diff --git a/personal_agent_protocol/__version__.py b/personal_agent_protocol/__version__.py index ab62c43..d47d673 100644 --- a/personal_agent_protocol/__version__.py +++ b/personal_agent_protocol/__version__.py @@ -7,4 +7,4 @@ """Personal Agent Protocol.""" -__version__ = "0.37.2" +__version__ = "0.37.3" diff --git a/personal_agent_protocol/company/__init__.py b/personal_agent_protocol/company/__init__.py index 32a1c07..625b89c 100644 --- a/personal_agent_protocol/company/__init__.py +++ b/personal_agent_protocol/company/__init__.py @@ -84,6 +84,7 @@ ConsentDecision, OpenWork, StaleConversationError, + resource_metadata_url, ) from .store import RECORD_KINDS, StoredRecord from .verify import verify_assertion @@ -182,7 +183,7 @@ def build_company( reactor.register_plugin( PluginManifest( name="personal-agent-protocol.company", - version="0.37.2", + version="0.37.3", contribution_points=[ COMPANY_STORES.id, COMPANY_ACCOUNTS.id, @@ -272,5 +273,6 @@ def build_company( "WebResult", "build_company", "company_app", + "resource_metadata_url", "verify_assertion", ] diff --git a/personal_agent_protocol/company/service.py b/personal_agent_protocol/company/service.py index bc89cc5..3d9cc73 100644 --- a/personal_agent_protocol/company/service.py +++ b/personal_agent_protocol/company/service.py @@ -357,6 +357,39 @@ class ConsentDecision: allow: bool +def resource_metadata_url(resource: str) -> str: + """Where a service's protected resource metadata is (RFC 9728 §3.1): the well-known + path between its host and its own path.""" + + parts = urlsplit(resource) + path = "" if parts.path in ("", "/") else parts.path + return f"{parts.scheme}://{parts.netloc}/.well-known/oauth-protected-resource{path}" + + +def _check_resource_servers(config: CompanyConfig) -> None: + """Each of `resource_servers` is an HTTPS URL of its own, named once (§4.5).""" + + servers = config.resource_servers + if not servers: + return + if not config.oauth: + raise ValueError( + "resource_servers take the issuer's tokens: a company with no issuer has none" + ) + own = {f"https://{domain}" for domain in (config.domain, *config.aliases)} + own |= {f"https://{config.domain}/mcp", f"https://{config.domain}/poppy/conversations"} + for server in servers: + parts = urlsplit(server) + if parts.scheme != "https" or not parts.netloc or parts.query or parts.fragment: + raise ValueError("a resource server is an HTTPS URL, without query or fragment") + if parts.netloc != parts.netloc.lower(): + raise ValueError("a resource server's host is in small letters") + if server in own: + raise ValueError("a resource server is another service than the company's own") + if len(set(servers)) != len(servers): + raise ValueError("each resource server is named once") + + def _check_aliases(domain: str, aliases: tuple[str, ...]) -> None: """Each alias a DNS name in small letters, another than `domain`, named once.""" for alias in aliases: @@ -475,6 +508,13 @@ class CompanyConfig: #: metadata naming itself as `resource`, with this company's issuer, the issuer lists #: it in `protected_resources` and issues tokens for it, and it takes only those. conversation_resource: bool = False + #: Services of this company at URLs of their own that take its access tokens (§4.5, §7): + #: an MCP server on another host than the issuer's, each named by its `url` as + #: `poppy.json` lists it. The issuer lists each in `protected_resources` (§3.2) and + #: issues Bearer tokens for it, at the request that completes a sign-in or at refresh + #: (RFC 8707); each publishes its own protected resource metadata naming this issuer, + #: and takes only the tokens issued for it (`CompanyService.access_token_for`). + resource_servers: tuple[str, ...] = () web: bool = False #: Whether the website returns operations to a joined browser (Operations 2, 4): the #: `operations` entry lists `endpoint` (`/poppy/operations`), beside the browser-session @@ -552,6 +592,7 @@ class CompanyConfig: def __post_init__(self) -> None: # noqa: C901 - one branch per protocol rule _check_aliases(self.domain, self.aliases) + _check_resource_servers(self) if not self.protocol_versions or len(set(self.protocol_versions)) != len( self.protocol_versions ): @@ -1784,6 +1825,7 @@ def oauth_metadata(self) -> dict[str, Any]: metadata["protected_resources"].append(config.mcp_url) if config.conversation_resource: metadata["protected_resources"].append(config.conversations_endpoint) + metadata["protected_resources"].extend(config.resource_servers) if config.direct: grants.append(AUTHORIZATION_CODE_GRANT) metadata["authorization_endpoint"] = config.authorization_endpoint @@ -2033,6 +2075,8 @@ def _resource(self, form: Mapping[str, str]) -> str | None: return resource if self.config.conversation_resource and resource == self.config.conversations_endpoint: return resource + if resource in self.config.resource_servers: + return resource raise _RefusedError(400, "invalid_target") def _account_scopes(self) -> tuple[str, ...]: @@ -2580,6 +2624,9 @@ def _takes_dpop(self, resource: str) -> bool: if self._mcp() is not None and resource == self.config.mcp_url: listed = self.protected_resource_metadata().get("dpop_signing_alg_values_supported") return DPOP_ALGORITHM in (listed or ()) + if resource in self.config.resource_servers: + # A service of its own verifies no proof here: it gets Bearer tokens (§7). + return False return True async def _access_token(self, token: str) -> IssuedAccessToken | None: @@ -2597,6 +2644,25 @@ async def _access_token(self, token: str) -> IssuedAccessToken | None: return None return issued + async def access_token_for(self, token: str, resource: str) -> IssuedAccessToken | None: + """The record of an access token presented at one of `resource_servers`, or `None`. + + For the service at `resource` to verify what it is sent (§4.5, §7): the token + was issued here **for that service**, is unexpired, its sign-in has not ended, + and every scope it holds is still offered. A token for another resource, the + 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. + """ + + if resource not in self.config.resource_servers: + raise ValueError(f"{resource} is not one of this company's resource_servers") + issued = await self._access_token(token) + if issued is None or issued.resource != resource or not self._offers(issued.scopes): + return None + return issued + async def _signed_out_before(self, account_id: str) -> datetime | None: accounts = optional_contribution(self.reactor, COMPANY_ACCOUNTS, "accounts") if not isinstance(accounts, AccountSignOuts): @@ -3305,6 +3371,8 @@ def _resource_metadata_url(self, resource: str | None) -> str: return self.config.mcp_resource_metadata if resource == self.config.conversations_endpoint: return self.config.conversation_resource_metadata + if resource in self.config.resource_servers: + return resource_metadata_url(resource) return f"{self.config.base}/.well-known/oauth-protected-resource" async def _session(self, verified: Any) -> str: diff --git a/personal_agent_protocol/reactor.py b/personal_agent_protocol/reactor.py index 8cf48f0..f9dd2fc 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.2", + version="0.37.3", contribution_points=[ DISCOVERY_TRANSPORTS.id, URL_SAFETY_POLICIES.id, diff --git a/src/__tests__/resource-servers.test.mjs b/src/__tests__/resource-servers.test.mjs new file mode 100644 index 0000000..b49f8e4 --- /dev/null +++ b/src/__tests__/resource-servers.test.mjs @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2025-2026 Datalayer, Inc. + * + * BSD 3-Clause License + */ + +// A service of the company at a URL of its own: listed, issued for, verified (§4.5, §7). +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + DeviceSignInClient, + RefreshTokenClient, + SessionClient, + discoverCompany, + negotiateExtensions, + parseProtectedResourceMetadata, +} from "../../lib/index.js"; +import { CompanyConfig, resourceMetadataUrl } from "../../lib/server.js"; +import { 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 MCP = "https://manzanita.example/mcp"; +/** The company's MCP server on a host of its own. */ +const ELSEWHERE = "https://mcp.manzanita.example/mcp"; + +/** Ada signed in at Manzanita by Device Sign-In, the company configured with `config`. */ +async function signedInWorld(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; + const { service: shop } = manzanita({ fetch, clock, ...(config === undefined ? {} : { config }) }); + sites["manzanita.example"] = shop; + const host = await agentHost({ identity, fetch, clock }); + const reactor = host.reactor; + const company = await discoverCompany("manzanita.example", { reactor }); + const metadata = company.oauthMetadata; + await new SessionClient({ reactor, fetch }).start({ + clientId: identity.clientId, + pairwiseUserId: PAIRWISE, + issuer: metadata.issuer, + tenantId: TENANT, + extensions: negotiateExtensions(company.document.extensions, identity.supportedExtensions), + }); + const device = new DeviceSignInClient({ reactor, fetch }); + const started = await device.begin({ + deviceAuthorizationEndpoint: metadata.device_authorization_endpoint, + tokenEndpoint: metadata.token_endpoint, + issuer: metadata.issuer, + clientId: identity.clientId, + scopes: ["orders:read", "orders:write"], + tenantId: TENANT, + organization: company.document.organization, + }); + await shop.approveDevice(started.userCode, { accountId: "acct_ada" }); + 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: identity.clientId, + tenantId: TENANT, + }; + const accounts = new RefreshTokenClient({ reactor, fetch }); + const tokenFor = (resource) => + accounts.tokenForMcp(done.refreshTokenReference, { context, server: parseProtectedResourceMetadata({ resource }) }); + return { clock, shop, identity, metadata, token: done.token, tokenFor }; +} + +test("without any, the issuer lists and issues as before", async () => { + const w = await signedInWorld(); + assert.deepEqual(w.shop.config.resourceServers, []); + assert.ok(!w.metadata.protected_resources.includes(ELSEWHERE)); + const refused = await w.tokenFor(ELSEWHERE).catch((error) => error); + assert.equal(refused.code, "invalid_target"); +}); + +test("the issuer lists it and issues a Bearer token for it, which only it takes", async () => { + // §3.2: `protected_resources` MAY list the company's MCP servers. §4.5: a token request names + // one `resource` and gets a token for that service; §7: the token's `resource` is the MCP + // server's `url`, and the company accepts it only there. + const w = await signedInWorld({ resourceServers: [ELSEWHERE] }); + const listed = w.metadata.protected_resources; + assert.equal(listed[0], "https://manzanita.example"); + assert.ok(listed.includes(ELSEWHERE) && listed.includes(MCP)); + + const { token } = await w.tokenFor(ELSEWHERE); + assert.deepEqual([token.resource, token.tokenType], [ELSEWHERE, "Bearer"]); + const issued = await w.shop.accessTokenFor(token.accessToken.reveal(), ELSEWHERE); + assert.deepEqual([issued.accountId, issued.clientId], ["acct_ada", w.identity.clientId]); + assert.deepEqual([...issued.scopes].sort(), ["orders:read", "orders:write"]); + + assert.equal(await w.shop.accessTokenFor(w.token.accessToken.reveal(), ELSEWHERE), undefined); + const own = (await w.tokenFor(MCP)).token; + assert.equal(await w.shop.accessTokenFor(own.accessToken.reveal(), ELSEWHERE), undefined); + assert.equal(await w.shop.accessTokenFor("invented", ELSEWHERE), undefined); + await assert.rejects(w.shop.accessTokenFor(token.accessToken.reveal(), "https://other.example/mcp"), RangeError); + + // It stops working there when it expires. + w.clock.advance(w.shop.config.accessTokenLifetimeSeconds + 1); + assert.equal(await w.shop.accessTokenFor(token.accessToken.reveal(), ELSEWHERE), undefined); +}); + +test("it gets Bearer tokens from an issuer that binds its own", async () => { + // §7: a company whose MCP server doesn't accept DPoP returns Bearer tokens for it. + const w = await signedInWorld({ resourceServers: [ELSEWHERE], dpopBinding: "optional" }); + assert.equal((await w.tokenFor(ELSEWHERE)).token.tokenType, "Bearer"); +}); + +test("its metadata is where RFC 9728 puts it", () => { + assert.equal(resourceMetadataUrl(ELSEWHERE), "https://mcp.manzanita.example/.well-known/oauth-protected-resource/mcp"); + assert.equal(resourceMetadataUrl("https://mcp.manzanita.example"), "https://mcp.manzanita.example/.well-known/oauth-protected-resource"); +}); + +test("each is an HTTPS URL of its own, named once, of a company with an issuer", () => { + const base = { name: "Shop", domain: "shop.example", scopes: ["orders:read"], agentDescription: "Orders", scopeDescriptions: { "orders:read": "Read orders" }, operations: false }; + assert.deepEqual(new CompanyConfig({ ...base, resourceServers: [ELSEWHERE] }).resourceServers, [ELSEWHERE]); + for (const resourceServers of [ + ["http://mcp.shop.example/mcp"], + ["https://mcp.shop.example/mcp?x=1"], + ["https://mcp.shop.example/mcp#x"], + ["https://MCP.shop.example/mcp"], + ["https://shop.example"], + ["https://shop.example/mcp"], + [ELSEWHERE, ELSEWHERE], + ]) { + assert.throws(() => new CompanyConfig({ ...base, resourceServers }), RangeError, String(resourceServers)); + } +}); diff --git a/src/company/index.ts b/src/company/index.ts index de2d333..ac48e14 100644 --- a/src/company/index.ts +++ b/src/company/index.ts @@ -127,7 +127,7 @@ export function createCompanyDefaultsPlugin( ) { return definePlugin({ name: "personal-agent-protocol.company", - version: "0.37.2", + version: "0.37.3", contributionPoints: [ CompanyStores, CompanyAccounts, diff --git a/src/company/service.ts b/src/company/service.ts index 957c88d..3db34c5 100644 --- a/src/company/service.ts +++ b/src/company/service.ts @@ -399,6 +399,15 @@ export interface CompanyConfigOptions { * issues tokens for it, and it takes only those. */ readonly conversationResource?: boolean; + /** + * Services of this company at URLs of their own that take its access tokens (§4.5, §7): an + * MCP server on another host than the issuer's, each named by its `url` as `poppy.json` lists + * it. The issuer lists each in `protected_resources` (§3.2) and issues Bearer tokens for it, + * at the request that completes a sign-in or at refresh (RFC 8707); each publishes its own + * protected resource metadata naming this issuer, and takes only the tokens issued for it + * (`CompanyService.accessTokenFor`). + */ + readonly resourceServers?: readonly string[]; /** * Tasks a feedback report may name that can be done after all: the alternative (§8.2) * the company answers with, HTTP 200, keyed by task, compared ignoring case. @@ -547,6 +556,7 @@ export class CompanyConfig { readonly conversationCarryOver: boolean; readonly skills: readonly (readonly [name: string, description: string, text: string])[]; readonly conversationResource: boolean; + readonly resourceServers: readonly string[]; readonly feedbackAnswers: Readonly>>>; readonly devicePage: string | undefined; readonly consentPage: string | undefined; @@ -635,6 +645,7 @@ export class CompanyConfig { } this.skills = [...(options.skills ?? [])]; this.conversationResource = options.conversationResource ?? false; + this.resourceServers = [...(options.resourceServers ?? [])]; this.feedbackAnswers = { ...(options.feedbackAnswers ?? {}) }; this.devicePage = hostedPage("devicePage", options.devicePage); this.consentPage = hostedPage("consentPage", options.consentPage); @@ -711,6 +722,25 @@ export class CompanyConfig { if (this.aliases.includes(this.domain) || new Set(this.aliases).size !== this.aliases.length) { throw new RangeError("each alias is another domain, named once"); } + if (this.resourceServers.length > 0) { + if (!this.oauth) { + throw new RangeError("resourceServers take the issuer's tokens: a company with no issuer has none"); + } + const own = new Set([ + ...[this.domain, ...this.aliases].map((domain) => `https://${domain}`), + `https://${this.domain}/mcp`, + `https://${this.domain}/poppy/conversations`, + ]); + for (const server of this.resourceServers) { + const match = /^https:\/\/([^/?#]+)(\/[^?#]*)?$/.exec(server); + if (match === null) throw new RangeError("a resource server is an HTTPS URL, without query or fragment"); + if (match[1] !== match[1]!.toLowerCase()) throw new RangeError("a resource server's host is in small letters"); + if (own.has(server)) throw new RangeError("a resource server is another service than the company's own"); + } + if (new Set(this.resourceServers).size !== this.resourceServers.length) { + throw new RangeError("each resource server is named once"); + } + } if (this.devicePage !== undefined) { const host = new URL(this.devicePage).hostname.toLowerCase(); const own = domainHost(this.domain); @@ -1355,6 +1385,16 @@ function expiry(at: Date | string | undefined): StoreWriteOptions { * the personal agent and says it wants to connect, never "Sign in with …", which reads as * signing in with an account at the agent. */ +/** + * Where a service's protected resource metadata is (RFC 9728 §3.1): the well-known path between + * its host and its own path. + */ +export function resourceMetadataUrl(resource: string): string { + const url = new URL(resource); + const path = url.pathname === "/" ? "" : url.pathname; + return `${url.protocol}//${url.host}/.well-known/oauth-protected-resource${path}`; +} + export function connectHeading(agent: string, company: string): string { return `${agent} wants to connect to your ${company} account`; } @@ -1992,6 +2032,7 @@ export class CompanyService { }; if (this.#mcp() !== undefined) resources.push(config.mcpUrl); if (config.conversationResource) resources.push(config.conversationsEndpoint); + resources.push(...config.resourceServers); if (config.direct) { grants.push(AUTHORIZATION_CODE_GRANT); metadata.authorization_endpoint = config.authorizationEndpoint; @@ -2230,6 +2271,7 @@ export class CompanyService { } if (this.#mcp() !== undefined && resource === this.config.mcpUrl) return resource; if (this.config.conversationResource && resource === this.config.conversationsEndpoint) return resource; + if (this.config.resourceServers.includes(resource)) return resource; throw new Refused(400, "invalid_target"); } @@ -2740,6 +2782,8 @@ export class CompanyService { const listed = this.protectedResourceMetadata().dpop_signing_alg_values_supported; return Array.isArray(listed) && listed.includes(DPOP_ALGORITHM); } + // A service of its own verifies no proof here: it gets Bearer tokens (§7). + if (this.config.resourceServers.includes(resource)) return false; return true; } @@ -2802,6 +2846,25 @@ export class CompanyService { return issued; } + /** + * The record of an access token presented at one of `resourceServers`, or `undefined`. + * + * For the service at `resource` to verify what it is sent (§4.5, §7): the token was issued + * here **for that service**, is unexpired, its sign-in has not ended, and every scope it + * holds is still offered. A token for another resource, the default token among them, is + * `undefined`: the service answers `invalid_token` with its `resource_metadata` + * (`resourceMetadataUrl`). The record says whose it is (`accountId`), which agent holds it + * (`clientId`) and its `scopes`, which the service enforces. + */ + async accessTokenFor(token: string, resource: string): Promise { + if (!this.config.resourceServers.includes(resource)) { + throw new RangeError(`${resource} is not one of this company's resourceServers`); + } + const issued = await this.#accessToken(token); + if (issued === undefined || issued.resource !== resource || !this.#offers(issued.scopes)) return undefined; + return issued; + } + async #signedOutBefore(accountId: string): Promise { const accounts = optionalContribution(this.reactor, CompanyAccounts, "accounts"); return accounts?.signedOutBefore === undefined ? undefined : accounts.signedOutBefore(accountId); @@ -3641,6 +3704,7 @@ export class CompanyService { #resourceMetadataUrl(resource: string | undefined): string { if (resource === this.config.mcpUrl) return this.config.mcpResourceMetadata; if (resource === this.config.conversationsEndpoint) return this.config.conversationResourceMetadata; + if (resource !== undefined && this.config.resourceServers.includes(resource)) return resourceMetadataUrl(resource); return `${this.config.base}/.well-known/oauth-protected-resource`; } diff --git a/src/reactor.ts b/src/reactor.ts index 6b8183a..7156e4a 100644 --- a/src/reactor.ts +++ b/src/reactor.ts @@ -371,7 +371,7 @@ export function createPapCorePlugin(options: PapCoreOptions = {}) { } return definePlugin({ name: "@datalayer/personal-agent-protocol-core", - version: "0.37.2", + version: "0.37.3", contributionPoints: [ DiscoveryTransports, UrlSafetyPolicies, From a9911f261852f0e2cbdda27c0d602c0023d0e4ee Mon Sep 17 00:00:00 2001 From: Eric Charles Date: Wed, 18 Nov 2026 10:57:05 +0100 Subject: [PATCH 2/4] Resource servers: validated with the rule the issuer's metadata is read with, and published where discovery reads (review of #21). Each URL passes the metadata parser's own HTTPS rule (_https_url, httpsUrl: a host, no user information) and names a well-formed host in small ASCII letters, a port allowed, an internationalized name as its A-labels, with no query or fragment; credentials, an empty or malformed host, a query, a fragment and http are refused when the company is configured, in both SDKs. resource_metadata_url (resourceMetadataUrl) is the helper discovery fetches the metadata at, so a trailing slash on the url cannot make a service undiscoverable. Tests: every accepted URL reads back through the metadata parser; publish URL equals discovery URL for /mcp, /mcp/, / and a nested path --- CHANGELOG.md | 13 ++- .../__tests__/test_resource_servers.py | 99 +++++++++++++++---- personal_agent_protocol/company/service.py | 38 +++++-- src/__tests__/resource-servers.test.mjs | 70 ++++++++++--- src/company/service.ts | 33 +++++-- src/models.ts | 3 +- 6 files changed, 205 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6be4b8a..aad6afd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,9 +26,16 @@ names none behaves exactly as before. default token and a token for another service among them (4.5: a token issued for a `resource` is accepted only at that service). The service enforces the record's `scopes`. - **`resource_metadata_url(resource)` (`resourceMetadataUrl`)**: where a service's protected - resource metadata is (RFC 9728 §3.1), for the `resource_metadata` of its challenges (7). -- Each resource server is an HTTPS URL without query or fragment, its host in small letters, - named once, and not one of the company's own (`https://{domain}`, an alias, its `/mcp`, its + resource metadata is (RFC 9728 §3.1), for the `resource_metadata` of its challenges (7). It + is the helper discovery reads the metadata at (`protected_resource_metadata_url`, + `protectedResourceMetadataUrl`), so what a service publishes and what a Personal Agent fetches + agree, a trailing slash on the `url` included. +- Each resource server is checked when the company is configured, with the rule the issuer's + metadata is read with (HTTPS, a host, no user information), since each is published in + `protected_resources` and one entry a Personal Agent refuses would fail discovery for the + whole company. Narrowed to what names one service: a well-formed host in small ASCII letters + (an internationalized name as its A-labels, a port allowed), no query, no fragment, named + once, and not one of the company's own (`https://{domain}`, an alias, its `/mcp`, its conversation endpoint); a company with no issuer has none. A service named here gets Bearer tokens even from an issuer that binds its own with DPoP (7: a company whose MCP server doesn't accept DPoP returns Bearer tokens for it). diff --git a/personal_agent_protocol/__tests__/test_resource_servers.py b/personal_agent_protocol/__tests__/test_resource_servers.py index 34ab7e0..72a96a5 100644 --- a/personal_agent_protocol/__tests__/test_resource_servers.py +++ b/personal_agent_protocol/__tests__/test_resource_servers.py @@ -14,7 +14,11 @@ from personal_agent_protocol.company import CompanyConfig, resource_metadata_url from personal_agent_protocol.demo.manzanita import CONFIG, manzanita from personal_agent_protocol.errors import PersonalAgentProtocolError -from personal_agent_protocol.models import ProtectedResourceMetadata +from personal_agent_protocol.models import ( + OAuthServerMetadata, + ProtectedResourceMetadata, + protected_resource_metadata_url, +) from .test_company_end_to_end import World from .test_company_refusals import signed_in @@ -112,30 +116,89 @@ async def test_it_gets_bearer_tokens_from_an_issuer_that_binds_its_own() -> None assert (await token_for(world, ELSEWHERE)).token_type == "Bearer" -def test_its_metadata_is_where_rfc_9728_puts_it() -> None: - assert resource_metadata_url(ELSEWHERE) == ( - "https://mcp.manzanita.example/.well-known/oauth-protected-resource/mcp" - ) - assert resource_metadata_url("https://mcp.manzanita.example") == ( - "https://mcp.manzanita.example/.well-known/oauth-protected-resource" - ) +@pytest.mark.parametrize( + ("resource", "published"), + [ + (ELSEWHERE, "https://mcp.manzanita.example/.well-known/oauth-protected-resource/mcp"), + ( + "https://mcp.manzanita.example/mcp/", + "https://mcp.manzanita.example/.well-known/oauth-protected-resource/mcp", + ), + ( + "https://mcp.manzanita.example/", + "https://mcp.manzanita.example/.well-known/oauth-protected-resource", + ), + ( + "https://mcp.manzanita.example", + "https://mcp.manzanita.example/.well-known/oauth-protected-resource", + ), + ( + "https://api.manzanita.example/v2/mcp", + "https://api.manzanita.example/.well-known/oauth-protected-resource/v2/mcp", + ), + ], +) +def test_its_metadata_is_published_where_discovery_reads_it(resource: str, published: str) -> None: + """RFC 9728 §3.1, and one implementation: what a service publishes at is what a + Personal Agent fetches (`fetch_mcp_server_metadata`), a trailing slash included.""" + + assert resource_metadata_url(resource) == published + assert resource_metadata_url(resource) == protected_resource_metadata_url(resource) + + +ACCEPTED = ( + ELSEWHERE, + "https://mcp.manzanita.example:8443/mcp", + "https://xn--mnchen-3ya.example/mcp", + "https://api.manzanita.example/v2/mcp", + "https://mcp.manzanita.example/mcp/", +) + + +def test_every_accepted_one_reads_back_through_the_metadata_parser() -> None: + """Each is published in `protected_resources`: one entry a Personal Agent's parser + refuses would fail discovery for the whole company.""" + + import httpx + + from personal_agent_protocol.company import build_company + + config = dataclasses.replace(CONFIG, resource_servers=ACCEPTED) + service = build_company(config, http_client=httpx.AsyncClient()) + parsed = OAuthServerMetadata.model_validate(service.oauth_metadata()) + assert set(ACCEPTED) <= set(parsed.protected_resources) + assert parsed.lists_resource("manzanita.example") @pytest.mark.parametrize( - "servers", + "server", [ - ("http://mcp.manzanita.example/mcp",), - ("https://mcp.manzanita.example/mcp?x=1",), - ("https://mcp.manzanita.example/mcp#x",), - ("https://MCP.manzanita.example/mcp",), - ("https://manzanita.example",), - ("https://manzanita.example/mcp",), - (ELSEWHERE, ELSEWHERE), + "http://mcp.manzanita.example/mcp", + "https://user:pass@mcp.manzanita.example/mcp", + "https://user@mcp.manzanita.example/mcp", + "https:///mcp", + "https://", + "https://not a host/mcp", + "https://mcp.manzanita.example:port/mcp", + "https://münchen.example/mcp", + "https://MCP.manzanita.example/mcp", + "https://mcp.manzanita.example/mcp?x=1", + "https://mcp.manzanita.example/mcp?", + "https://mcp.manzanita.example/mcp#x", + "https://[::1/mcp", + "mcp.manzanita.example/mcp", + "https://manzanita.example", + "https://manzanita.example/mcp", ], ) -def test_each_is_an_https_url_of_its_own_named_once(servers: tuple[str, ...]) -> None: +def test_anything_else_is_refused_when_the_company_is_configured(server: str) -> None: + with pytest.raises(ValueError): + dataclasses.replace(CONFIG, resource_servers=(server,)) + + +def test_each_is_named_once() -> None: with pytest.raises(ValueError): - dataclasses.replace(CONFIG, resource_servers=servers) + dataclasses.replace(CONFIG, resource_servers=(ELSEWHERE, ELSEWHERE)) def test_a_company_with_no_issuer_has_none() -> None: diff --git a/personal_agent_protocol/company/service.py b/personal_agent_protocol/company/service.py index 3d9cc73..7023ac5 100644 --- a/personal_agent_protocol/company/service.py +++ b/personal_agent_protocol/company/service.py @@ -121,11 +121,13 @@ LinksContent, Message, Operation, + _https_url, compatible_versions, domain_host, effective_context, operations_content, parse_version, + protected_resource_metadata_url, redirect_uri_matches, split_domain, ) @@ -359,15 +361,32 @@ class ConsentDecision: def resource_metadata_url(resource: str) -> str: """Where a service's protected resource metadata is (RFC 9728 §3.1): the well-known - path between its host and its own path.""" + path between its host and its own path. - parts = urlsplit(resource) - path = "" if parts.path in ("", "/") else parts.path - return f"{parts.scheme}://{parts.netloc}/.well-known/oauth-protected-resource{path}" + The URL discovery reads it at (`models.protected_resource_metadata_url`, which this + is): what a service publishes and what a Personal Agent fetches cannot differ, a + trailing slash on the service's `url` included. + """ + + return protected_resource_metadata_url(resource) + + +#: A resource server's authority: DNS labels in small ASCII letters (an +#: internationalized name as its A-labels), and a port when it is not 443. +_RESOURCE_AUTHORITY = re.compile( + r"[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?" +) def _check_resource_servers(config: CompanyConfig) -> None: - """Each of `resource_servers` is an HTTPS URL of its own, named once (§4.5).""" + """Each of `resource_servers` is an HTTPS URL of its own, named once (§4.5). + + Checked with the rule the issuer's metadata is read with (`models._https_url`: HTTPS, + a host, no user information), since each is published in `protected_resources` and + one entry a Personal Agent refuses fails discovery for the whole company; then + narrowed to what names one service: a well-formed host in small letters, no query, + no fragment. + """ servers = config.resource_servers if not servers: @@ -379,11 +398,14 @@ def _check_resource_servers(config: CompanyConfig) -> None: own = {f"https://{domain}" for domain in (config.domain, *config.aliases)} own |= {f"https://{config.domain}/mcp", f"https://{config.domain}/poppy/conversations"} for server in servers: + _https_url(server, "a resource server") parts = urlsplit(server) - if parts.scheme != "https" or not parts.netloc or parts.query or parts.fragment: + if not _RESOURCE_AUTHORITY.fullmatch(parts.netloc): + raise ValueError( + "a resource server names a host in small letters, and no user information" + ) + if parts.query or parts.fragment or "?" in server or "#" in server: raise ValueError("a resource server is an HTTPS URL, without query or fragment") - if parts.netloc != parts.netloc.lower(): - raise ValueError("a resource server's host is in small letters") if server in own: raise ValueError("a resource server is another service than the company's own") if len(set(servers)) != len(servers): diff --git a/src/__tests__/resource-servers.test.mjs b/src/__tests__/resource-servers.test.mjs index b49f8e4..adbd936 100644 --- a/src/__tests__/resource-servers.test.mjs +++ b/src/__tests__/resource-servers.test.mjs @@ -14,8 +14,11 @@ import { SessionClient, discoverCompany, negotiateExtensions, + parseOAuthServerMetadata, parseProtectedResourceMetadata, } from "../../lib/index.js"; +// The helper discovery and `fetchMcpServerMetadata` read the metadata at. +import { protectedResourceMetadataUrl } from "../../lib/models.js"; import { CompanyConfig, resourceMetadataUrl } from "../../lib/server.js"; import { manzanita } from "../../lib/demo/manzanita.js"; import { MutableClock, agentHost, agentIdentity, inProcessFetch } from "./support/world.mjs"; @@ -113,23 +116,60 @@ test("it gets Bearer tokens from an issuer that binds its own", async () => { assert.equal((await w.tokenFor(ELSEWHERE)).token.tokenType, "Bearer"); }); -test("its metadata is where RFC 9728 puts it", () => { - assert.equal(resourceMetadataUrl(ELSEWHERE), "https://mcp.manzanita.example/.well-known/oauth-protected-resource/mcp"); - assert.equal(resourceMetadataUrl("https://mcp.manzanita.example"), "https://mcp.manzanita.example/.well-known/oauth-protected-resource"); +test("its metadata is published where discovery reads it", () => { + // RFC 9728 §3.1, and one implementation: what a service publishes at is what a Personal Agent + // fetches (`fetchMcpServerMetadata`), a trailing slash included. + for (const [resource, published] of [ + [ELSEWHERE, "https://mcp.manzanita.example/.well-known/oauth-protected-resource/mcp"], + ["https://mcp.manzanita.example/mcp/", "https://mcp.manzanita.example/.well-known/oauth-protected-resource/mcp"], + ["https://mcp.manzanita.example/", "https://mcp.manzanita.example/.well-known/oauth-protected-resource"], + ["https://mcp.manzanita.example", "https://mcp.manzanita.example/.well-known/oauth-protected-resource"], + ["https://api.manzanita.example/v2/mcp", "https://api.manzanita.example/.well-known/oauth-protected-resource/v2/mcp"], + ]) { + assert.equal(resourceMetadataUrl(resource), published); + assert.equal(resourceMetadataUrl(resource), protectedResourceMetadataUrl(resource)); + } +}); + +const BASE = { name: "Shop", domain: "shop.example", scopes: ["orders:read"], agentDescription: "Orders", scopeDescriptions: { "orders:read": "Read orders" }, operations: false }; +const ACCEPTED = [ + ELSEWHERE, + "https://mcp.shop.example:8443/mcp", + "https://xn--mnchen-3ya.example/mcp", + "https://api.shop.example/v2/mcp", + "https://mcp.shop.example/mcp/", +]; + +test("every accepted one reads back through the metadata parser", async () => { + // Each is published in `protected_resources`: one entry a Personal Agent's parser refuses + // would fail discovery for the whole company. + const w = await signedInWorld({ resourceServers: ACCEPTED }); + const parsed = parseOAuthServerMetadata(w.shop.oauthMetadata()); + for (const resource of ACCEPTED) assert.ok(parsed.protected_resources.includes(resource), resource); + assert.deepEqual(new CompanyConfig({ ...BASE, resourceServers: ACCEPTED }).resourceServers, ACCEPTED); }); -test("each is an HTTPS URL of its own, named once, of a company with an issuer", () => { - const base = { name: "Shop", domain: "shop.example", scopes: ["orders:read"], agentDescription: "Orders", scopeDescriptions: { "orders:read": "Read orders" }, operations: false }; - assert.deepEqual(new CompanyConfig({ ...base, resourceServers: [ELSEWHERE] }).resourceServers, [ELSEWHERE]); - for (const resourceServers of [ - ["http://mcp.shop.example/mcp"], - ["https://mcp.shop.example/mcp?x=1"], - ["https://mcp.shop.example/mcp#x"], - ["https://MCP.shop.example/mcp"], - ["https://shop.example"], - ["https://shop.example/mcp"], - [ELSEWHERE, ELSEWHERE], +test("anything else is refused when the company is configured", () => { + for (const server of [ + "http://mcp.shop.example/mcp", + "https://user:pass@mcp.shop.example/mcp", + "https://user@mcp.shop.example/mcp", + "https:///mcp", + "https://", + "https://not a host/mcp", + "https://mcp.shop.example:port/mcp", + "https://münchen.example/mcp", + "https://MCP.shop.example/mcp", + "https://mcp.shop.example/mcp?x=1", + "https://mcp.shop.example/mcp?", + "https://mcp.shop.example/mcp#x", + "https://[::1/mcp", + "mcp.shop.example/mcp", + "https://shop.example", + "https://shop.example/mcp", ]) { - assert.throws(() => new CompanyConfig({ ...base, resourceServers }), RangeError, String(resourceServers)); + assert.throws(() => new CompanyConfig({ ...BASE, resourceServers: [server] }), RangeError, server); } + assert.throws(() => new CompanyConfig({ ...BASE, resourceServers: [ELSEWHERE, ELSEWHERE] }), RangeError); + assert.throws(() => new CompanyConfig({ ...BASE, oauth: false, scopes: [], scopeDescriptions: {}, device: false, direct: false, resourceServers: [ELSEWHERE] }), RangeError); }); diff --git a/src/company/service.ts b/src/company/service.ts index 3db34c5..6bd61ca 100644 --- a/src/company/service.ts +++ b/src/company/service.ts @@ -114,7 +114,9 @@ import { compatibleVersions, domainHost, effectiveContext, + httpsUrl, parseVersion, + protectedResourceMetadataUrl, splitDomain, } from "../models.js"; import { @@ -732,9 +734,22 @@ export class CompanyConfig { `https://${this.domain}/poppy/conversations`, ]); for (const server of this.resourceServers) { - const match = /^https:\/\/([^/?#]+)(\/[^?#]*)?$/.exec(server); - if (match === null) throw new RangeError("a resource server is an HTTPS URL, without query or fragment"); - if (match[1] !== match[1]!.toLowerCase()) throw new RangeError("a resource server's host is in small letters"); + // The rule the issuer's metadata is read with (`httpsUrl`: HTTPS, no user information), + // since each is published in `protected_resources` and one entry a Personal Agent + // refuses fails discovery for the whole company; then narrowed to what names one + // service: a well-formed host in small letters, no query, no fragment. + try { + httpsUrl(server, "a resource server"); + } catch (cause) { + throw new RangeError("a resource server is an HTTPS URL, without user information", { cause }); + } + const authority = /^https:\/\/([^/?#]*)/.exec(server)?.[1] ?? ""; + if (!RESOURCE_AUTHORITY.test(authority) || new URL(server).host !== authority.replace(/:443$/, "")) { + throw new RangeError("a resource server names a host in small letters, and no user information"); + } + if (server.includes("?") || server.includes("#")) { + throw new RangeError("a resource server is an HTTPS URL, without query or fragment"); + } if (own.has(server)) throw new RangeError("a resource server is another service than the company's own"); } if (new Set(this.resourceServers).size !== this.resourceServers.length) { @@ -1390,11 +1405,17 @@ function expiry(at: Date | string | undefined): StoreWriteOptions { * its host and its own path. */ export function resourceMetadataUrl(resource: string): string { - const url = new URL(resource); - const path = url.pathname === "/" ? "" : url.pathname; - return `${url.protocol}//${url.host}/.well-known/oauth-protected-resource${path}`; + // The URL discovery reads it at (`protectedResourceMetadataUrl`, which this is): what a service + // publishes and what a Personal Agent fetches cannot differ, a trailing slash included. + return protectedResourceMetadataUrl(resource); } +/** + * A resource server's authority: DNS labels in small ASCII letters (an internationalized name as + * its A-labels), and a port when it is not 443. + */ +const RESOURCE_AUTHORITY = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:[0-9]{1,5})?$/; + export function connectHeading(agent: string, company: string): string { return `${agent} wants to connect to your ${company} account`; } diff --git a/src/models.ts b/src/models.ts index c0078f7..0fffee0 100644 --- a/src/models.ts +++ b/src/models.ts @@ -1176,7 +1176,8 @@ export function companyExtension( return (document.extensions[name] ?? []).find((entry) => entry.version === version); } -function httpsUrl(value: unknown, label: string): string { +/** An HTTPS URL without user information, as given: the rule every published URL is read with. */ +export function httpsUrl(value: unknown, label: string): string { const result = string(value, label); let parsed: URL; try { From 434cb0d70dbb98330d3ec92d6e5d73bfed041362 Mon Sep 17 00:00:00 2001 From: Eric Charles Date: Wed, 18 Nov 2026 11:22:37 +0100 Subject: [PATCH 3/4] Resource servers: the client policy is asked when a token is presented, and a port that is no port is refused (second review of #21). access_token_for (accessTokenFor) answers nothing for an agent the client policy blocks, or for a service it has since left out for that agent, so a blocked agent's unexpired token stops working at a resource server at once, as at the company's own services; a port above 65535 is refused when the company is configured, in Python as in TypeScript. Tests: a blocked agent's token stops working there at once (both SDKs), out-of-range ports --- CHANGELOG.md | 4 ++- .../__tests__/test_resource_servers.py | 34 +++++++++++++++++++ personal_agent_protocol/company/service.py | 14 +++++++- src/__tests__/resource-servers.test.mjs | 21 +++++++++++- src/company/service.ts | 10 ++++-- 5 files changed, 78 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aad6afd..3793af7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,9 @@ names none behaves exactly as before. named no `resource` covers them, those added after it too (4.5). - **`CompanyService.access_token_for(token, resource)` (`accessTokenFor`)**: for such a service to verify what it is sent. The token's record when it was issued for that service, is - unexpired, its sign-in has not ended and its scopes are still offered; nothing otherwise, the + unexpired, its sign-in has not ended, its scopes are still offered and the client policy + still allows its agent and this service for it (asked when the token is presented, so a + blocked agent's token stops working at once); nothing otherwise, the default token and a token for another service among them (4.5: a token issued for a `resource` is accepted only at that service). The service enforces the record's `scopes`. - **`resource_metadata_url(resource)` (`resourceMetadataUrl`)**: where a service's protected diff --git a/personal_agent_protocol/__tests__/test_resource_servers.py b/personal_agent_protocol/__tests__/test_resource_servers.py index 72a96a5..3778488 100644 --- a/personal_agent_protocol/__tests__/test_resource_servers.py +++ b/personal_agent_protocol/__tests__/test_resource_servers.py @@ -107,6 +107,38 @@ async def test_a_token_stops_working_there_when_it_expires() -> None: ) +@pytest.mark.asyncio +async def test_a_blocked_agents_token_stops_working_there_at_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The client policy is asked when the token is presented, not only when it was + issued: an agent the company blocks, or a service it leaves out for that agent + (§4.5), and its unexpired token is refused.""" + + from personal_agent_protocol.company.points import CLIENT_POLICIES + from personal_agent_protocol.reactor import first_contribution + + world = world_with(ELSEWHERE) + await signed_in(world) + token = (await token_for(world, ELSEWHERE)).access_token.get_secret_value() + assert await world.shop.access_token_for(token, ELSEWHERE) is not None + policy = first_contribution(world.shop.reactor, CLIENT_POLICIES, "policy") + + async def left_out(client_id: str, resource: str) -> bool: + return resource != ELSEWHERE + + monkeypatch.setattr(policy, "allows_resource", left_out, raising=False) + assert await world.shop.access_token_for(token, ELSEWHERE) is None + monkeypatch.delattr(policy, "allows_resource") + assert await world.shop.access_token_for(token, ELSEWHERE) is not None + + async def blocked(client_id: str) -> bool: + return False + + monkeypatch.setattr(policy, "allows", blocked) + assert await world.shop.access_token_for(token, ELSEWHERE) is None + + @pytest.mark.asyncio async def test_it_gets_bearer_tokens_from_an_issuer_that_binds_its_own() -> None: """§7: a company whose MCP server doesn't accept DPoP returns Bearer tokens for it.""" @@ -180,6 +212,8 @@ def test_every_accepted_one_reads_back_through_the_metadata_parser() -> None: "https://", "https://not a host/mcp", "https://mcp.manzanita.example:port/mcp", + "https://mcp.manzanita.example:65536/mcp", + "https://mcp.manzanita.example:99999/mcp", "https://münchen.example/mcp", "https://MCP.manzanita.example/mcp", "https://mcp.manzanita.example/mcp?x=1", diff --git a/personal_agent_protocol/company/service.py b/personal_agent_protocol/company/service.py index 7023ac5..d0b9afd 100644 --- a/personal_agent_protocol/company/service.py +++ b/personal_agent_protocol/company/service.py @@ -400,6 +400,10 @@ def _check_resource_servers(config: CompanyConfig) -> None: for server in servers: _https_url(server, "a resource server") parts = urlsplit(server) + # Read, so a port that is no port (above 65535) is refused here: `urlsplit` + # checks it only when asked, and a URL parser that checks at once would refuse + # the issuer's whole metadata over it. + _ = parts.port if not _RESOURCE_AUTHORITY.fullmatch(parts.netloc): raise ValueError( "a resource server names a host in small letters, and no user information" @@ -2671,7 +2675,8 @@ async def access_token_for(self, token: str, resource: str) -> IssuedAccessToken For the service at `resource` to verify what it is sent (§4.5, §7): the token was issued here **for that service**, is unexpired, its sign-in has not ended, - and every scope it holds is still offered. A token for another resource, the + every scope it holds is still offered, and the client policy still allows its + agent, and this service for it. A token for another resource, the 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 @@ -2683,6 +2688,13 @@ 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 + # 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 + ): + return None return issued async def _signed_out_before(self, account_id: str) -> datetime | None: diff --git a/src/__tests__/resource-servers.test.mjs b/src/__tests__/resource-servers.test.mjs index adbd936..69d5c96 100644 --- a/src/__tests__/resource-servers.test.mjs +++ b/src/__tests__/resource-servers.test.mjs @@ -13,13 +13,14 @@ import { RefreshTokenClient, SessionClient, discoverCompany, + firstContribution, negotiateExtensions, parseOAuthServerMetadata, parseProtectedResourceMetadata, } from "../../lib/index.js"; // The helper discovery and `fetchMcpServerMetadata` read the metadata at. import { protectedResourceMetadataUrl } from "../../lib/models.js"; -import { CompanyConfig, resourceMetadataUrl } from "../../lib/server.js"; +import { ClientPolicies, CompanyConfig, resourceMetadataUrl } from "../../lib/server.js"; import { manzanita } from "../../lib/demo/manzanita.js"; import { MutableClock, agentHost, agentIdentity, inProcessFetch } from "./support/world.mjs"; @@ -110,6 +111,22 @@ test("the issuer lists it and issues a Bearer token for it, which only it takes" assert.equal(await w.shop.accessTokenFor(token.accessToken.reveal(), ELSEWHERE), undefined); }); +test("a blocked agent's token stops working there at once", async () => { + // The client policy is asked when the token is presented, not only when it was issued: an + // agent the company blocks, or a service it leaves out for that agent (§4.5), and its + // unexpired token is refused. + const w = await signedInWorld({ resourceServers: [ELSEWHERE] }); + const token = (await w.tokenFor(ELSEWHERE)).token.accessToken.reveal(); + assert.ok(await w.shop.accessTokenFor(token, ELSEWHERE)); + const policy = firstContribution(w.shop.reactor, ClientPolicies, "policy"); + policy.allowsResource = async (_clientId, resource) => resource !== ELSEWHERE; + assert.equal(await w.shop.accessTokenFor(token, ELSEWHERE), undefined); + delete policy.allowsResource; + assert.ok(await w.shop.accessTokenFor(token, ELSEWHERE)); + policy.allows = async () => false; + assert.equal(await w.shop.accessTokenFor(token, ELSEWHERE), undefined); +}); + test("it gets Bearer tokens from an issuer that binds its own", async () => { // §7: a company whose MCP server doesn't accept DPoP returns Bearer tokens for it. const w = await signedInWorld({ resourceServers: [ELSEWHERE], dpopBinding: "optional" }); @@ -158,6 +175,8 @@ test("anything else is refused when the company is configured", () => { "https://", "https://not a host/mcp", "https://mcp.shop.example:port/mcp", + "https://mcp.shop.example:65536/mcp", + "https://mcp.shop.example:99999/mcp", "https://münchen.example/mcp", "https://MCP.shop.example/mcp", "https://mcp.shop.example/mcp?x=1", diff --git a/src/company/service.ts b/src/company/service.ts index 6bd61ca..7a78c23 100644 --- a/src/company/service.ts +++ b/src/company/service.ts @@ -2871,8 +2871,8 @@ export class CompanyService { * The record of an access token presented at one of `resourceServers`, or `undefined`. * * For the service at `resource` to verify what it is sent (§4.5, §7): the token was issued - * here **for that service**, is unexpired, its sign-in has not ended, and every scope it - * holds is still offered. A token for another resource, the default token among them, is + * here **for that service**, is unexpired, its sign-in has not ended, every scope it holds is + * still offered, and the client policy still allows its agent, and this service for it. A token for another resource, the default token among them, is * `undefined`: the service answers `invalid_token` with its `resource_metadata` * (`resourceMetadataUrl`). The record says whose it is (`accountId`), which agent holds it * (`clientId`) and its `scopes`, which the service enforces. @@ -2883,6 +2883,12 @@ export class CompanyService { } const issued = await this.#accessToken(token); if (issued === undefined || issued.resource !== resource || !this.#offers(issued.scopes)) return undefined; + // 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 (!(await this.#allowed(issued.clientId)) || !(await this.#resourceAllowed(issued.clientId, resource))) { + return undefined; + } return issued; } From 8ec2ac8c2b6f3ef1f0a9e886577e89f163c49220 Mon Sep 17 00:00:00 2001 From: Eric Charles Date: Wed, 18 Nov 2026 11:31:29 +0100 Subject: [PATCH 4/4] =?UTF-8?q?Docs:=20the=20independent=20study=20of=200.?= =?UTF-8?q?35.0=20names=20who=20ran=20it=20=E2=80=94=20Kai=20Karlstrom=20(?= =?UTF-8?q?Kirkaldy,=20independent=20testing=20of=20agent=20infrastructure?= =?UTF-8?q?),=20with=20the=20link=20to=20his=20conformance=20kit=20?= =?UTF-8?q?=E2=80=94=20and=20says=20a=20re-run=20on=20the=20current=20rele?= =?UTF-8?q?ase=20is=20planned=20and=20will=20be=20published;=20its=20facts?= =?UTF-8?q?=20are=20unchanged?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 9 ++++++--- docs/docs/protocol/independent-testing.mdx | 8 +++++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3f9d3bf..a47a428 100644 --- a/README.md +++ b/README.md @@ -227,8 +227,9 @@ Each open or partial requirement is listed with its reason in recovery fixture across the four pairings (a Python or TypeScript personal agent against a Python or TypeScript reference company), over real TCP and TLS: [Compatibility and conformance report](https://personal-agent-protocol.datalayer.tech/protocol/conformance-report/). -- **An independent study**: in November 2026 an independent tester ran the - Python SDK 0.35.0, self-hosted and unmodified, through Poppy 1.0's Operations +- **An independent study**: in November 2026 + [Kai Karlstrom](https://github.com/kkrlstrm/kirkaldy-conformance-kit) (Kirkaldy, independent testing of agent infrastructure) + ran the Python SDK 0.35.0, self-hosted and unmodified, through Poppy 1.0's Operations extension and sign-out tests, with effects counted by a separate recorder. Everything passed: a retry after a lost response returned the original response and performed the action once (3 of 3 trials; a deliberately broken @@ -239,7 +240,9 @@ Each open or partial requirement is listed with its reason in user's approval, instruction coverage). One finding is about the protocol, not the SDK: an operation already performing at sign-out completed and reported success, which Poppy leaves unspecified (raised on the Poppy tracker, #84). - 0.36.x was not tested. The write-up, evidence and harness: + 0.36.x and later versions were not tested; a re-run on the current release + is planned, and its result will be published. The write-up, evidence and + harness: [studies/poppy-1.0](https://github.com/kkrlstrm/kirkaldy-conformance-kit/tree/main/studies/poppy-1.0). - **The official company kit**: validate a company implementation, on these SDKs or any other, with the protocol's diff --git a/docs/docs/protocol/independent-testing.mdx b/docs/docs/protocol/independent-testing.mdx index 276422a..2d03ae5 100644 --- a/docs/docs/protocol/independent-testing.mdx +++ b/docs/docs/protocol/independent-testing.mdx @@ -12,8 +12,9 @@ their own implementation. ## An independent study of the Python SDK 0.35.0 -In November 2026 an independent tester of agent infrastructure ran the -**Python SDK 0.35.0, self-hosted and unmodified**, through tests of Poppy 1.0's +In November 2026 +[Kai Karlstrom](https://github.com/kkrlstrm/kirkaldy-conformance-kit) (Kirkaldy, independent testing of agent infrastructure) +ran the **Python SDK 0.35.0, self-hosted and unmodified**, through tests of Poppy 1.0's **Operations extension** and **sign-out**. The effects of each test were counted by a separate recorder, not read from the SDK's own responses. @@ -31,7 +32,8 @@ Poppy does not say what should happen in that case; it was raised on the Poppy tracker (issue #84). **What it does not cover:** the study tested 0.35.0. Version 0.36.x (the 1.0 -draft as the default) has not been tested by it. +draft as the default) and later versions have not been tested by it. A re-run +on the current release is planned, and its result will be published. The write-up, its evidence and the harness are published: [studies/poppy-1.0](https://github.com/kkrlstrm/kirkaldy-conformance-kit/tree/main/studies/poppy-1.0).