-
Notifications
You must be signed in to change notification settings - Fork 229
feat(payments-next): add OAuth strategy guard #20352
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| { | ||
| "extends": ["../../../.eslintrc.json"], | ||
| "ignorePatterns": ["!**/*"], | ||
| "overrides": [ | ||
| { | ||
| "files": ["*.ts", "*.tsx", "*.js", "*.jsx"], | ||
| "rules": {} | ||
| }, | ||
| { | ||
| "files": ["*.ts", "*.tsx"], | ||
| "rules": {} | ||
| }, | ||
| { | ||
| "files": ["*.js", "*.jsx"], | ||
| "rules": {} | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| export default { | ||
| displayName: 'payments-auth', | ||
| preset: '../../../jest.preset.js', | ||
| testEnvironment: 'node', | ||
| transform: { | ||
| '^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }], | ||
| }, | ||
| moduleFileExtensions: ['ts', 'js', 'html'], | ||
| coverageDirectory: '../../../coverage/libs/payments/auth', | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| { | ||
| "name": "@fxa/payments/auth", | ||
| "version": "0.0.1" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| { | ||
| "name": "payments-auth", | ||
| "$schema": "../../../node_modules/nx/schemas/project-schema.json", | ||
| "sourceRoot": "libs/payments/auth/src", | ||
| "projectType": "library", | ||
| "tags": [], | ||
| "targets": { | ||
| "build": { | ||
| "executor": "@nx/esbuild:esbuild", | ||
| "outputs": ["{options.outputPath}"], | ||
| "options": { | ||
| "outputPath": "dist/libs/payments/auth", | ||
| "main": "libs/payments/auth/src/index.ts", | ||
| "tsConfig": "libs/payments/auth/tsconfig.lib.json", | ||
| "assets": ["libs/payments/auth/*.md"], | ||
| "format": ["cjs"] | ||
| } | ||
| }, | ||
| "test-unit": { | ||
| "executor": "@nx/jest:jest", | ||
| "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], | ||
| "options": { | ||
| "jestConfig": "libs/payments/auth/jest.config.ts" | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| export * from './lib/auth.module'; | ||
| export * from './lib/fxa-oauth-auth.guard'; | ||
| export * from './lib/fxa-access-token.schemas'; | ||
| export * from './lib/fxa-oauth.config'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { Module } from '@nestjs/common'; | ||
|
|
||
| import { FxaOAuthJwtStrategy } from './fxa-oauth-jwt.strategy'; | ||
| import { FxaOAuthVerifyStrategy } from './fxa-oauth-verify.strategy'; | ||
|
|
||
| @Module({ | ||
| providers: [FxaOAuthJwtStrategy, FxaOAuthVerifyStrategy], | ||
| exports: [FxaOAuthJwtStrategy, FxaOAuthVerifyStrategy], | ||
| }) | ||
| export class AuthModule {} |
15 changes: 15 additions & 0 deletions
15
libs/payments/auth/src/lib/factories/fxa-access-token-claims.factory.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { faker } from '@faker-js/faker'; | ||
| import { FxaAccessTokenClaims } from '../fxa-access-token.schemas'; | ||
|
|
||
| export const FxaAccessTokenClaimsFactory = ( | ||
| override?: Partial<FxaAccessTokenClaims> | ||
| ): FxaAccessTokenClaims => ({ | ||
| sub: faker.string.hexadecimal({ length: 32, prefix: '' }), | ||
| client_id: faker.string.hexadecimal({ length: 16, prefix: '' }), | ||
| scope: 'profile', | ||
| ...override, | ||
| }); |
15 changes: 15 additions & 0 deletions
15
libs/payments/auth/src/lib/factories/verify-response.factory.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { faker } from '@faker-js/faker'; | ||
| import { FxaVerifyResponse } from '../fxa-access-token.schemas'; | ||
|
|
||
| export const FxaVerifyResponseFactory = ( | ||
| override?: Partial<FxaVerifyResponse> | ||
| ): FxaVerifyResponse => ({ | ||
| user: faker.string.hexadecimal({ length: 32, prefix: '' }), | ||
| client_id: faker.string.hexadecimal({ length: 16, prefix: '' }), | ||
| scope: ['profile'], | ||
| ...override, | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { z } from 'zod'; | ||
|
|
||
| /** | ||
| * Common user identity returned by both FxA OAuth strategies. | ||
| * Contains only the fields reliably available from both JWT and | ||
| * opaque-token verification paths. | ||
| */ | ||
| export const fxaOAuthUserSchema = z.object({ | ||
| sub: z.string(), | ||
| client_id: z.string(), | ||
| scope: z.array(z.string()), | ||
| }); | ||
|
|
||
| export type FxaOAuthUser = z.infer<typeof fxaOAuthUserSchema>; | ||
|
|
||
| /** | ||
| * Zod schema for JWT claims from an FxA OAuth access token. | ||
| */ | ||
| export const fxaAccessTokenClaimsSchema = z.object({ | ||
| sub: z.string(), | ||
| client_id: z.string(), | ||
| scope: z.string(), | ||
| 'fxa-generation': z.number().optional(), | ||
| 'fxa-profileChangedAt': z.number().optional(), | ||
| }); | ||
|
|
||
| /** | ||
| * JWT claims from an FXA OAuth access token. | ||
| */ | ||
| export type FxaAccessTokenClaims = z.infer<typeof fxaAccessTokenClaimsSchema>; | ||
|
|
||
| /** | ||
| * Zod schema for the response from the FxA auth server's POST /v1/verify endpoint. | ||
| */ | ||
| export const fxaVerifyResponseSchema = z.object({ | ||
| user: z.string(), | ||
| client_id: z.string(), | ||
| scope: z.array(z.string()), | ||
| generation: z.number().optional(), | ||
| profile_changed_at: z.number().optional(), | ||
| }); | ||
|
|
||
| /** | ||
| * Response from the FxA auth server's POST /v1/verify endpoint. | ||
| */ | ||
| export type FxaVerifyResponse = z.infer<typeof fxaVerifyResponseSchema>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { FxaOAuthAuthGuard } from './fxa-oauth-auth.guard'; | ||
|
|
||
| describe('FxaOAuthAuthGuard', () => { | ||
| it('can be instantiated', () => { | ||
| const guard = new FxaOAuthAuthGuard(); | ||
| expect(guard).toBeDefined(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { Injectable } from '@nestjs/common'; | ||
| import { AuthGuard } from '@nestjs/passport'; | ||
|
|
||
| /** | ||
| * Route guard that validates FxA OAuth access tokens. | ||
| * | ||
| * Accepts both token formats via Authorization: Bearer <token>: | ||
| * | ||
| * 1. JWT access tokens — validated locally via JWKS (fast, no network call). | ||
| * Requires the OAuth client to be in jwtAccessTokens.enabledClientIds. | ||
| * See FxaOAuthJwtStrategy (./fxa-oauth-jwt.strategy.ts). | ||
| * | ||
| * 2. Opaque hex access tokens — validated by calling POST {auth-server}/v1/verify, | ||
| * the same path used by the profile server and the auth server's own | ||
| * oauthToken scheme. See FxaOAuthVerifyStrategy (./fxa-oauth-verify.strategy.ts). | ||
| * | ||
| * The JWT strategy is tried first. If it fails (token is not a JWT), the | ||
| * verify strategy handles it as a fallback. | ||
| * | ||
| * Requirements: | ||
| * - Token must include the scope from FXA_O_AUTH_CONFIG__FXA_O_AUTH_REQUIRED_SCOPE. | ||
| * - For JWTs: issuer must match oauthServer.openid.issuer (localhost:3030 in dev). | ||
| * - Auth server URL set via FXA_O_AUTH_CONFIG__FXA_O_AUTH_SERVER_URL for verify fallback. | ||
| */ | ||
| @Injectable() | ||
| export class FxaOAuthAuthGuard extends AuthGuard([ | ||
| 'fxa-oauth-jwt', | ||
| 'fxa-oauth-verify', | ||
| ]) {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { UnauthorizedException } from '@nestjs/common'; | ||
| import { FxaOAuthJwtStrategy } from './fxa-oauth-jwt.strategy'; | ||
| import { MockFxaOAuthConfig } from './fxa-oauth.config'; | ||
| import { FxaAccessTokenClaimsFactory } from './factories/fxa-access-token-claims.factory'; | ||
|
|
||
| // Mock jwks-rsa to avoid real JWKS fetching during construction | ||
| jest.mock('jwks-rsa', () => ({ | ||
| passportJwtSecret: jest.fn(() => (_req: any, _raw: any, done: any) => | ||
| done(null, 'mock-secret') | ||
| ), | ||
| })); | ||
|
|
||
| /** Build a mock Express Request. */ | ||
| function makeReq(): any { | ||
| return { headers: {} }; | ||
| } | ||
|
|
||
| describe('FxaOAuthJwtStrategy', () => { | ||
| let strategy: FxaOAuthJwtStrategy; | ||
|
|
||
| beforeEach(() => { | ||
| strategy = new FxaOAuthJwtStrategy(MockFxaOAuthConfig); | ||
| }); | ||
|
|
||
| it('returns user with scope array when required scope is present', () => { | ||
| const claims = FxaAccessTokenClaimsFactory({ | ||
| scope: MockFxaOAuthConfig.fxaOAuthRequiredScope, | ||
| }); | ||
| const result = strategy.validate(makeReq(), claims); | ||
| expect(result).toEqual({ | ||
| sub: claims.sub, | ||
| client_id: claims.client_id, | ||
| scope: [MockFxaOAuthConfig.fxaOAuthRequiredScope], | ||
| }); | ||
| }); | ||
|
|
||
| it('returns user with scope array when required scope is among multiple scopes', () => { | ||
| const claims = FxaAccessTokenClaimsFactory({ | ||
| scope: `profile ${MockFxaOAuthConfig.fxaOAuthRequiredScope} openid`, | ||
| }); | ||
| const result = strategy.validate(makeReq(), claims); | ||
| expect(result).toEqual({ | ||
| sub: claims.sub, | ||
| client_id: claims.client_id, | ||
| scope: ['profile', MockFxaOAuthConfig.fxaOAuthRequiredScope, 'openid'], | ||
| }); | ||
| }); | ||
|
|
||
| it('throws UnauthorizedException when required scope is missing', () => { | ||
| const claims = FxaAccessTokenClaimsFactory({ scope: 'profile openid' }); | ||
| expect(() => strategy.validate(makeReq(), claims)).toThrow( | ||
| UnauthorizedException | ||
| ); | ||
| }); | ||
|
|
||
| it('throws UnauthorizedException when scope is empty', () => { | ||
| const claims = FxaAccessTokenClaimsFactory({ scope: '' }); | ||
| expect(() => strategy.validate(makeReq(), claims)).toThrow( | ||
| UnauthorizedException | ||
| ); | ||
| }); | ||
|
|
||
| it('throws UnauthorizedException when scope is undefined', () => { | ||
| const claims = FxaAccessTokenClaimsFactory({ scope: undefined } as any); | ||
| expect(() => strategy.validate(makeReq(), claims)).toThrow( | ||
| UnauthorizedException | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { Injectable, UnauthorizedException } from '@nestjs/common'; | ||
| import { PassportStrategy } from '@nestjs/passport'; | ||
| import { passportJwtSecret } from 'jwks-rsa'; | ||
| import { ExtractJwt, Strategy } from 'passport-jwt'; | ||
| import { Request } from 'express'; | ||
|
|
||
| import { FxaOAuthConfig } from './fxa-oauth.config'; | ||
| import { | ||
| fxaAccessTokenClaimsSchema, | ||
| FxaOAuthUser, | ||
| } from './fxa-access-token.schemas'; | ||
|
|
||
| @Injectable() | ||
| export class FxaOAuthJwtStrategy extends PassportStrategy( | ||
| Strategy, | ||
| 'fxa-oauth-jwt' | ||
| ) { | ||
| private requiredScope: string; | ||
|
|
||
| constructor(config: FxaOAuthConfig) { | ||
| super({ | ||
| secretOrKeyProvider: passportJwtSecret({ | ||
| cache: true, | ||
| rateLimit: true, | ||
| jwksRequestsPerMinute: 5, | ||
| jwksUri: config.fxaOAuthJwksUri, | ||
| }), | ||
| jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
| issuer: config.fxaOAuthIssuer, | ||
| algorithms: ['RS256'], | ||
| passReqToCallback: true, | ||
| }); | ||
|
Comment on lines
+32
to
+36
|
||
| this.requiredScope = config.fxaOAuthRequiredScope; | ||
| } | ||
|
|
||
| public validate(req: Request, claims: unknown): FxaOAuthUser { | ||
| const result = fxaAccessTokenClaimsSchema.safeParse(claims); | ||
| if (!result.success) { | ||
| throw new UnauthorizedException('Invalid token claims'); | ||
| } | ||
|
|
||
| const scopes = result.data.scope?.split(' ') ?? []; | ||
| if (!scopes.includes(this.requiredScope)) { | ||
| throw new UnauthorizedException('Insufficient scope'); | ||
| } | ||
|
|
||
| return { | ||
| sub: result.data.sub, | ||
| client_id: result.data.client_id, | ||
| scope: scopes, | ||
| }; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.