A free open source IT asset/license management system
feat: accept federated OIDC bearer tokens on the API (provider-agnostic SSO)
Rod Christiansencc37d57928c1
diff --git a/app/Auth/OidcGuard.php b/app/Auth/OidcGuard.phpnew file mode 100644index 0000000000..8ad770c24a--- /dev/null+++ b/app/Auth/OidcGuard.php@@ -0,0 +1,88 @@+<?php++namespace App\Auth;++use App\Services\Oidc\OidcTokenValidator;+use App\Services\Oidc\OidcUserResolver;+use Illuminate\Auth\GuardHelpers;+use Illuminate\Contracts\Auth\Guard;+use Illuminate\Contracts\Auth\UserProvider;+use Illuminate\Http\Request;++/**+ * Stateless bearer-token guard: validates an `Authorization: Bearer <jwt>`+ * against a trusted OIDC provider and resolves it to a Snipe-IT user. Returns+ * null on any failure so the framework produces a normal 401.+ *+ * Registered as the `oidc` driver in config/auth.php and layered alongside+ * Passport via the `auth:api,oidc` multi-guard, so a route accepts either an+ * OIDC token or a Passport token. Inert until config('oidc.enabled') is true.+ */+class OidcGuard implements Guard+{+ use GuardHelpers;++ protected Request $request;++ protected OidcTokenValidator $validator;++ protected OidcUserResolver $resolver;++ public function __construct(+ UserProvider $provider,+ Request $request,+ OidcTokenValidator $validator,+ OidcUserResolver $resolver+ ) {+ $this->provider = $provider;+ $this->request = $request;+ $this->validator = $validator;+ $this->resolver = $resolver;+ }++ public function user()+ {+ if (! is_null($this->user)) {+ return $this->user;+ }++ if (! config('oidc.enabled')) {+ return null;+ }++ $token = $this->bearerToken();+ if ($token === null) {+ return null;+ }++ $claims = $this->validator->validate($token);+ if ($claims === null) {+ return null;+ }++ return $this->user = $this->resolver->resolve($claims);+ }++ public function validate(array $credentials = [])+ {+ if (empty($credentials['token'])) {+ return false;+ }++ $claims = $this->validator->validate($credentials['token']);++ return $claims !== null && $this->resolver->resolve($claims) !== null;+ }++ protected function bearerToken(): ?string+ {+ $header = (string) $this->request->header('Authorization', '');+ if (stripos($header, 'bearer ') !== 0) {+ return null;+ }++ $token = trim(substr($header, 7));++ return $token !== '' ? $token : null;+ }+}diff --git a/app/Http/Kernel.php b/app/Http/Kernel.phpindex 9856d29f71..82b9419801 100644--- a/app/Http/Kernel.php+++ b/app/Http/Kernel.php@@ -82,7 +82,7 @@ class Kernel extends HttpKernel],'api' => [- 'auth:api',+ 'auth:api,oidc',CheckUserIsActivated::class,EnforceApiTwoFactorEnrollment::class,EnforceApiUserAgent::class,diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.phpindex 6cd6ae8915..595b3d2174 100644--- a/app/Providers/AuthServiceProvider.php+++ b/app/Providers/AuthServiceProvider.php@@ -44,6 +44,7 @@ use App\Policies\SupplierPolicy;use App\Policies\UserPolicy;use Carbon\CarbonInterval;use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;+use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Gate;use Laravel\Passport\Console\ClientCommand;use Laravel\Passport\Console\InstallCommand;@@ -103,6 +104,18 @@ class AuthServiceProvider extends ServiceProviderPassport::cookie(config('passport.cookie_name'));+ // Federated identity: a provider-agnostic OIDC bearer guard, layered+ // alongside Passport via the `auth:api,oidc` multi-guard. Inert until+ // config('oidc.enabled') is true, so this is purely additive.+ Auth::extend('oidc', function ($app, $name, array $config) {+ return new \App\Auth\OidcGuard(+ Auth::createUserProvider($config['provider']),+ $app['request'],+ $app->make(\App\Services\Oidc\OidcTokenValidator::class),+ $app->make(\App\Services\Oidc\OidcUserResolver::class),+ );+ });+/*** BEFORE ANYTHING ELSE*diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.phpindex bccde92d03..758068b268 100644--- a/app/Providers/RouteServiceProvider.php+++ b/app/Providers/RouteServiceProvider.php@@ -65,7 +65,7 @@ class RouteServiceProvider extends ServiceProviderprotected function mapApiRoutes(){Route::group([- 'middleware' => 'auth:api',+ 'middleware' => 'auth:api,oidc',// 'namespace' => $this->namespace, // this might also be a problem? I don't really know :/'prefix' => 'api',], function ($router) {diff --git a/app/Services/Oidc/OidcTokenValidator.php b/app/Services/Oidc/OidcTokenValidator.phpnew file mode 100644index 0000000000..6c51472fc3--- /dev/null+++ b/app/Services/Oidc/OidcTokenValidator.php@@ -0,0 +1,118 @@+<?php++namespace App\Services\Oidc;++use Firebase\JWT\JWK;+use Firebase\JWT\JWT;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Log;++/**+ * Validates an OIDC JWT (asymmetric RS/ES algorithms only) against the+ * configured trusted issuer(s), audience(s) and JWKS. Returns the claims or+ * null on any failure -- callers never learn *why* (no error oracle); failures+ * are logged server-side.+ *+ * Signing keys are discovered per issuer and cached, so validation does not hit+ * the provider on every request. `signingKeys()` is isolated so tests can seed+ * a local key without a network round-trip.+ */+class OidcTokenValidator+{+ public function validate(string $token): ?array+ {+ $issuers = (array) config('oidc.issuers');+ $audiences = (array) config('oidc.audiences');++ if (empty($issuers) || empty($audiences)) {+ return null;+ }++ // Read the (unverified) issuer first so we can reject untrusted issuers+ // before any crypto, and select the right JWKS for a multi-issuer+ // deployment. The signature is still fully verified below.+ $issuer = $this->unverifiedIssuer($token);+ if ($issuer === null || ! in_array($issuer, $issuers, true)) {+ Log::warning('[OIDC] Rejected bearer token from untrusted issuer', ['iss' => $issuer]);++ return null;+ }++ try {+ $keys = $this->signingKeys($issuer);+ JWT::$leeway = (int) config('oidc.leeway', 60);+ $decoded = (array) JWT::decode($token, $keys);+ } catch (\Throwable $e) {+ Log::warning('[OIDC] Bearer validation failed', ['error' => $e->getMessage()]);++ return null;+ }++ // php-jwt verifies the signature + exp/nbf, but not iss/aud -- do those+ // explicitly.+ if (($decoded['iss'] ?? null) !== $issuer) {+ return null;+ }++ if (! $this->audienceMatches($decoded, $audiences)) {+ Log::warning('[OIDC] Rejected bearer token: audience mismatch');++ return null;+ }++ return $decoded;+ }++ protected function unverifiedIssuer(string $token): ?string+ {+ $parts = explode('.', $token);+ if (count($parts) !== 3) {+ return null;+ }++ $payload = json_decode(JWT::urlsafeB64Decode($parts[1]), true);++ return is_array($payload) ? ($payload['iss'] ?? null) : null;+ }++ protected function audienceMatches(array $claims, array $audiences): bool+ {+ $aud = $claims['aud'] ?? null;+ $presented = is_array($aud) ? $aud : [$aud];++ return count(array_intersect($presented, $audiences)) > 0;+ }++ /**+ * Resolve and cache the issuer's signing keys as Firebase\JWT\Key objects.+ * JWKS documents only carry asymmetric public keys, so `none`/HS* can never+ * enter here -- algorithm confusion is structurally impossible.+ */+ protected function signingKeys(string $issuer): array+ {+ $jwksUri = config('oidc.jwks_uri') ?: $this->discoverJwksUri($issuer);+ $defaultAlg = config('oidc.algorithms')[0] ?? 'RS256';++ $jwks = Cache::remember('oidc_jwks_'.md5($jwksUri), 3600, function () use ($jwksUri) {+ return Http::timeout(5)->get($jwksUri)->throw()->json();+ });++ return JWK::parseKeySet($jwks, $defaultAlg);+ }++ protected function discoverJwksUri(string $issuer): string+ {+ $wellKnown = rtrim($issuer, '/').'/.well-known/openid-configuration';++ $doc = Cache::remember('oidc_disco_'.md5($issuer), 3600, function () use ($wellKnown) {+ return Http::timeout(5)->get($wellKnown)->throw()->json();+ });++ if (empty($doc['jwks_uri'])) {+ throw new \RuntimeException('OIDC discovery for '.$issuer.' has no jwks_uri');+ }++ return $doc['jwks_uri'];+ }+}diff --git a/app/Services/Oidc/OidcUserResolver.php b/app/Services/Oidc/OidcUserResolver.phpnew file mode 100644index 0000000000..360508ac12--- /dev/null+++ b/app/Services/Oidc/OidcUserResolver.php@@ -0,0 +1,76 @@+<?php++namespace App\Services\Oidc;++use App\Models\User;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Str;++/**+ * Maps a validated OIDC token's claims to an existing Snipe-IT user. The+ * matched user's own permissions then apply unchanged -- this class grants no+ * privileges of its own.+ *+ * Lookup mirrors the SAML path (by username, active + not soft-deleted). Unknown+ * users are rejected unless just-in-time provisioning is explicitly enabled, in+ * which case they are created with no extra permissions.+ */+class OidcUserResolver+{+ public function resolve(array $claims): ?User+ {+ $username = $this->usernameFromClaims($claims);+ if (empty($username)) {+ Log::warning('[OIDC] Token carries no usable username claim');++ return null;+ }++ $user = User::where('username', '=', $username)+ ->whereNull('deleted_at')+ ->where('activated', '=', '1')+ ->first();++ if ($user) {+ return $user;+ }++ if (config('oidc.provision')) {+ return $this->provision($claims, $username);+ }++ Log::warning('[OIDC] No active Snipe-IT user for token', ['username' => $username]);++ return null;+ }++ protected function usernameFromClaims(array $claims): ?string+ {+ $claimName = config('oidc.username_claim', 'preferred_username');++ foreach ([$claimName, 'preferred_username', 'upn', 'email'] as $candidate) {+ if (! empty($claims[$candidate])) {+ return $claims[$candidate];+ }+ }++ return null;+ }++ protected function provision(array $claims, string $username): ?User+ {+ $user = new User;+ $user->username = $username;+ $user->email = $claims['email'] ?? '';+ $user->first_name = $claims['given_name'] ?? $username;+ $user->last_name = $claims['family_name'] ?? '';+ $user->activated = 1;+ // Random unusable password -- these users authenticate only via OIDC.+ $user->password = bcrypt(Str::random(40));+ $user->save();++ Log::info('[OIDC] Just-in-time provisioned Snipe-IT user', ['username' => $username]);++ return $user;+ }+}diff --git a/config/auth.php b/config/auth.phpindex ad771e5896..8971c8eace 100644--- a/config/auth.php+++ b/config/auth.php@@ -48,6 +48,13 @@ return ['provider' => 'users','hash' => false,],++ // Federated OIDC bearer guard (see config/oidc.php). Layered with+ // Passport via `auth:api,oidc`; inert until OIDC is configured.+ 'oidc' => [+ 'driver' => 'oidc',+ 'provider' => 'users',+ ],],/*diff --git a/config/oidc.php b/config/oidc.phpnew file mode 100644index 0000000000..035ee27248--- /dev/null+++ b/config/oidc.php@@ -0,0 +1,62 @@+<?php++/*+|--------------------------------------------------------------------------+| OIDC API bearer authentication+|--------------------------------------------------------------------------+|+| Lets the Snipe-IT API accept a short-lived JWT issued by an external OpenID+| Connect provider (Microsoft Entra, Okta, Auth0, Keycloak, Google, ...) as a+| `Authorization: Bearer` credential, in addition to Passport tokens. The token+| is validated against the configured issuer(s)/audience/JWKS and mapped to an+| existing Snipe-IT user, whose own permissions then apply unchanged.+|+| Provider-agnostic and inert until configured: with OIDC_API_ENABLED unset (or+| no issuers/audience), the guard authenticates nothing and Passport keeps+| working exactly as before.+|+*/++return [++ // Master switch. The guard is a no-op until this is true AND issuers ++ // audience are configured.+ 'enabled' => env('OIDC_API_ENABLED', false),++ // Comma-separated list of trusted token issuers (the `iss` claim).+ // Entra v2: https://login.microsoftonline.com/<tenant-id>/v2.0+ 'issuers' => array_values(array_filter(array_map(+ 'trim',+ explode(',', (string) env('OIDC_API_ISSUERS', ''))+ ))),++ // Comma-separated list of accepted audiences (the `aud` claim). Usually the+ // API app registration's client id and/or its App ID URI (api://<id>).+ 'audiences' => array_values(array_filter(array_map(+ 'trim',+ explode(',', (string) env('OIDC_API_AUDIENCE', ''))+ ))),++ // Optional explicit JWKS endpoint. When empty, it is discovered from each+ // issuer's /.well-known/openid-configuration document.+ 'jwks_uri' => env('OIDC_API_JWKS_URI') ?: null,++ // Accepted signing algorithms. Asymmetric only -- `none` and HS* are never+ // accepted (they would enable algorithm-confusion attacks).+ 'algorithms' => array_values(array_filter(array_map(+ 'trim',+ explode(',', (string) env('OIDC_API_ALGORITHMS', 'RS256,RS384,RS512,ES256'))+ ))),++ // Token claim used to match a Snipe-IT user by username. Entra: the UPN+ // arrives in `preferred_username`.+ 'username_claim' => env('OIDC_API_USERNAME_CLAIM', 'preferred_username'),++ // Just-in-time provisioning of unknown users. Off by default; when on, a new+ // user is created with no extra permissions (an admin grants them after).+ 'provision' => env('OIDC_API_PROVISION', false),++ // Clock-skew leeway (seconds) for exp/nbf validation.+ 'leeway' => (int) env('OIDC_API_LEEWAY', 60),++];diff --git a/tests/Feature/Authentication/OidcApiAuthTest.php b/tests/Feature/Authentication/OidcApiAuthTest.phpnew file mode 100644index 0000000000..5dc52dcc1c--- /dev/null+++ b/tests/Feature/Authentication/OidcApiAuthTest.php@@ -0,0 +1,177 @@+<?php++namespace Tests\Feature\Authentication;++use App\Models\User;+use Firebase\JWT\JWT;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\Route;+use Laravel\Passport\Passport;+use Tests\TestCase;++/**+ * Provider-agnostic OIDC bearer authentication for the API. Exercised through a+ * throwaway route under the real `auth:api,oidc` multi-guard, with JWTs signed+ * by a local RSA keypair and the JWKS seeded into the cache -- so these tests+ * never touch a network or a real IdP.+ */+class OidcApiAuthTest extends TestCase+{+ private string $issuer = 'https://issuer.test/v2.0';++ private string $audience = 'api://snipe-test';++ private string $jwksUri = 'https://issuer.test/discovery/keys';++ private string $kid = 'test-key-1';++ private string $privatePem;++ protected function setUp(): void+ {+ parent::setUp();++ $res = openssl_pkey_new([+ 'private_key_bits' => 2048,+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,+ ]);+ openssl_pkey_export($res, $this->privatePem);+ $details = openssl_pkey_get_details($res);++ $jwks = ['keys' => [[+ 'kty' => 'RSA',+ 'use' => 'sig',+ 'alg' => 'RS256',+ 'kid' => $this->kid,+ 'n' => $this->b64url($details['rsa']['n']),+ 'e' => $this->b64url($details['rsa']['e']),+ ]]];++ config([+ 'oidc.enabled' => true,+ 'oidc.issuers' => [$this->issuer],+ 'oidc.audiences' => [$this->audience],+ 'oidc.jwks_uri' => $this->jwksUri,+ 'oidc.algorithms' => ['RS256'],+ 'oidc.username_claim' => 'preferred_username',+ 'oidc.provision' => false,+ 'oidc.leeway' => 60,+ ]);++ // Seed the signing keys so the validator never fetches over the network.+ Cache::put('oidc_jwks_'.md5($this->jwksUri), $jwks, 3600);++ Route::middleware('auth:api,oidc')->get('/_test/oidc-whoami', function () {+ return response()->json(['username' => auth()->user()->username]);+ });+ }++ private function b64url(string $bin): string+ {+ return rtrim(strtr(base64_encode($bin), '+/', '-_'), '=');+ }++ private function token(array $overrides = []): string+ {+ $now = time();+ $payload = array_merge([+ 'iss' => $this->issuer,+ 'aud' => $this->audience,+ 'sub' => 'subject-123',+ 'preferred_username' => 'oidcuser',+ 'iat' => $now,+ 'nbf' => $now,+ 'exp' => $now + 3600,+ ], $overrides);++ return JWT::encode($payload, $this->privatePem, 'RS256', $this->kid);+ }++ private function bearer(string $token): array+ {+ return ['Authorization' => 'Bearer '.$token];+ }++ public function test_valid_token_authenticates_the_matching_user()+ {+ User::factory()->create(['username' => 'oidcuser', 'activated' => 1]);++ $this->withHeaders($this->bearer($this->token()))+ ->getJson('/_test/oidc-whoami')+ ->assertOk()+ ->assertJson(['username' => 'oidcuser']);+ }++ public function test_bearer_is_ignored_when_oidc_is_disabled()+ {+ config(['oidc.enabled' => false]);+ User::factory()->create(['username' => 'oidcuser', 'activated' => 1]);++ $this->withHeaders($this->bearer($this->token()))+ ->getJson('/_test/oidc-whoami')+ ->assertUnauthorized();+ }++ public function test_unknown_user_is_rejected()+ {+ $this->withHeaders($this->bearer($this->token(['preferred_username' => 'ghost'])))+ ->getJson('/_test/oidc-whoami')+ ->assertUnauthorized();+ }++ public function test_deactivated_user_is_rejected()+ {+ User::factory()->create(['username' => 'oidcuser', 'activated' => 0]);++ $this->withHeaders($this->bearer($this->token()))+ ->getJson('/_test/oidc-whoami')+ ->assertUnauthorized();+ }++ public function test_wrong_audience_is_rejected()+ {+ User::factory()->create(['username' => 'oidcuser', 'activated' => 1]);++ $this->withHeaders($this->bearer($this->token(['aud' => 'api://someone-else'])))+ ->getJson('/_test/oidc-whoami')+ ->assertUnauthorized();+ }++ public function test_untrusted_issuer_is_rejected()+ {+ User::factory()->create(['username' => 'oidcuser', 'activated' => 1]);++ $this->withHeaders($this->bearer($this->token(['iss' => 'https://evil.test/v2.0'])))+ ->getJson('/_test/oidc-whoami')+ ->assertUnauthorized();+ }++ public function test_expired_token_is_rejected()+ {+ User::factory()->create(['username' => 'oidcuser', 'activated' => 1]);+ $past = time() - 300;++ $this->withHeaders($this->bearer($this->token(['iat' => $past, 'nbf' => $past, 'exp' => $past + 60])))+ ->getJson('/_test/oidc-whoami')+ ->assertUnauthorized();+ }++ public function test_malformed_bearer_is_rejected()+ {+ $this->withHeaders($this->bearer('not-a-jwt'))+ ->getJson('/_test/oidc-whoami')+ ->assertUnauthorized();+ }++ public function test_passport_token_still_authenticates_via_multiguard()+ {+ // The oidc guard must not break the existing Passport path: a route+ // under auth:api,oidc still authenticates a Passport-acting user.+ $user = User::factory()->create(['activated' => 1]);+ Passport::actingAs($user);++ $this->getJson('/_test/oidc-whoami')+ ->assertOk()+ ->assertJson(['username' => $user->username]);+ }+}