From 9c7bba5f6368faf1d057419acffc3fab4514fc51 Mon Sep 17 00:00:00 2001 From: Lumina Date: Sun, 15 Nov 2026 15:10:41 -0500 Subject: [PATCH 1/2] Accept client_secret_basic at the token endpoint The discovery document advertises client_secret_basic, but the token endpoint only looked for client_id in the request body. A confidential client that authenticates with an HTTP Basic Authorization header (the default for openid-client, which @inrupt/solid-client-authn-node uses) therefore got an ID token with "aud": null, which the client rejects, and its registration was never loaded, so the client_credentials grant always failed with 401. Read the client_id from the Basic header (form-urlencoded per RFC 6749 section 2.3.1) when it is not in the body, both for loading the client registration and for the audience of the issued tokens. Co-Authored-By: Claude Opus 5.5 --- solid/lib/Controller/ServerController.php | 33 ++++++++++++- .../Unit/Controller/ServerControllerTest.php | 47 +++++++++++++++++++ 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/solid/lib/Controller/ServerController.php b/solid/lib/Controller/ServerController.php index deeff6cd..7f7e60de 100644 --- a/solid/lib/Controller/ServerController.php +++ b/solid/lib/Controller/ServerController.php @@ -118,6 +118,12 @@ private function createAuthServerConfig() { $clientId = $_POST['client_id']; } } + + if ($clientId === null) { + // A confidential client may authenticate with HTTP Basic (client_secret_basic), + // in which case the client_id is not in the request body. + $clientId = $this->getBasicAuthClientId(); + } $client = $this->getClient($clientId); $keys = $this->getKeys(); try { @@ -310,6 +316,31 @@ private function checkApproval($clientId, $clientRegistration) return $approved; } + /** + * Returns the client_id from an HTTP Basic Authorization header, if present. + * + * Per RFC 6749 section 2.3.1 the client_id and client_secret are + * form-urlencoded before they are joined and base64 encoded. + */ + private function getBasicAuthClientId(): ?string { + $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? ''; + + if (stripos($header, 'Basic ') !== 0) { + return null; + } + + $decoded = base64_decode(substr($header, 6), true); + + if ($decoded === false || strpos($decoded, ':') === false) { + return null; + } + + [$clientId] = explode(':', $decoded, 2); + $clientId = urldecode($clientId); + + return $clientId === '' ? null : $clientId; + } + private function getProfilePage() { return $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute("solid.profile.handleGet", array("userId" => $this->userId, "path" => "/card"))) . "#me"; } @@ -366,7 +397,7 @@ public function token() { break; } - $clientId = $request->getParsedBody()['client_id'] ?? null; + $clientId = $request->getParsedBody()['client_id'] ?? $this->getBasicAuthClientId(); $httpDpop = $request->getServerParams()['HTTP_DPOP'] ?? null; diff --git a/solid/tests/Unit/Controller/ServerControllerTest.php b/solid/tests/Unit/Controller/ServerControllerTest.php index a6768aa7..7d24b9ff 100644 --- a/solid/tests/Unit/Controller/ServerControllerTest.php +++ b/solid/tests/Unit/Controller/ServerControllerTest.php @@ -520,6 +520,53 @@ public function testToken() $this->assertEquals($expected, $actual); } + /** + * @testdox ServerController should read the client_id from an HTTP Basic Authorization header when generating a token + * + * @covers ::token + */ + public function testTokenWithClientSecretBasic() + { + unset($_POST['client_id']); + $_POST['code'] = ''; + $_POST['grant_type'] = 'authorization_code'; + $_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode(urlencode(self::MOCK_CLIENT_ID) . ':mock secret'); + $_SERVER['HTTP_DPOP'] = 'mock dpop'; + $_SESSION['nonce'] = 'mock nonce'; + + $parameters = $this->createMockConstructorParameters(); + + $mockTokenGenerator = $this->createMock(\Pdsinterop\Solid\Auth\TokenGenerator::class); + $mockTokenGenerator->method('getCodeInfo')->willReturn(['user_id' => self::MOCK_USER_ID]); + $mockTokenGenerator->expects($this->once()) + ->method('addIdTokenToResponse') + ->with( + $this->isInstanceOf(Response::class), + self::MOCK_CLIENT_ID, + self::MOCK_USER_ID, + $_SESSION['nonce'], + self::$privateKey, + $_SERVER['HTTP_DPOP'], + ) + ->willReturn(new Response('php://memory', Http::STATUS_IM_A_TEAPOT, [ + 'Content-Type' => 'mock application type' + ])); + + try { + $controller = new ServerController(...$parameters); + + $reflectionObject = new \ReflectionObject($controller); + $reflectionProperty = $reflectionObject->getProperty('tokenGenerator'); + $reflectionProperty->setValue($controller, $mockTokenGenerator); + + $tokenResponse = $controller->token(); + } finally { + unset($_SERVER['HTTP_AUTHORIZATION']); + } + + $this->assertEquals(Http::STATUS_IM_A_TEAPOT, $tokenResponse->getStatus()); + } + /** * @testdox ServerController should return an OK when asked to logout * From c6bb813fc2ca4d16b9fef301ddd125d562095be0 Mon Sep 17 00:00:00 2001 From: Lumina Date: Sun, 15 Nov 2026 15:53:25 -0500 Subject: [PATCH 2/2] Add client credentials bound to a user's WebID A client without a browser (a script, a background service or an AI agent) has no way to get a Solid access token today. The discovery document advertises the client_credentials grant, but a token from that grant carries no WebID, so it gives no access to anything. Let a signed-in user create client credentials that are bound to their own WebID: GET /apps/solid/client-credentials list (no secrets) POST /apps/solid/client-credentials create DELETE /apps/solid/client-credentials/{clientId} revoke The user signs in with a session or a Nextcloud app password; the routes keep the CSRF check, so API clients send OCS-APIRequest: true. When such a client uses the client_credentials grant (client_secret_basic, DPoP), the token endpoint issues the access token and ID token for the bound WebID, after the authorization server has validated the client secret. A client from dynamic registration, or one whose user no longer exists, still gets no WebID. docs/client-credentials.md describes the routes and how to use them with @inrupt/solid-client-authn-node. Co-Authored-By: Claude Opus 5.5 --- docs/client-credentials.md | 62 ++++++++ solid/appinfo/routes.php | 4 + .../ClientCredentialsController.php | 143 ++++++++++++++++++ solid/lib/Controller/ServerController.php | 35 +++++ .../ClientCredentialsControllerTest.php | 138 +++++++++++++++++ .../Unit/Controller/ServerControllerTest.php | 81 ++++++++++ 6 files changed, 463 insertions(+) create mode 100644 docs/client-credentials.md create mode 100644 solid/lib/Controller/ClientCredentialsController.php create mode 100644 solid/tests/Unit/Controller/ClientCredentialsControllerTest.php diff --git a/docs/client-credentials.md b/docs/client-credentials.md new file mode 100644 index 00000000..ba98ad5e --- /dev/null +++ b/docs/client-credentials.md @@ -0,0 +1,62 @@ +# Client credentials for scripts, services and agents + +A Solid app that runs in a browser signs in with the authorization code flow +and the user approves it on the consent page. A client without a browser +(a script, a background service or an AI agent) cannot do that. For those +clients a user can create client credentials that are bound to their own +WebID. The client then uses the OAuth 2.0 `client_credentials` grant with +DPoP, as in the Solid-OIDC client credentials flow that other pod servers +support. + +## Create credentials + +The user (or the client, acting as the user) signs in to Nextcloud with a +normal session or an app password. These routes require the CSRF check, so an +API client sends the `OCS-APIRequest: true` header. + +```sh +curl -u alice: -H 'OCS-APIRequest: true' \ + -H 'Content-Type: application/json' -d '{"name": "backup script"}' \ + https://cloud.example/apps/solid/client-credentials +``` + +The response (`201 Created`) contains the `client_id`, the `client_secret` +(shown only once), the `issuer` and the `webid` the credentials act as. + +| Method | Route | Purpose | +|----------|---------------------------------------------|--------------------------------------| +| `GET` | `/apps/solid/client-credentials` | List your credentials (no secrets) | +| `POST` | `/apps/solid/client-credentials` | Create credentials, optional `name` | +| `DELETE` | `/apps/solid/client-credentials/{clientId}` | Revoke credentials | + +## Use them + +With `@inrupt/solid-client-authn-node`: + +```js +import { Session } from "@inrupt/solid-client-authn-node"; + +const session = new Session(); +await session.login({ + clientId: process.env.SOLID_CLIENT_ID, + clientSecret: process.env.SOLID_CLIENT_SECRET, + oidcIssuer: "https://cloud.example", + tokenType: "DPoP", +}); + +const response = await session.fetch("https://cloud.example/apps/solid/~alice/storage/private/notes.ttl"); +``` + +The access token carries the user's WebID, so the client gets exactly the +access that the user's ACLs give that WebID. A dedicated Nextcloud account for +the client (with its own WebID) keeps its access separate from a person's: +other users can then grant that WebID access to specific resources. + +## Notes + +- Only credentials created through these routes are bound to a WebID. A + client registered through dynamic client registration gets no WebID from + the `client_credentials` grant. +- Revoking credentials stops new tokens. A token that was already issued + stays valid until it expires (one hour). +- Deleting the Nextcloud user also stops new tokens for their credentials. diff --git a/solid/appinfo/routes.php b/solid/appinfo/routes.php index 5475341a..df0ebc51 100644 --- a/solid/appinfo/routes.php +++ b/solid/appinfo/routes.php @@ -32,6 +32,10 @@ ['name' => 'server#register', 'url' => '/register', 'verb' => 'POST'], ['name' => 'server#registeredClient', 'url' => '/register/{clientId}', 'verb' => 'GET'], + ['name' => 'clientCredentials#index', 'url' => '/client-credentials', 'verb' => 'GET'], + ['name' => 'clientCredentials#create', 'url' => '/client-credentials', 'verb' => 'POST'], + ['name' => 'clientCredentials#destroy', 'url' => '/client-credentials/{clientId}', 'verb' => 'DELETE'], + ['name' => 'solidWebhook#listWebhooks', 'url' => '/webhook/list', 'verb' => 'GET'], ['name' => 'solidWebhook#register', 'url' => '/webhook/register', 'verb' => 'POST'], ['name' => 'solidWebhook#unregister', 'url' => '/webhook/unregister', 'verb' => 'POST'], diff --git a/solid/lib/Controller/ClientCredentialsController.php b/solid/lib/Controller/ClientCredentialsController.php new file mode 100644 index 00000000..24acffe5 --- /dev/null +++ b/solid/lib/Controller/ClientCredentialsController.php @@ -0,0 +1,143 @@ +nextcloudConfig = $config; + $this->config = new ServerConfig($config, $urlGenerator, $userManager); + $this->urlGenerator = $urlGenerator; + $this->userId = $userId; + } + + /** + * @NoAdminRequired + */ + public function index(): JSONResponse + { + $credentials = []; + + foreach ($this->getClientIds() as $clientId) { + $registration = $this->config->getClientRegistration($clientId); + if (($registration[self::USER_KEY] ?? null) === $this->userId) { + $credentials[] = [ + 'client_id' => $clientId, + 'client_name' => $registration['client_name'] ?? '', + 'client_id_issued_at' => $registration['client_id_issued_at'] ?? null, + ]; + } + } + + return new JSONResponse($credentials); + } + + /** + * @NoAdminRequired + */ + public function create(?string $name = null): JSONResponse + { + $name = trim((string) $name); + if ($name === '') { + $name = 'Client credentials'; + } + + $registration = $this->config->saveClientRegistration([ + 'client_id_issued_at' => time(), + 'client_name' => mb_substr($name, 0, 100), + 'grant_types' => [self::GRANT_TYPE], + 'redirect_uris' => [], + 'token_endpoint_auth_method' => 'client_secret_basic', + self::USER_KEY => $this->userId, + ]); + + $clientIds = $this->getClientIds(); + $clientIds[] = $registration['client_id']; + $this->setClientIds($clientIds); + + return new JSONResponse([ + 'client_id' => $registration['client_id'], + 'client_secret' => $registration['client_secret'], + 'client_name' => $registration['client_name'], + 'grant_types' => [self::GRANT_TYPE], + 'token_endpoint_auth_method' => 'client_secret_basic', + 'issuer' => $this->urlGenerator->getBaseUrl(), + 'webid' => $this->getWebId(), + ], Http::STATUS_CREATED); + } + + /** + * @NoAdminRequired + */ + public function destroy(string $clientId): JSONResponse + { + $clientIds = $this->getClientIds(); + $registration = $this->config->getClientRegistration($clientId); + + if (!in_array($clientId, $clientIds, true) || ($registration[self::USER_KEY] ?? null) !== $this->userId) { + return new JSONResponse('Not found', Http::STATUS_NOT_FOUND); + } + + $this->config->removeClientRegistration($clientId); + $this->setClientIds(array_values(array_diff($clientIds, [$clientId]))); + + return new JSONResponse('ok'); + } + + private function getWebId(): string + { + return $this->urlGenerator->getAbsoluteURL( + $this->urlGenerator->linkToRoute('solid.profile.handleGet', ['userId' => $this->userId, 'path' => '/card']) + ) . '#me'; + } + + private function getClientIds(): array + { + $value = $this->nextcloudConfig->getUserValue($this->userId, 'solid', self::USER_VALUE_KEY, '[]'); + + return json_decode($value, true) ?: []; + } + + private function setClientIds(array $clientIds): void + { + $this->nextcloudConfig->setUserValue($this->userId, 'solid', self::USER_VALUE_KEY, json_encode(array_values($clientIds))); + } +} diff --git a/solid/lib/Controller/ServerController.php b/solid/lib/Controller/ServerController.php index 7f7e60de..40cf3e30 100644 --- a/solid/lib/Controller/ServerController.php +++ b/solid/lib/Controller/ServerController.php @@ -341,6 +341,33 @@ private function getBasicAuthClientId(): ?string { return $clientId === '' ? null : $clientId; } + /** + * Returns the WebID that client credentials are bound to, or false. + */ + private function getClientCredentialsWebId(?string $clientId) { + if ($clientId === null || $clientId === '') { + return false; + } + + $registration = $this->config->getClientRegistration($clientId) ?? []; + $boundUserId = $registration[ClientCredentialsController::USER_KEY] ?? null; + $grantTypes = $registration['grant_types'] ?? []; + + if ( + !is_string($boundUserId) + || !in_array(ClientCredentialsController::GRANT_TYPE, $grantTypes, true) + || !$this->userManager->userExists($boundUserId) + ) { + return false; + } + + return $this->getProfilePageForUser($boundUserId); + } + + private function getProfilePageForUser(string $userId): string { + return $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute("solid.profile.handleGet", array("userId" => $userId, "path" => "/card"))) . "#me"; + } + private function getProfilePage() { return $this->urlGenerator->getAbsoluteURL($this->urlGenerator->linkToRoute("solid.profile.handleGet", array("userId" => $this->userId, "path" => "/card"))) . "#me"; } @@ -387,6 +414,14 @@ public function token() { $codeInfo = $this->tokenGenerator->getCodeInfo($code); $userId = $codeInfo['user_id']; break; + case "client_credentials": + // Only credentials that a user created for themselves (see + // ClientCredentialsController) are bound to a WebID. The client + // secret itself is validated by the authorization server below. + $userId = $this->getClientCredentialsWebId( + $request->getParsedBody()['client_id'] ?? $this->getBasicAuthClientId() + ); + break; case "refresh_token": $refreshToken = $request->getParsedBody()['refresh_token']; $tokenInfo = $this->tokenGenerator->getCodeInfo($refreshToken); // FIXME: getCodeInfo should be named 'decrypt' or 'getInfo'? diff --git a/solid/tests/Unit/Controller/ClientCredentialsControllerTest.php b/solid/tests/Unit/Controller/ClientCredentialsControllerTest.php new file mode 100644 index 00000000..f2f1db7b --- /dev/null +++ b/solid/tests/Unit/Controller/ClientCredentialsControllerTest.php @@ -0,0 +1,138 @@ + In-memory app values */ + private array $appValues = []; + /** @var array In-memory user values, keyed by "user/key" */ + private array $userValues = []; + + private function createController(?string $userId = self::MOCK_USER_ID): ClientCredentialsController + { + $config = $this->createMock(IConfig::class); + $config->method('getAppValue')->willReturnCallback( + fn ($app, $key, $default = '') => $this->appValues[$key] ?? $default + ); + $config->method('setAppValue')->willReturnCallback( + function ($app, $key, $value) { $this->appValues[$key] = $value; } + ); + $config->method('deleteAppValue')->willReturnCallback( + function ($app, $key) { unset($this->appValues[$key]); } + ); + $config->method('getUserValue')->willReturnCallback( + fn ($user, $app, $key, $default = '') => $this->userValues["$user/$key"] ?? $default + ); + $config->method('setUserValue')->willReturnCallback( + function ($user, $app, $key, $value) { $this->userValues["$user/$key"] = $value; } + ); + + $urlGenerator = $this->createMock(IURLGenerator::class); + $urlGenerator->method('getBaseUrl')->willReturn('https://cloud.example'); + $urlGenerator->method('linkToRoute')->willReturnCallback( + fn ($route, $params) => '/apps/solid/~' . $params['userId'] . '/profile' . $params['path'] + ); + $urlGenerator->method('getAbsoluteURL')->willReturnCallback(fn ($url) => 'https://cloud.example' . $url); + + return new ClientCredentialsController( + 'solid', + $this->createMock(IRequest::class), + $config, + $urlGenerator, + $this->createMock(IUserManager::class), + $userId + ); + } + + /** + * @testdox ClientCredentialsController should create client credentials that are bound to the signed-in user + * @covers ::create + */ + public function testCreate(): void + { + $response = $this->createController()->create('my agent'); + $data = $response->getData(); + + $this->assertSame(Http::STATUS_CREATED, $response->getStatus()); + $this->assertSame('my agent', $data['client_name']); + $this->assertSame('https://cloud.example/apps/solid/~agent/profile/card#me', $data['webid']); + $this->assertSame(['client_credentials'], $data['grant_types']); + $this->assertNotEmpty($data['client_secret']); + + $stored = json_decode($this->appValues['client-' . $data['client_id']], true); + $this->assertSame(self::MOCK_USER_ID, $stored[ClientCredentialsController::USER_KEY]); + $this->assertSame(['client_credentials'], $stored['grant_types']); + $this->assertSame($data['client_secret'], $stored['client_secret']); + } + + /** + * @testdox ClientCredentialsController should list only the credentials of the signed-in user, without secrets + * @covers ::index + * @covers ::create + */ + public function testIndex(): void + { + $mine = $this->createController()->create('mine')->getData(); + + // A registration of another user, listed (by mistake) under this user's ids + $this->appValues['client-theirs'] = json_encode([ + 'client_id' => 'theirs', + 'client_name' => 'theirs', + ClientCredentialsController::USER_KEY => 'someone-else', + ]); + $this->userValues[self::MOCK_USER_ID . '/clientCredentials'] = json_encode([$mine['client_id'], 'theirs']); + + $list = $this->createController()->index()->getData(); + + $this->assertCount(1, $list); + $this->assertSame($mine['client_id'], $list[0]['client_id']); + $this->assertArrayNotHasKey('client_secret', $list[0]); + } + + /** + * @testdox ClientCredentialsController should let a user revoke their own credentials + * @covers ::destroy + * @covers ::create + */ + public function testDestroy(): void + { + $clientId = $this->createController()->create('mine')->getData()['client_id']; + + $response = $this->createController()->destroy($clientId); + + $this->assertSame(Http::STATUS_OK, $response->getStatus()); + $this->assertArrayNotHasKey('client-' . $clientId, $this->appValues); + $this->assertSame([], $this->createController()->index()->getData()); + } + + /** + * @testdox ClientCredentialsController should not let a user revoke credentials of someone else + * @covers ::destroy + * @covers ::create + */ + public function testDestroyOtherUsersCredentials(): void + { + $clientId = $this->createController('someone-else')->create('theirs')->getData()['client_id']; + + $response = $this->createController()->destroy($clientId); + + $this->assertSame(Http::STATUS_NOT_FOUND, $response->getStatus()); + $this->assertArrayHasKey('client-' . $clientId, $this->appValues); + } +} diff --git a/solid/tests/Unit/Controller/ServerControllerTest.php b/solid/tests/Unit/Controller/ServerControllerTest.php index 7d24b9ff..4701cd90 100644 --- a/solid/tests/Unit/Controller/ServerControllerTest.php +++ b/solid/tests/Unit/Controller/ServerControllerTest.php @@ -567,6 +567,87 @@ public function testTokenWithClientSecretBasic() $this->assertEquals(Http::STATUS_IM_A_TEAPOT, $tokenResponse->getStatus()); } + /** + * @testdox ServerController should bind a client_credentials token to the WebID of the user who created the credentials + * + * @covers ::token + */ + public function testTokenWithBoundClientCredentials() + { + $this->assertSame( + 'https://mock.server/apps/solid/~agent/profile/card#me', + $this->requestClientCredentialsToken(['solid_user_id' => 'agent', 'grant_types' => ['client_credentials']], true) + ); + } + + /** + * @testdox ServerController should not bind a client_credentials token to a WebID for a client that no user created + * + * @covers ::token + * @dataProvider provideUnboundRegistrations + */ + public function testTokenWithUnboundClientCredentials(array $registration, bool $userExists) + { + $this->assertNull($this->requestClientCredentialsToken($registration, $userExists)); + } + + public static function provideUnboundRegistrations(): array + { + return [ + 'dynamic registration' => [['grant_types' => ['client_credentials']], true], + 'bound user without the client_credentials grant' => [['solid_user_id' => 'agent'], true], + 'bound user that no longer exists' => [['solid_user_id' => 'agent', 'grant_types' => ['client_credentials']], false], + ]; + } + + /** + * Requests a client_credentials token and returns the subject passed to the token generator, or null + */ + private function requestClientCredentialsToken(array $registration, bool $userExists): ?string + { + $_POST = ['grant_type' => 'client_credentials']; + $_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode(self::MOCK_CLIENT_ID . ':mock secret'); + + $clientData = json_encode(array_merge([ + 'client_id' => self::MOCK_CLIENT_ID, + 'client_name' => 'Mock Client', + 'client_secret' => 'mock secret', + 'redirect_uris' => [], + ], $registration)); + + $parameters = $this->createMockConstructorParameters($clientData); + $this->mockUserManager->method('userExists')->willReturn($userExists); + $this->mockURLGenerator->method('linkToRoute')->willReturnCallback( + fn ($route, $params = []) => isset($params['userId']) + ? '/apps/solid/~' . $params['userId'] . '/profile' . $params['path'] + : '/apps/solid/' . $route + ); + $this->mockURLGenerator->method('getAbsoluteURL')->willReturnCallback(fn ($url) => 'https://mock.server' . $url); + + $subject = null; + $mockTokenGenerator = $this->createMock(\Pdsinterop\Solid\Auth\TokenGenerator::class); + $mockTokenGenerator->method('addIdTokenToResponse')->willReturnCallback( + function ($response, $clientId, $userId) use (&$subject) { + $subject = $userId; + return $response; + } + ); + + try { + $controller = new ServerController(...$parameters); + + $reflectionProperty = (new \ReflectionObject($controller))->getProperty('tokenGenerator'); + $reflectionProperty->setValue($controller, $mockTokenGenerator); + + $controller->token(); + } finally { + $_POST = []; + unset($_SERVER['HTTP_AUTHORIZATION']); + } + + return $subject; + } + /** * @testdox ServerController should return an OK when asked to logout *