From fa0d02a9ac88a1249f54a78e97e03c8e6539381b Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Tue, 25 Jan 2022 12:17:32 +0000 Subject: [PATCH] [PLUGIN][OAuth2] Start adding OAuth2 support with client registration This hardcodes the user, and has some other issues, so it is not yet complete. We follow mastodon's spec for automatic client registration, available at both `/api/v1/apps` and a more reasonable `/oauth/client`. This accepts a JSON POST with the client info and returns JSON with a `client_id` and a `client_secret`, to be used with `/oauth/authorize` and `/oauth/token`. It also, seemingly, requires returning an `id` with unclear purpose. The `/oauth/token` endpoint doesn't currently return a `me` field. --- composer.lock | 341 +++++++++++++++++++++ config/packages/security.yaml | 3 + plugins/OAuth2/Controller/Authorize.php | 100 ++++++ plugins/OAuth2/Controller/Client.php | 98 ++++++ plugins/OAuth2/Controller/Token.php | 72 +++++ plugins/OAuth2/Entity/AccessToken.php | 145 +++++++++ plugins/OAuth2/Entity/AuthCode.php | 152 +++++++++ plugins/OAuth2/Entity/Client.php | 231 ++++++++++++++ plugins/OAuth2/Entity/RefreshToken.php | 177 +++++++++++ plugins/OAuth2/Entity/Token.php | 149 +++++++++ plugins/OAuth2/OAuth2.php | 108 +++++++ plugins/OAuth2/Repository/AccessToken.php | 75 +++++ plugins/OAuth2/Repository/AuthCode.php | 62 ++++ plugins/OAuth2/Repository/Client.php | 61 ++++ plugins/OAuth2/Repository/RefreshToken.php | 62 ++++ plugins/OAuth2/Repository/Scope.php | 92 ++++++ plugins/OAuth2/composer.json | 6 + plugins/OAuth2/config.yaml | 6 + social.yaml | 6 + symfony.lock | 15 + 20 files changed, 1961 insertions(+) create mode 100644 plugins/OAuth2/Controller/Authorize.php create mode 100644 plugins/OAuth2/Controller/Client.php create mode 100644 plugins/OAuth2/Controller/Token.php create mode 100644 plugins/OAuth2/Entity/AccessToken.php create mode 100644 plugins/OAuth2/Entity/AuthCode.php create mode 100644 plugins/OAuth2/Entity/Client.php create mode 100644 plugins/OAuth2/Entity/RefreshToken.php create mode 100644 plugins/OAuth2/Entity/Token.php create mode 100644 plugins/OAuth2/OAuth2.php create mode 100644 plugins/OAuth2/Repository/AccessToken.php create mode 100644 plugins/OAuth2/Repository/AuthCode.php create mode 100644 plugins/OAuth2/Repository/Client.php create mode 100644 plugins/OAuth2/Repository/RefreshToken.php create mode 100644 plugins/OAuth2/Repository/Scope.php create mode 100644 plugins/OAuth2/composer.json create mode 100644 plugins/OAuth2/config.yaml diff --git a/composer.lock b/composer.lock index 420e1e68e3..871a293c67 100644 --- a/composer.lock +++ b/composer.lock @@ -221,6 +221,72 @@ ], "time": "2022-01-17T14:14:24+00:00" }, + { + "name": "defuse/php-encryption", + "version": "v2.3.1", + "source": { + "type": "git", + "url": "https://github.com/defuse/php-encryption.git", + "reference": "77880488b9954b7884c25555c2a0ea9e7053f9d2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/defuse/php-encryption/zipball/77880488b9954b7884c25555c2a0ea9e7053f9d2", + "reference": "77880488b9954b7884c25555c2a0ea9e7053f9d2", + "shasum": "" + }, + "require": { + "ext-openssl": "*", + "paragonie/random_compat": ">= 2", + "php": ">=5.6.0" + }, + "require-dev": { + "phpunit/phpunit": "^4|^5|^6|^7|^8|^9" + }, + "bin": [ + "bin/generate-defuse-key" + ], + "type": "library", + "autoload": { + "psr-4": { + "Defuse\\Crypto\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Hornby", + "email": "taylor@defuse.ca", + "homepage": "https://defuse.ca/" + }, + { + "name": "Scott Arciszewski", + "email": "info@paragonie.com", + "homepage": "https://paragonie.com" + } + ], + "description": "Secure PHP Encryption Library", + "keywords": [ + "aes", + "authenticated encryption", + "cipher", + "crypto", + "cryptography", + "encrypt", + "encryption", + "openssl", + "security", + "symmetric key cryptography" + ], + "support": { + "issues": "https://github.com/defuse/php-encryption/issues", + "source": "https://github.com/defuse/php-encryption/tree/v2.3.1" + }, + "time": "2021-04-09T23:57:26+00:00" + }, { "name": "doctrine/annotations", "version": "1.13.2", @@ -2599,6 +2665,281 @@ }, "time": "2021-04-11T16:10:46+00:00" }, + { + "name": "lcobucci/clock", + "version": "2.1.0", + "source": { + "type": "git", + "url": "https://github.com/lcobucci/clock.git", + "reference": "903513d28e85376a33385ebc601afd2ee69e5653" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/lcobucci/clock/zipball/903513d28e85376a33385ebc601afd2ee69e5653", + "reference": "903513d28e85376a33385ebc601afd2ee69e5653", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "require-dev": { + "infection/infection": "^0.25", + "lcobucci/coding-standard": "^8.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-deprecation-rules": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", + "phpstan/phpstan-strict-rules": "^0.12", + "phpunit/phpunit": "^9.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Lcobucci\\Clock\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Luís Cobucci", + "email": "lcobucci@gmail.com" + } + ], + "description": "Yet another clock abstraction", + "support": { + "issues": "https://github.com/lcobucci/clock/issues", + "source": "https://github.com/lcobucci/clock/tree/2.1.0" + }, + "funding": [ + { + "url": "https://github.com/lcobucci", + "type": "github" + }, + { + "url": "https://www.patreon.com/lcobucci", + "type": "patreon" + } + ], + "time": "2021-10-31T21:32:07+00:00" + }, + { + "name": "lcobucci/jwt", + "version": "4.1.5", + "source": { + "type": "git", + "url": "https://github.com/lcobucci/jwt.git", + "reference": "fe2d89f2eaa7087af4aa166c6f480ef04e000582" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/lcobucci/jwt/zipball/fe2d89f2eaa7087af4aa166c6f480ef04e000582", + "reference": "fe2d89f2eaa7087af4aa166c6f480ef04e000582", + "shasum": "" + }, + "require": { + "ext-hash": "*", + "ext-json": "*", + "ext-mbstring": "*", + "ext-openssl": "*", + "ext-sodium": "*", + "lcobucci/clock": "^2.0", + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "infection/infection": "^0.21", + "lcobucci/coding-standard": "^6.0", + "mikey179/vfsstream": "^1.6.7", + "phpbench/phpbench": "^1.0", + "phpstan/extension-installer": "^1.0", + "phpstan/phpstan": "^0.12", + "phpstan/phpstan-deprecation-rules": "^0.12", + "phpstan/phpstan-phpunit": "^0.12", + "phpstan/phpstan-strict-rules": "^0.12", + "phpunit/php-invoker": "^3.1", + "phpunit/phpunit": "^9.5" + }, + "type": "library", + "autoload": { + "psr-4": { + "Lcobucci\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Luís Cobucci", + "email": "lcobucci@gmail.com", + "role": "Developer" + } + ], + "description": "A simple library to work with JSON Web Token and JSON Web Signature", + "keywords": [ + "JWS", + "jwt" + ], + "support": { + "issues": "https://github.com/lcobucci/jwt/issues", + "source": "https://github.com/lcobucci/jwt/tree/4.1.5" + }, + "funding": [ + { + "url": "https://github.com/lcobucci", + "type": "github" + }, + { + "url": "https://www.patreon.com/lcobucci", + "type": "patreon" + } + ], + "time": "2021-09-28T19:34:56+00:00" + }, + { + "name": "league/event", + "version": "2.2.0", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/event.git", + "reference": "d2cc124cf9a3fab2bb4ff963307f60361ce4d119" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/event/zipball/d2cc124cf9a3fab2bb4ff963307f60361ce4d119", + "reference": "d2cc124cf9a3fab2bb4ff963307f60361ce4d119", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "henrikbjorn/phpspec-code-coverage": "~1.0.1", + "phpspec/phpspec": "^2.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev" + } + }, + "autoload": { + "psr-4": { + "League\\Event\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Frank de Jonge", + "email": "info@frenky.net" + } + ], + "description": "Event package", + "keywords": [ + "emitter", + "event", + "listener" + ], + "support": { + "issues": "https://github.com/thephpleague/event/issues", + "source": "https://github.com/thephpleague/event/tree/master" + }, + "time": "2018-11-26T11:52:41+00:00" + }, + { + "name": "league/oauth2-server", + "version": "8.3.3", + "source": { + "type": "git", + "url": "https://github.com/thephpleague/oauth2-server.git", + "reference": "f5698a3893eda9a17bcd48636990281e7ca77b2a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/thephpleague/oauth2-server/zipball/f5698a3893eda9a17bcd48636990281e7ca77b2a", + "reference": "f5698a3893eda9a17bcd48636990281e7ca77b2a", + "shasum": "" + }, + "require": { + "defuse/php-encryption": "^2.2.1", + "ext-json": "*", + "ext-openssl": "*", + "lcobucci/jwt": "^3.4.6 || ^4.0.4", + "league/event": "^2.2", + "php": "^7.2 || ^8.0", + "psr/http-message": "^1.0.1" + }, + "replace": { + "league/oauth2server": "*", + "lncd/oauth2": "*" + }, + "require-dev": { + "laminas/laminas-diactoros": "^2.4.1", + "phpstan/phpstan": "^0.12.57", + "phpstan/phpstan-phpunit": "^0.12.16", + "phpunit/phpunit": "^8.5.13", + "roave/security-advisories": "dev-master" + }, + "type": "library", + "autoload": { + "psr-4": { + "League\\OAuth2\\Server\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Alex Bilbie", + "email": "hello@alexbilbie.com", + "homepage": "http://www.alexbilbie.com", + "role": "Developer" + }, + { + "name": "Andy Millington", + "email": "andrew@noexceptions.io", + "homepage": "https://www.noexceptions.io", + "role": "Developer" + } + ], + "description": "A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.", + "homepage": "https://oauth2.thephpleague.com/", + "keywords": [ + "Authentication", + "api", + "auth", + "authorisation", + "authorization", + "oauth", + "oauth 2", + "oauth 2.0", + "oauth2", + "protect", + "resource", + "secure", + "server" + ], + "support": { + "issues": "https://github.com/thephpleague/oauth2-server/issues", + "source": "https://github.com/thephpleague/oauth2-server/tree/8.3.3" + }, + "funding": [ + { + "url": "https://github.com/sephster", + "type": "github" + } + ], + "time": "2021-10-11T20:41:49+00:00" + }, { "name": "league/uri-parser", "version": "1.4.1", diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 237d96223f..9566d2688c 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -20,6 +20,9 @@ security: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false + oauth: + pattern: ^/oauth + security: false main: entry_point: App\Security\Authenticator guard: diff --git a/plugins/OAuth2/Controller/Authorize.php b/plugins/OAuth2/Controller/Authorize.php new file mode 100644 index 0000000000..f1535443a6 --- /dev/null +++ b/plugins/OAuth2/Controller/Authorize.php @@ -0,0 +1,100 @@ +. +// }}} + +/** + * OAuth2 implementation for GNU social + * + * @package OAuth2 + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Controller; + +use App\Core\Controller; +use App\Entity\LocalUser; +use App\Util\Exception\NotFoundException; +use League\OAuth2\Server\Entities\UserEntityInterface; +use League\OAuth2\Server\Exception\OAuthServerException; +use Nyholm\Psr7\Factory\Psr17Factory; +use Plugin\OAuth2\OAuth2; +use Psr\Http\Message\ResponseFactoryInterface; +use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; +use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; + +class Authorize extends Controller +{ + public function __construct( + RequestStack $stack, + private ResponseFactoryInterface $response_factory, + ) { + parent::__construct($stack); + } + + public function __invoke(Request $request) + { + // @var \League\OAuth2\Server\AuthorizationServer $server + $server = OAuth2::$authorization_server; + $response = $this->response_factory->createResponse(); + $httpFoundationFactory = new HttpFoundationFactory; + + try { + // Validate the HTTP request and return an AuthorizationRequest object. + // The auth request object can be serialized into a user's session + $psr17Factory = new Psr17Factory(); + $psrHttpFactory = new PsrHttpFactory($psr17Factory, $psr17Factory, $psr17Factory, $psr17Factory); + $psrRequest = $psrHttpFactory->createRequest($request); + $authRequest = $server->validateAuthorizationRequest($psrRequest); + + // TODO + // Once the user has logged in set the user on the AuthorizationRequest + $authRequest->setUser( + new class(LocalUser::getByNickname('foo')->getId()) implements UserEntityInterface { + public function __construct(private int $id) + { + } + public function getIdentifier() + { + return $this->id; + } + }, + ); + + // Once the user has approved or denied the client update the status + // (true = approved, false = denied) + $authRequest->setAuthorizationApproved(true); + + // Return the HTTP redirect response + return $httpFoundationFactory->createResponse($server->completeAuthorizationRequest($authRequest, $response)); + } catch (OAuthServerException $exception) { + return $httpFoundationFactory->createResponse($exception->generateHttpResponse($response)); + } catch (NotFoundException) { + return new JsonResponse(['error' => 'No such client', 'error_description' => 'This client is not registered']); + } + } +} diff --git a/plugins/OAuth2/Controller/Client.php b/plugins/OAuth2/Controller/Client.php new file mode 100644 index 0000000000..1ab2467f48 --- /dev/null +++ b/plugins/OAuth2/Controller/Client.php @@ -0,0 +1,98 @@ +. +// }}} + +/** + * OAuth2 implementation for GNU social + * + * @package OAuth2 + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Controller; + +use App\Core\Controller; +use App\Core\DB\DB; +use function App\Core\I18n\_m; +use App\Core\Log; +use App\Util\Exception\ClientException; +use Plugin\OAuth2\Entity; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; + +/** + * Client Management Endpoint + * + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ +class Client extends Controller +{ + public function onPost(Request $request): JsonResponse + { + Log::debug('OAuth2 Apps: Received a POST request.'); + Log::debug('OAuth2 Apps: Request content: ', [$body = $request->getContent()]); + $args = json_decode($body, true); + + if (\is_null($args) || !\array_key_exists('redirect_uris', $args)) { + throw new ClientException(_m('Invalid request'), code: 400); + } + + $identifier = hash('sha256', random_bytes(16)); // TODO maybe use password_hash and verify + $secret = hash('sha256', random_bytes(64)); + + // TODO more validation + $client = Entity\Client::create([ + 'id' => $identifier, + 'secret' => $secret, + 'active' => true, + 'plain_pcke' => false, + 'is_confidential' => true, + 'redirect_uris' => $args['redirect_uris'], + 'grants' => 'client_credentials', + 'scopes' => $args['scopes'] ?? 'read', + 'client_name' => $args['client_name'], + 'website' => $args['website'] ?? null, + ]); + DB::persist($client); + DB::flush(); + + Log::debug('OAuth2 Apps: Created App: ', [$client]); + + $app_response = [ + 'id' => 42, // TODO ??? + 'name' => $client->getName(), + 'website' => $client->getWebsite(), + 'redirect_uri' => $client->getRedirectUri(), + 'client_id' => $client->getIdentifier(), + 'client_secret' => $client->getSecret(), + ]; + + Log::debug('OAuth2 Apps: Create App response: ', [$app_response]); + + // Success + return new JsonResponse($app_response, status: 200, headers: ['content_type' => 'application/json; charset=utf-8']); + } +} diff --git a/plugins/OAuth2/Controller/Token.php b/plugins/OAuth2/Controller/Token.php new file mode 100644 index 0000000000..ff1a83b8ee --- /dev/null +++ b/plugins/OAuth2/Controller/Token.php @@ -0,0 +1,72 @@ +. +// }}} + +/** + * OAuth2 implementation for GNU social + * + * @package OAuth2 + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Controller; + +use App\Core\Controller; +use League\OAuth2\Server\Exception\OAuthServerException; +use Nyholm\Psr7\Factory\Psr17Factory; +use Plugin\OAuth2\OAuth2; +use Psr\Http\Message\ResponseFactoryInterface; +use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; +use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; + +class Token extends Controller +{ + public function __construct( + RequestStack $stack, + private ResponseFactoryInterface $response_factory, + ) { + parent::__construct($stack); + } + + public function __invoke(Request $request) + { + // @var \League\OAuth2\Server\AuthorizationServer $server + $server = OAuth2::$authorization_server; + $psr17factory = new Psr17Factory(); + $psr_http_factory = new PsrHttpFactory($psr17factory, $psr17factory, $psr17factory, $psr17factory); + $psr_request = $psr_http_factory->createRequest($request); + + $http_foundation_factory = new HttpFoundationFactory; + $server_response = $this->response_factory->createResponse(); + + try { + return $http_foundation_factory->createResponse($server->respondToAccessTokenRequest($psr_request, $server_response)); + } catch (OAuthServerException $e) { + return $http_foundation_factory->createResponse($e->generateHttpResponse($server_response)); + } + } +} diff --git a/plugins/OAuth2/Entity/AccessToken.php b/plugins/OAuth2/Entity/AccessToken.php new file mode 100644 index 0000000000..9282ecbead --- /dev/null +++ b/plugins/OAuth2/Entity/AccessToken.php @@ -0,0 +1,145 @@ +. +// }}} + +/** + * OAuth2 Client + * + * @package GNUsocial + * + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Entity; + +use DateTimeInterface; +use League\OAuth2\Server\CryptKey; +use League\OAuth2\Server\Entities\AccessTokenEntityInterface; + +class AccessToken extends Token implements AccessTokenEntityInterface +{ + // {{{ Autocode + // @codeCoverageIgnoreStart + private string $id; + private DateTimeInterface $expiry; + private ?int $user_id = null; + private string $client_id; + private string $token_scopes; + private bool $revoked; + private DateTimeInterface $created; + + public function setId(string $id): self + { + $this->id = mb_substr($id, 0, 64); + return $this; + } + + public function getId(): string + { + return $this->id; + } + + public function setExpiry(DateTimeInterface $expiry): self + { + $this->expiry = $expiry; + return $this; + } + + public function getExpiry(): DateTimeInterface + { + return $this->expiry; + } + + public function setUserId(?int $user_id): self + { + $this->user_id = $user_id; + return $this; + } + + public function getUserId(): ?int + { + return $this->user_id; + } + + public function setClientId(string $client_id): self + { + $this->client_id = mb_substr($client_id, 0, 64); + return $this; + } + + public function getClientId(): string + { + return $this->client_id; + } + + public function setTokenScopes(string $token_scopes): self + { + $this->token_scopes = $token_scopes; + return $this; + } + + public function getTokenScopes(): string + { + return $this->token_scopes; + } + + public function setRevoked(bool $revoked): self + { + $this->revoked = $revoked; + return $this; + } + + public function getRevoked(): bool + { + return $this->revoked; + } + + public function setCreated(DateTimeInterface $created): self + { + $this->created = $created; + return $this; + } + + public function getCreated(): DateTimeInterface + { + return $this->created; + } + + // @codeCoverageIgnoreEnd + // }}} Autocode + + public CryptKey $private_key; + public function setPrivateKey(CryptKey $private_key) + { + $this->private_key = $private_key; + } + + public function __toString() + { + return $this->getId(); + } + + public static function schemaDef(): array + { + return parent::tokenSchema('oauth2_access_token'); + } +} diff --git a/plugins/OAuth2/Entity/AuthCode.php b/plugins/OAuth2/Entity/AuthCode.php new file mode 100644 index 0000000000..8de06b28f7 --- /dev/null +++ b/plugins/OAuth2/Entity/AuthCode.php @@ -0,0 +1,152 @@ +. +// }}} + +/** + * OAuth2 Client + * + * @package GNUsocial + * + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Entity; + +use DateTimeInterface; +use League\OAuth2\Server\Entities\AuthCodeEntityInterface; +use Plugin\OAuth2\Repository; + +class AuthCode extends Token implements AuthCodeEntityInterface +{ + // {{{ Autocode + // @codeCoverageIgnoreStart + private string $id; + private DateTimeInterface $expiry; + private ?int $user_id = null; + private string $client_id; + private string $token_scopes; + private bool $revoked; + private DateTimeInterface $created; + + public function setId(string $id): self + { + $this->id = mb_substr($id, 0, 64); + return $this; + } + + public function getId(): string + { + return $this->id; + } + + public function setExpiry(DateTimeInterface $expiry): self + { + $this->expiry = $expiry; + return $this; + } + + public function getExpiry(): DateTimeInterface + { + return $this->expiry; + } + + public function setUserId(?int $user_id): self + { + $this->user_id = $user_id; + return $this; + } + + public function getUserId(): ?int + { + return $this->user_id; + } + + public function setClientId(string $client_id): self + { + $this->client_id = mb_substr($client_id, 0, 64); + return $this; + } + + public function getClientId(): string + { + return $this->client_id; + } + + public function setTokenScopes(string $token_scopes): self + { + $this->token_scopes = $token_scopes; + return $this; + } + + public function getTokenScopes(): string + { + return $this->token_scopes; + } + + public function setRevoked(bool $revoked): self + { + $this->revoked = $revoked; + return $this; + } + + public function getRevoked(): bool + { + return $this->revoked; + } + + public function setCreated(DateTimeInterface $created): self + { + $this->created = $created; + return $this; + } + + public function getCreated(): DateTimeInterface + { + return $this->created; + } + + // @codeCoverageIgnoreEnd + // }}} Autocode + + /** + * @return null|string + */ + public function getRedirectUri() + { + return (new Repository\Client)->getClientEntity($this->getClientId())->getRedirectUri(); + } + + /** + * @param string $uri + */ + public function setRedirectUri($uri) + { + /** @var Client $client */ + $client = (new Repository\Client)->getClientEntity($this->getClientId()); + $client->setRedirectUris($uri); + } + + public static function schemaDef(): array + { + return parent::tokenSchema('oauth2_auth_code'); + } +} diff --git a/plugins/OAuth2/Entity/Client.php b/plugins/OAuth2/Entity/Client.php new file mode 100644 index 0000000000..27ef342a6e --- /dev/null +++ b/plugins/OAuth2/Entity/Client.php @@ -0,0 +1,231 @@ +. +// }}} + +/** + * OAuth2 Client + * + * @package GNUsocial + * + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Entity; + +use App\Core\Entity; +use DateTimeInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; + +class Client extends Entity implements ClientEntityInterface +{ + // {{{ Autocode + // @codeCoverageIgnoreStart + private string $id; + private string $secret; + private bool $active; + private bool $plain_pcke; + private bool $is_confidential; + private string $redirect_uris; + private string $grants; + private string $scopes; + private string $client_name; + private ?string $website = null; + private DateTimeInterface $created; + private DateTimeInterface $modified; + + public function setId(string $id): self + { + $this->id = mb_substr($id, 0, 64); + return $this; + } + + public function getId(): string + { + return $this->id; + } + + public function setSecret(string $secret): self + { + $this->secret = mb_substr($secret, 0, 64); + return $this; + } + + public function getSecret(): string + { + return $this->secret; + } + + public function setActive(bool $active): self + { + $this->active = $active; + return $this; + } + + public function getActive(): bool + { + return $this->active; + } + + public function setPlainPcke(bool $plain_pcke): self + { + $this->plain_pcke = $plain_pcke; + return $this; + } + + public function getPlainPcke(): bool + { + return $this->plain_pcke; + } + + public function setIsConfidential(bool $is_confidential): self + { + $this->is_confidential = $is_confidential; + return $this; + } + + public function getIsConfidential(): bool + { + return $this->is_confidential; + } + + public function setRedirectUris(string $redirect_uris): self + { + $this->redirect_uris = $redirect_uris; + return $this; + } + + public function getRedirectUris(): string + { + return $this->redirect_uris; + } + + public function setGrants(string $grants): self + { + $this->grants = $grants; + return $this; + } + + public function getGrants(): string + { + return $this->grants; + } + + public function setScopes(string $scopes): self + { + $this->scopes = $scopes; + return $this; + } + + public function getScopes(): string + { + return $this->scopes; + } + + public function setClientName(string $client_name): self + { + $this->client_name = mb_substr($client_name, 0, 191); + return $this; + } + + public function getClientName(): string + { + return $this->client_name; + } + + public function setWebsite(?string $website): self + { + $this->website = $website; + return $this; + } + + public function getWebsite(): ?string + { + return $this->website; + } + + public function setCreated(DateTimeInterface $created): self + { + $this->created = $created; + return $this; + } + + public function getCreated(): DateTimeInterface + { + return $this->created; + } + + public function setModified(DateTimeInterface $modified): self + { + $this->modified = $modified; + return $this; + } + + public function getModified(): DateTimeInterface + { + return $this->modified; + } + + // @codeCoverageIgnoreEnd + // }}} Autocode + + public function getIdentifier() + { + return $this->getId(); + } + + public function getName(): string + { + return $this->getClientName(); + } + + public function getRedirectUri(): string + { + return mb_substr($this->getRedirectUris(), 0, mb_strpos($this->getRedirectUris(), ' ') ?: null); + } + + public function isConfidential(): bool + { + return $this->getIsConfidential(); + } + + public static function schemaDef(): array + { + return [ + 'name' => 'oauth2_client', + 'fields' => [ + 'id' => ['type' => 'char', 'length' => 64, 'not null' => true, 'description' => 'client identifier'], + 'secret' => ['type' => 'char', 'length' => 64, 'not null' => true, 'description' => 'client secret'], + 'active' => ['type' => 'bool', 'not null' => true, 'description' => 'whether this client is active'], + 'plain_pcke' => ['type' => 'bool', 'not null' => true, 'description' => 'whether to allow plaintext PKCE'], + 'is_confidential' => ['type' => 'bool', 'not null' => true, 'description' => 'whether this client needs to provide the secret'], + 'redirect_uris' => ['type' => 'text', 'not null' => true, 'description' => 'application redirect uris, space separated'], + 'grants' => ['type' => 'text', 'not null' => true, 'description' => 'application grants, space separated'], + 'scopes' => ['type' => 'text', 'not null' => true, 'description' => 'application scopes, space separated'], + 'client_name' => ['type' => 'varchar', 'length' => 191, 'not null' => true, 'description' => 'name of the application'], + 'website' => ['type' => 'text', 'not null' => false, 'description' => 'application homepage - used for source link'], + 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'], + 'modified' => ['type' => 'timestamp', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'], + ], + 'primary key' => ['id'], + ]; + } +} diff --git a/plugins/OAuth2/Entity/RefreshToken.php b/plugins/OAuth2/Entity/RefreshToken.php new file mode 100644 index 0000000000..ed6d4b1815 --- /dev/null +++ b/plugins/OAuth2/Entity/RefreshToken.php @@ -0,0 +1,177 @@ +. +// }}} + +/** + * OAuth2 Client + * + * @package GNUsocial + * + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Entity; + +use App\Core\Entity; +use DateTimeInterface; +use League\OAuth2\Server\Entities\AccessTokenEntityInterface; +use League\OAuth2\Server\Entities\RefreshTokenEntityInterface; + +class RefreshToken extends Entity implements RefreshTokenEntityInterface +{ + // {{{ Autocode + // @codeCoverageIgnoreStart + private string $id; + private DateTimeInterface $expiry; + private ?string $access_token_id = null; + private bool $revoked; + private DateTimeInterface $created; + + public function setId(string $id): self + { + $this->id = mb_substr($id, 0, 64); + return $this; + } + + public function getId(): string + { + return $this->id; + } + + public function setExpiry(DateTimeInterface $expiry): self + { + $this->expiry = $expiry; + return $this; + } + + public function getExpiry(): DateTimeInterface + { + return $this->expiry; + } + + public function setAccessTokenId(?string $access_token_id): self + { + $this->access_token_id = \is_null($access_token_id) ? null : mb_substr($access_token_id, 0, 64); + return $this; + } + + public function getAccessTokenId(): ?string + { + return $this->access_token_id; + } + + public function setRevoked(bool $revoked): self + { + $this->revoked = $revoked; + return $this; + } + + public function getRevoked(): bool + { + return $this->revoked; + } + + public function setCreated(DateTimeInterface $created): self + { + $this->created = $created; + return $this; + } + + public function getCreated(): DateTimeInterface + { + return $this->created; + } + + // @codeCoverageIgnoreEnd + // }}} Autocode + + /** + * Get the token's identifier. + * + * @return string + */ + public function getIdentifier() + { + return $this->getId(); + } + + /** + * Set the token's identifier. + */ + public function setIdentifier($identifier) + { + $this->setId($identifier); + } + + /** + * Get the token's expiry date time. + * + * @return DateTimeImmutable + */ + public function getExpiryDateTime() + { + return $this->getExpiry(); + } + + /** + * Set the date time when the token expires. + * + * @param DateTimeImmutable $dateTime + */ + public function setExpiryDateTime(\DateTimeImmutable $dateTime) + { + $this->setExpiry($dateTime); + } + + /** + * Set the access token that the refresh token was associated with. + */ + public function setAccessToken(AccessTokenEntityInterface $accessToken) + { + $this->setAccessTokenId($accessToken->getIdentifier()); + } + + /** + * Get the access token that the refresh token was originally associated with. + * + * @return AccessTokenEntityInterface + */ + public function getAccessToken() + { + return (new Repository\AccessToken)->getAccessTokenEntity($this->getAccessTokenId()); + } + + public static function schemaDef(): array + { + return [ + 'name' => 'oauth2_refresh_token', + 'fields' => [ + 'id' => ['type' => 'char', 'length' => 64, 'not null' => true, 'description' => 'identifier for this token'], + 'expiry' => ['type' => 'datetime', 'not null' => true, 'description' => 'when this token expires'], + 'access_token_id' => ['type' => 'char', 'length' => 64, 'foreign key' => true, 'description' => 'Actor foreign key'], + 'revoked' => ['type' => 'bool', 'not null' => true, 'foreign key' => true, 'description' => 'Whether this token is revoked'], + 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'], + ], + 'primary key' => ['id'], + ]; + } +} diff --git a/plugins/OAuth2/Entity/Token.php b/plugins/OAuth2/Entity/Token.php new file mode 100644 index 0000000000..11e105ae39 --- /dev/null +++ b/plugins/OAuth2/Entity/Token.php @@ -0,0 +1,149 @@ +. +// }}} + +/** + * OAuth2 Client + * + * @package GNUsocial + * + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Entity; + +use App\Core\Entity; +use Functional as F; +use League\OAuth2\Server\Entities\ClientEntityInterface; +use League\OAuth2\Server\Entities\ScopeEntityInterface; +use League\OAuth2\Server\Entities\TokenInterface; +use Plugin\OAuth2\Repository; + +abstract class Token extends Entity implements TokenInterface +{ + public function getIdentifier() + { + return $this->getId(); + } + + public function setIdentifier($identifier) + { + $this->setId($identifier); + } + + /** + * Get the token's expiry date time. + * + * @return DateTimeImmutable + */ + public function getExpiryDateTime() + { + return $this->getExpiry(); + } + + /** + * Set the date time when the token expires. + * + * @param DateTimeImmutable $dateTime + */ + public function setExpiryDateTime(\DateTimeImmutable $dateTime) + { + $this->setExpiry($dateTime); + } + + /** + * Set the identifier of the user associated with the token. + * + * @param null|int|string $identifier The identifier of the user + */ + public function setUserIdentifier($identifier) + { + $this->setUserId($identifier); + } + + /** + * Get the token user's identifier. + * + * @return null|int|string + */ + public function getUserIdentifier() + { + return $this->getUserId(); + } + + /** + * Get the client that the token was issued to. + * + * @return ClientEntityInterface + */ + public function getClient() + { + return (new Repository\Client)->getClientEntity($this->getClientId()); + } + + /** + * Set the client that the token was issued to. + */ + public function setClient(ClientEntityInterface $client) + { + $this->setClientId($client->getIdentifier()); + } + + /** + * Associate a scope with the token. + */ + public function addScope(ScopeEntityInterface $scope) + { + $scope = $this->hasTokenScopes() ? $this->getTokenScopes() . ' ' . $scope->getIdentifier() : $scope->getIdentifier(); + $this->setTokenScopes($scope); + } + + /** + * Return an array of scopes associated with the token. + * + * @return ScopeEntityInterface[] + */ + public function getScopes() + { + return F\map( + explode(' ', $this->getTokenScopes()), + fn (string $scope) => (new Repository\Scope)->getScopeEntityByIdentifier($scope), + ); + } + + public static function tokenSchema(string $table_name): array + { + return [ + 'name' => $table_name, + 'fields' => [ + 'id' => ['type' => 'char', 'length' => 64, 'not null' => true, 'description' => 'identifier for this token'], + 'expiry' => ['type' => 'datetime', 'not null' => true, 'description' => 'when this token expires'], + 'user_id' => ['type' => 'int', 'foreign key' => true, 'description' => 'Actor foreign key'], + 'client_id' => ['type' => 'char', 'length' => 64, 'not null' => true, 'foreign key' => true, 'description' => 'OAuth client foreign key'], + 'token_scopes' => ['type' => 'text', 'not null' => true, 'description' => 'Space separated scopes'], + 'revoked' => ['type' => 'bool', 'not null' => true, 'foreign key' => true, 'description' => 'Whether this token is revoked'], + 'created' => ['type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was created'], + ], + 'primary key' => ['id'], + ]; + } +} diff --git a/plugins/OAuth2/OAuth2.php b/plugins/OAuth2/OAuth2.php new file mode 100644 index 0000000000..fb6a18d912 --- /dev/null +++ b/plugins/OAuth2/OAuth2.php @@ -0,0 +1,108 @@ +. +// }}} + +/** + * ActivityPub implementation for GNU social + * + * @package GNUsocial + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2; + +use App\Core\Event; +use App\Core\Modules\Plugin; +use App\Core\Router\RouteLoader; +use App\Core\Router\Router; +use App\Util\Common; +use DateInterval; +use League\OAuth2\Server\AuthorizationServer; +use League\OAuth2\Server\CryptKey; +use League\OAuth2\Server\Grant\AuthCodeGrant; +use Plugin\OAuth2\Controller as C; +use XML_XRD_Element_Link; + +/** + * Adds OAuth2 support to GNU social when enabled + * + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ +class OAuth2 extends Plugin +{ + public const OAUTH_REQUEST_TOKEN_REL = 'http://apinamespace.org/oauth/request_token'; + public const OAUTH_ACCESS_TOKEN_REL = 'http://apinamespace.org/oauth/access_token'; + public const OAUTH_AUTHORIZE_REL = 'http://apinamespace.org/oauth/authorize'; + + public function version(): string + { + return '3.0.0'; + } + + public static ?AuthorizationServer $authorization_server = null; + public function onInitializePlugin() + { + self::$authorization_server = new AuthorizationServer( + new Repository\Client, + new Repository\AccessToken, + new Repository\Scope, + privateKey: new CryptKey(keyPath: Common::config('oauth2', 'private_key'), passPhrase: Common::config('oauth2', 'private_key_password')), + encryptionKey: Common::config('oauth2', 'encryption_key'), + ); + + self::$authorization_server->enableGrantType( + new AuthCodeGrant( + new Repository\AuthCode, + new Repository\RefreshToken, + new DateInterval('PT10M'), // ??? + ), + new DateInterval('PT1H'), + ); + } + + /** + * This code executes when GNU social creates the page routing, and we hook + * on this event to add our Inbox and Outbox handler for ActivityPub. + * + * @param RouteLoader $r the router that was initialized + */ + public function onAddRoute(RouteLoader $r): bool + { + $r->connect('oauth2_mastodon_api_apps', '/api/v1/apps', C\Client::class, ['http-methods' => ['POST']]); + $r->connect('oauth2_client', '/oauth/client', C\Client::class, ['http-methods' => ['POST']]); + $r->connect('oauth2_authorize', '/oauth/authorize', C\Authorize::class); + $r->connect('oauth2_token', '/oauth/token', C\Token::class); + return Event::next; + } + + public function onEndHostMetaLinks(array &$links): bool + { + $links[] = new XML_XRD_Element_link(self::OAUTH_REQUEST_TOKEN_REL, Router::url('oauth2_client', type: Router::ABSOLUTE_URL)); + $links[] = new XML_XRD_Element_link(self::OAUTH_AUTHORIZE_REL, Router::url('oauth2_authorize', type: Router::ABSOLUTE_URL)); + $links[] = new XML_XRD_Element_link(self::OAUTH_ACCESS_TOKEN_REL, Router::url('oauth2_token', type: Router::ABSOLUTE_URL)); + return Event::next; + } +} diff --git a/plugins/OAuth2/Repository/AccessToken.php b/plugins/OAuth2/Repository/AccessToken.php new file mode 100644 index 0000000000..2baa278561 --- /dev/null +++ b/plugins/OAuth2/Repository/AccessToken.php @@ -0,0 +1,75 @@ +. +// }}} + +/** + * OAuth2 implementation for GNU social + * + * @package OAuth2 + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Repository; + +use App\Core\DB\DB; +use League\OAuth2\Server\Entities\AccessTokenEntityInterface; +use League\OAuth2\Server\Entities\ClientEntityInterface; +use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface; +use Plugin\OAuth2\Entity; + +class AccessToken implements AccessTokenRepositoryInterface +{ + public function getAccessTokenEntity(string $identifier): Entity\AccessToken + { + return DB::findOneBy(Entity\AccessToken::class, ['id' => $identifier]); + } + + public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity) + { + DB::persist($accessTokenEntity); + } + + public function revokeAccessToken($tokenId) + { + // Some logic here to revoke the access token + } + + public function isAccessTokenRevoked($tokenId) + { + return false; // Access token hasn't been revoked + } + + public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null) + { + $accessToken = new Entity\AccessToken(); + $accessToken->setClient($clientEntity); + foreach ($scopes as $scope) { + $accessToken->addScope($scope); + } + $accessToken->setUserIdentifier($userIdentifier); + + return $accessToken; + } +} diff --git a/plugins/OAuth2/Repository/AuthCode.php b/plugins/OAuth2/Repository/AuthCode.php new file mode 100644 index 0000000000..251abac79d --- /dev/null +++ b/plugins/OAuth2/Repository/AuthCode.php @@ -0,0 +1,62 @@ +. +// }}} + +/** + * OAuth2 implementation for GNU social + * + * @package OAuth2 + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Repository; + +use App\Core\DB\DB; +use League\OAuth2\Server\Entities\AuthCodeEntityInterface; +use League\OAuth2\Server\Repositories\AuthCodeRepositoryInterface; +use Plugin\OAuth2\Entity; + +class AuthCode implements AuthCodeRepositoryInterface +{ + public function persistNewAuthCode(AuthCodeEntityInterface $authCodeEntity) + { + DB::persist($authCodeEntity); + } + + public function revokeAuthCode($codeId) + { + // Some logic to revoke the auth code in a database + } + + public function isAuthCodeRevoked($codeId) + { + return false; // The auth code has not been revoked + } + + public function getNewAuthCode() + { + return new Entity\AuthCode(); + } +} diff --git a/plugins/OAuth2/Repository/Client.php b/plugins/OAuth2/Repository/Client.php new file mode 100644 index 0000000000..572da197c1 --- /dev/null +++ b/plugins/OAuth2/Repository/Client.php @@ -0,0 +1,61 @@ +. +// }}} + +/** + * OAuth2 implementation for GNU social + * + * @package OAuth2 + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Repository; + +use App\Core\DB\DB; +use App\Util\Exception\NotFoundException; +use League\OAuth2\Server\Repositories\ClientRepositoryInterface; +use Plugin\OAuth2\Entity; + +class Client implements ClientRepositoryInterface +{ + public function getClientEntity($clientIdentifier) + { + return DB::findOneBy(Entity\Client::class, ['id' => $clientIdentifier]); + } + + public function validateClient($clientIdentifier, $clientSecret, $grantType) + { + try { + /** @var Entity\Client $client */ + $client = $this->getClientEntity($clientIdentifier); + if ($client->getIsConfidential() && $clientSecret !== $client->getSecret()) { + return false; + } + } catch (NotFoundException) { + return false; + } + return true; + } +} diff --git a/plugins/OAuth2/Repository/RefreshToken.php b/plugins/OAuth2/Repository/RefreshToken.php new file mode 100644 index 0000000000..efae3a9b79 --- /dev/null +++ b/plugins/OAuth2/Repository/RefreshToken.php @@ -0,0 +1,62 @@ +. +// }}} + +/** + * OAuth2 implementation for GNU social + * + * @package OAuth2 + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Repository; + +use App\Core\DB\DB; +use League\OAuth2\Server\Entities\RefreshTokenEntityInterface; +use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface; +use Plugin\OAuth2\Entity; + +class RefreshToken implements RefreshTokenRepositoryInterface +{ + public function persistNewRefreshToken(RefreshtokenEntityInterface $refreshtokenEntity) + { + DB::persist($refreshtokenEntity); + } + + public function revokeRefreshToken($tokenId) + { + // Some logic to revoke the auth token in a database + } + + public function isRefreshtokenRevoked($tokenId) + { + return false; // The auth token has not been revoked + } + + public function getNewRefreshToken() + { + return new Entity\RefreshToken(); + } +} diff --git a/plugins/OAuth2/Repository/Scope.php b/plugins/OAuth2/Repository/Scope.php new file mode 100644 index 0000000000..94f45f34ca --- /dev/null +++ b/plugins/OAuth2/Repository/Scope.php @@ -0,0 +1,92 @@ +. +// }}} + +/** + * OAuth2 implementation for GNU social + * + * @package OAuth2 + * @category API + * + * @author Diogo Peralta Cordeiro + * @author Hugo Sales + * @copyright 2022 Free Software Foundation, Inc http://www.fsf.org + * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later + */ + +namespace Plugin\OAuth2\Repository; + +use League\OAuth2\Server\Entities\ClientEntityInterface; +use League\OAuth2\Server\Entities\ScopeEntityInterface; +use League\OAuth2\Server\Repositories\ScopeRepositoryInterface; + +class Scope implements ScopeRepositoryInterface +{ + /** + * @return ?ScopeEntityInterface + */ + public function getScopeEntityByIdentifier($scopeIdentifier) + { + $scopes = [ + 'basic' => [ + 'description' => 'Basic details about you', + ], + 'email' => [ + 'description' => 'Your email address', + ], + 'read' => [ + 'description' => 'Read', + ], + 'write' => [ + 'description' => 'Read', + ], + 'follow' => [ + 'description' => 'Read', + ], + ]; + + if (\array_key_exists($scopeIdentifier, $scopes) === false) { + return; + } + + return new class($scopeIdentifier) implements ScopeEntityInterface { + public function __construct(private string $identifier) + { + } + public function getIdentifier() + { + return $this->identifier; + } + public function jsonSerialize(): mixed + { + return $this->getIdentifier(); + } + }; + } + + public function finalizeScopes( + array $scopes, + $grantType, + ClientEntityInterface $clientEntity, + $userIdentifier = null, + ) { + return $scopes; + } +} diff --git a/plugins/OAuth2/composer.json b/plugins/OAuth2/composer.json new file mode 100644 index 0000000000..89086e78ee --- /dev/null +++ b/plugins/OAuth2/composer.json @@ -0,0 +1,6 @@ +{ + "require": { + "league/oauth2-server": "*", + "nyholm/psr7": "*" + } +} diff --git a/plugins/OAuth2/config.yaml b/plugins/OAuth2/config.yaml new file mode 100644 index 0000000000..ed33902794 --- /dev/null +++ b/plugins/OAuth2/config.yaml @@ -0,0 +1,6 @@ +parameters: + oauth2: + private_key: '%kernel.project_dir%/file/oauth/private.key' + private_key_password: null + public_key: '%kernel.project_dir%/file/oauth/public.key' + encryption_key: 'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen' diff --git a/social.yaml b/social.yaml index 43dc65e436..11a612ad91 100644 --- a/social.yaml +++ b/social.yaml @@ -278,3 +278,9 @@ parameters: feeds: entries_per_page: 32 + + oauth2: + private_key: '%kernel.project_dir%/file/oauth/private.key' + private_key_password: null + public_key: '%kernel.project_dir%/file/oauth/public.key' + encryption_key: 'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen' diff --git a/symfony.lock b/symfony.lock index 1700d19cf3..e601bc3e0c 100644 --- a/symfony.lock +++ b/symfony.lock @@ -65,6 +65,9 @@ "composer/xdebug-handler": { "version": "1.4.6" }, + "defuse/php-encryption": { + "version": "v2.3.1" + }, "doctrine/annotations": { "version": "1.0", "recipe": { @@ -223,6 +226,18 @@ "landrok/activitypub": { "version": "0.5.6" }, + "lcobucci/clock": { + "version": "2.1.0" + }, + "lcobucci/jwt": { + "version": "4.1.5" + }, + "league/event": { + "version": "2.2.0" + }, + "league/oauth2-server": { + "version": "8.3.3" + }, "league/uri-parser": { "version": "1.4.1" },