diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 7975076d..b3bcff2c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -17,13 +17,9 @@ jobs: fail-fast: false matrix: php: [ 8.3, 8.4, 8.5 ] - laravel: [ 11.*, 12.*, 13.* ] + laravel: [ 12.*, 13.* ] dependency-version: [ stable, lowest ] include: - # orchestra/testbench below 9.2 sets a static property it never declares, - # which fails every test, so the Laravel 11 floor starts there - - laravel: 11.* - testbench: ^9.2 - laravel: 12.* testbench: ^10.0 - laravel: 13.* diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ac7e6ec..e5f51a47 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ format. This project adheres to [Semantic Versioning](https://semver.org/spec/v2 ## [Unreleased] +### Added + +- Sign in as a Linear OAuth app with the client credentials grant (`LINEAR_CLIENT_ID`, `LINEAR_CLIENT_SECRET`, `LINEAR_SCOPES`). The app token is cached until it expires, and replaced when Linear rejects it. + +### Removed + +- Laravel 11 support. Every Laravel 11 release now has unpatched security advisories, so Composer refuses to install it. + ## [0.1.2] - 2026-09-20 ### Added diff --git a/README.md b/README.md index 89e4ebcc..02acf3a3 100644 --- a/README.md +++ b/README.md @@ -40,14 +40,32 @@ Linear changes their schema. composer require glhd/linearavel ``` -Then add your API key to your `.env` file: +Then add your personal API key to your `.env` file: ```dotenv LINEAR_API_KEY=lin_api_... ``` You can create a key under **Settings → Security & access → Personal API keys** in -Linear. To publish the config file: +Linear. + +To act as an app instead of as your own user, create an OAuth application in Linear +(**Settings → API → OAuth applications**), turn on **Client credentials**, and add +its credentials in place of a personal API key. Linear requires a redirect URI when +you create the app, but the client credentials grant never uses it, so any URL on +your own domain will do. + +```dotenv +LINEAR_CLIENT_ID=... +LINEAR_CLIENT_SECRET=... +LINEAR_SCOPES=read,write +``` + +Linearavel requests an app token with the client credentials grant and keeps it in +your application cache until it expires (30 days). If Linear rejects the token, +Linearavel fetches a new one and sends the request again. + +To publish the config file: ```shell php artisan vendor:publish --tag=linearavel-config diff --git a/composer.json b/composer.json index 11473609..23e4330b 100755 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "require": { "php": "^8.3", "ext-json": "*", - "illuminate/support": "^11.0|^12.0|^13.0", + "illuminate/support": "^12.0|^13.0", "guzzlehttp/guzzle": "^7.8|^8.0", "nikic/php-parser": "^5.0", "saloonphp/saloon": "^4.0", @@ -29,7 +29,7 @@ "require-dev": { "friendsofphp/php-cs-fixer": "^3.34", "mockery/mockery": "^1.6", - "orchestra/testbench": "^9.2|^10.0|^11.0", + "orchestra/testbench": "^10.0|^11.0", "phpunit/phpunit": "^10.3|^11.0|^12.0|^13.0" }, "autoload": { diff --git a/config/linearavel.php b/config/linearavel.php index fde141cc..5ee75d3b 100644 --- a/config/linearavel.php +++ b/config/linearavel.php @@ -12,4 +12,20 @@ 'api_key' => env('LINEAR_API_KEY'), 'base_url' => env('LINEAR_BASE_URL', 'https://api.linear.app/graphql'), + + /* + |-------------------------------------------------------------------------- + | OAuth app (client credentials) + |-------------------------------------------------------------------------- + | + | To act as an OAuth app instead of a user, turn on "Client credentials + | tokens" for the app in Linear and set its client ID and secret. When a + | client ID is set, it's used in place of the API key. Scopes are a + | comma-separated list. + | + */ + + 'client_id' => env('LINEAR_CLIENT_ID'), + 'client_secret' => env('LINEAR_CLIENT_SECRET'), + 'scopes' => env('LINEAR_SCOPES', 'read,write'), ]; diff --git a/src/Connectors/LinearConnector.php b/src/Connectors/LinearConnector.php index 232b525c..0c1b9e47 100644 --- a/src/Connectors/LinearConnector.php +++ b/src/Connectors/LinearConnector.php @@ -4,8 +4,11 @@ use Glhd\Linearavel\Exceptions\LinearRequestException; use Saloon\Contracts\Authenticator; +use Saloon\Exceptions\Request\FatalRequestException; +use Saloon\Exceptions\Request\RequestException; use Saloon\Http\Auth\TokenAuthenticator; use Saloon\Http\Connector; +use Saloon\Http\Request; use Saloon\Http\Response; use Throwable; @@ -15,9 +18,13 @@ class LinearConnector extends Connector use MutatesLinear; public function __construct( - protected string $api_key, + protected ?string $api_key = null, protected string $base_url = 'https://api.linear.app/graphql', + protected ?LinearOAuthConnector $oauth = null, ) { + if ($this->oauth) { + $this->tries = 2; + } } public function resolveBaseUrl(): string @@ -49,8 +56,26 @@ public function getRequestException(Response $response, ?Throwable $senderExcept return null; } + public function handleRetry(FatalRequestException|RequestException $exception, Request $request): bool + { + $was_unauthorized = $exception instanceof RequestException && 401 === $exception->getResponse()->status(); + $was_graphql_request = $exception->getPendingRequest()->getConnector() === $this; + + if ($was_unauthorized && $was_graphql_request) { + $this->oauth?->forgetAccessToken(); + + return true; + } + + return false; + } + protected function defaultAuth(): ?Authenticator { + if ($this->oauth) { + return new TokenAuthenticator($this->oauth->accessToken()); + } + return new TokenAuthenticator($this->api_key, prefix: ''); } diff --git a/src/Connectors/LinearOAuthConnector.php b/src/Connectors/LinearOAuthConnector.php new file mode 100644 index 00000000..adafcbb3 --- /dev/null +++ b/src/Connectors/LinearOAuthConnector.php @@ -0,0 +1,59 @@ + $scopes */ + public function __construct( + protected string $client_id, + protected string $client_secret, + protected array $scopes, + ) { + } + + public function resolveBaseUrl(): string + { + return 'https://api.linear.app'; + } + + public function accessToken(): string + { + if ($token = Cache::get($this->cacheKey())) { + return $token; + } + + $authenticator = $this->getAccessToken($this->scopes, ','); + + Cache::put($this->cacheKey(), $authenticator->getAccessToken(), $authenticator->getExpiresAt()?->modify('-1 hour')); + + return $authenticator->getAccessToken(); + } + + public function forgetAccessToken(): void + { + Cache::forget($this->cacheKey()); + } + + protected function defaultOauthConfig(): OAuthConfig + { + return OAuthConfig::make() + ->setClientId($this->client_id) + ->setClientSecret($this->client_secret) + ->setTokenEndpoint('/oauth/token'); + } + + protected function cacheKey(): string + { + return 'linearavel:access-token:'.sha1($this->client_id.'|'.implode(',', $this->scopes)); + } +} diff --git a/src/Support/LinearavelServiceProvider.php b/src/Support/LinearavelServiceProvider.php index 595ebf85..da58f505 100755 --- a/src/Support/LinearavelServiceProvider.php +++ b/src/Support/LinearavelServiceProvider.php @@ -3,6 +3,7 @@ namespace Glhd\Linearavel\Support; use Glhd\Linearavel\Connectors\LinearConnector; +use Glhd\Linearavel\Connectors\LinearOAuthConnector; use Glhd\Linearavel\Support\CodeGeneration\PhpStormMetaWriter; use Glhd\Linearavel\Support\CodeGeneration\WriteQueue; use Illuminate\Support\ServiceProvider; @@ -22,6 +23,11 @@ public function register() return new LinearConnector( api_key: config('linearavel.api_key'), base_url: config('linearavel.base_url', 'https://api.linear.app/graphql'), + oauth: config('linearavel.client_id') ? new LinearOAuthConnector( + client_id: config('linearavel.client_id'), + client_secret: config('linearavel.client_secret'), + scopes: array_map('trim', explode(',', config('linearavel.scopes'))), + ) : null, ); }); diff --git a/tests/Feature/ClientCredentialsTest.php b/tests/Feature/ClientCredentialsTest.php new file mode 100644 index 00000000..65362bf6 --- /dev/null +++ b/tests/Feature/ClientCredentialsTest.php @@ -0,0 +1,118 @@ + null, + 'linearavel.client_id' => 'client-id', + 'linearavel.client_secret' => 'client-secret', + ]); + } + + public function test_it_signs_in_as_the_app_with_a_client_credentials_token(): void + { + MockClient::global([ + GetClientCredentialsTokenRequest::class => $this->token('app-token'), + LinearRequest::class => $this->viewer(), + ]); + + $this->assertSame('app-user', linear()->viewer()->get('id')->id); + + $this->assertSaloonSent(fn(Request $request) => $request instanceof GetClientCredentialsTokenRequest + && 'client_credentials' === $request->body()->get('grant_type') + && 'client-id' === $request->body()->get('client_id') + && 'client-secret' === $request->body()->get('client_secret') + && 'read,write' === $request->body()->get('scope')); + + $this->assertSaloonSent(fn(Request $request, Response $response) => $request instanceof LinearRequest + && 'Bearer app-token' === $response->getPendingRequest()->headers()->get('Authorization')); + } + + public function test_the_token_is_reused_for_later_requests(): void + { + MockClient::global([ + GetClientCredentialsTokenRequest::class => $this->token('app-token'), + LinearRequest::class => $this->viewer(), + ]); + + linear()->viewer()->get('id'); + linear()->viewer()->get('id'); + + MockClient::getGlobal()->assertSentCount(1, GetClientCredentialsTokenRequest::class); + MockClient::getGlobal()->assertSentCount(2, LinearRequest::class); + } + + public function test_a_rejected_token_is_replaced_and_the_request_is_sent_again(): void + { + MockClient::global([ + $this->token('revoked-token'), + MockResponse::make(['errors' => [['message' => 'Authentication required, not authenticated', 'extensions' => ['code' => 'AUTHENTICATION_ERROR']]]], 401), + $this->token('new-token'), + $this->viewer(), + ]); + + $this->assertSame('app-user', linear()->viewer()->get('id')->id); + + $this->assertSaloonSent(fn(Request $request, Response $response) => $request instanceof LinearRequest + && $response->successful() + && 'Bearer new-token' === $response->getPendingRequest()->headers()->get('Authorization')); + } + + public function test_a_rejected_client_secret_is_not_retried(): void + { + MockClient::global([ + GetClientCredentialsTokenRequest::class => MockResponse::make(['error' => 'invalid_client'], 401), + ]); + + try { + linear()->viewer()->get('id'); + $this->fail('Expected the token request to fail.'); + } catch (RequestException) { + } + + MockClient::getGlobal()->assertSentCount(1, GetClientCredentialsTokenRequest::class); + } + + public function test_a_personal_api_key_is_sent_without_a_bearer_prefix(): void + { + config(['linearavel.api_key' => 'lin_api_key', 'linearavel.client_id' => null]); + + MockClient::global([LinearRequest::class => $this->viewer()]); + + linear()->viewer()->get('id'); + + $this->assertSaloonSent(fn(Request $request, Response $response) => 'lin_api_key' === $response->getPendingRequest()->headers()->get('Authorization')); + } + + protected function token(string $access_token): MockResponse + { + return MockResponse::make([ + 'access_token' => $access_token, + 'token_type' => 'Bearer', + 'expires_in' => 2591999, + 'scope' => 'read write', + ]); + } + + protected function viewer(): MockResponse + { + return MockResponse::make(['data' => ['viewer' => ['id' => 'app-user']]]); + } +}