Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions docs/client-credentials.md
Original file line number Diff line number Diff line change
@@ -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:<app-password> -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.
4 changes: 4 additions & 0 deletions solid/appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down
143 changes: 143 additions & 0 deletions solid/lib/Controller/ClientCredentialsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

namespace OCA\Solid\Controller;

use OCA\Solid\ServerConfig;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IURLGenerator;
use OCP\IUserManager;

/**
* Lets a signed-in user create client credentials that are bound to their own WebID.
*
* A non-interactive client (a script, a service or an AI agent) can then use
* the OAuth 2.0 client_credentials grant with DPoP to get an access token for
* that WebID, without a browser. The user is signed in with a normal Nextcloud
* session or with an app password (HTTP Basic). Because these routes require
* the CSRF check, API clients send the `OCS-APIRequest: true` header.
*/
class ClientCredentialsController extends Controller
{
public const GRANT_TYPE = 'client_credentials';
public const USER_KEY = 'solid_user_id';

private const USER_VALUE_KEY = 'clientCredentials';

private IConfig $nextcloudConfig;
private ServerConfig $config;
private IURLGenerator $urlGenerator;
private ?string $userId;

public function __construct(
$AppName,
IRequest $request,
IConfig $config,
IURLGenerator $urlGenerator,
IUserManager $userManager,
?string $userId
) {
parent::__construct($AppName, $request);
require_once(__DIR__ . '/../../vendor/autoload.php');

$this->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)));
}
}
68 changes: 67 additions & 1 deletion solid/lib/Controller/ServerController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -310,6 +316,58 @@ 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;
}

/**
* 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";
}
Expand Down Expand Up @@ -356,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'?
Expand All @@ -366,7 +432,7 @@ public function token() {
break;
}

$clientId = $request->getParsedBody()['client_id'] ?? null;
$clientId = $request->getParsedBody()['client_id'] ?? $this->getBasicAuthClientId();

$httpDpop = $request->getServerParams()['HTTP_DPOP'] ?? null;

Expand Down
Loading