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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions apps/payments/api/.env
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,9 @@ GLEAN_CONFIG__LOGGER_APP_NAME='fxa-payments-next'
FXA_WEBHOOK_CONFIG__FXA_WEBHOOK_ISSUER=https://accounts.firefox.com/
FXA_WEBHOOK_CONFIG__FXA_WEBHOOK_JWKS_URI=https://oauth.accounts.firefox.com/v1/jwks/
FXA_WEBHOOK_CONFIG__FXA_WEBHOOK_AUDIENCE=

# FXA OAuth Config
FXA_O_AUTH_CONFIG__FXA_O_AUTH_JWKS_URI=http://localhost:9000/v1/jwks
FXA_O_AUTH_CONFIG__FXA_O_AUTH_ISSUER=http://localhost:3030
FXA_O_AUTH_CONFIG__FXA_O_AUTH_REQUIRED_SCOPE=https://identity.mozilla.com/account/subscriptions
FXA_O_AUTH_CONFIG__FXA_O_AUTH_SERVER_URL=http://localhost:9000
2 changes: 2 additions & 0 deletions apps/payments/api/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TypedConfigModule, dotenvLoader } from 'nest-typed-config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RootConfig } from '../config';
import { AuthModule } from '@fxa/payments/auth';
import {
CmsWebhooksController,
CmsWebhookService,
Expand Down Expand Up @@ -46,6 +47,7 @@ import { NimbusClient, NimbusClientConfig } from '@fxa/shared/experiments';

@Module({
imports: [
AuthModule,
TypedConfigModule.forRoot({
schema: RootConfig,
load: dotenvLoader({
Expand Down
6 changes: 6 additions & 0 deletions apps/payments/api/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { MySQLConfig } from '@fxa/shared/db/mysql/core';
import { FxaWebhookConfig, StripeEventConfig } from '@fxa/payments/webhooks';
import { StatsDConfig } from '@fxa/shared/metrics/statsd';
import { FirestoreConfig } from 'libs/shared/db/firestore/src/lib/firestore.config';
import { FxaOAuthConfig } from '@fxa/payments/auth';

export class RootConfig {
@Type(() => MySQLConfig)
Expand Down Expand Up @@ -61,4 +62,9 @@ export class RootConfig {
@ValidateNested()
@IsDefined()
public readonly fxaWebhookConfig!: Partial<FxaWebhookConfig>;

@Type(() => FxaOAuthConfig)
@ValidateNested()
@IsDefined()
public readonly fxaOAuthConfig!: Partial<FxaOAuthConfig>;
}
18 changes: 18 additions & 0 deletions libs/payments/auth/.eslintrc.json
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": {}
}
]
}
10 changes: 10 additions & 0 deletions libs/payments/auth/jest.config.ts
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',
};
4 changes: 4 additions & 0 deletions libs/payments/auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"name": "@fxa/payments/auth",
"version": "0.0.1"
}
27 changes: 27 additions & 0 deletions libs/payments/auth/project.json
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"
}
}
}
}
8 changes: 8 additions & 0 deletions libs/payments/auth/src/index.ts
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';
14 changes: 14 additions & 0 deletions libs/payments/auth/src/lib/auth.module.ts
Comment thread
StaberindeZA marked this conversation as resolved.
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 {}
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 libs/payments/auth/src/lib/factories/verify-response.factory.ts
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,
});
50 changes: 50 additions & 0 deletions libs/payments/auth/src/lib/fxa-access-token.schemas.ts
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>;
12 changes: 12 additions & 0 deletions libs/payments/auth/src/lib/fxa-oauth-auth.guard.spec.ts
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();
});
});
33 changes: 33 additions & 0 deletions libs/payments/auth/src/lib/fxa-oauth-auth.guard.ts
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',
]) {}
73 changes: 73 additions & 0 deletions libs/payments/auth/src/lib/fxa-oauth-jwt.strategy.spec.ts
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
);
});
});
57 changes: 57 additions & 0 deletions libs/payments/auth/src/lib/fxa-oauth-jwt.strategy.ts
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,
};
}
}
Loading
Loading