Skip to content
Open
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
47 changes: 47 additions & 0 deletions deploy/dev-jwt-issuer-policies.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
[
{
"issuer": "https://api.topcoder-dev.com",
"algorithm": "RS256",
"audience": "https://api.topcoder-dev.com/v6",
"jwksUri": "https://api.topcoder-dev.com/v6/authorizations/.well-known/jwks.json"
},
{
"issuer": "https://auth.topcoder-dev.com/",
"algorithm": "RS256",
"audience": "BXWXUWnilVUPdN01t2Se29Tw2ZYNGZvH",
"jwksUri": "https://auth.topcoder-dev.com/.well-known/jwks.json"
},
{
"issuer": "https://topcoder-dev.auth0.com/",
"algorithm": "RS256",
"audience": [
"BXWXUWnilVUPdN01t2Se29Tw2ZYNGZvH",
"https://m2m.topcoder-dev.com/"
],
"jwksUri": "https://topcoder-dev.auth0.com/.well-known/jwks.json"
},
{
"issuer": "https://keycloak.topcoder-dev.com/realms/topcoder-m2m-dev",
"algorithm": "RS256",
"audience": "https://m2m.topcoder-dev.com/",
"jwksUri": "https://keycloak.topcoder-dev.com/realms/topcoder-m2m-dev/protocol/openid-connect/certs"
},
{
"issuer": "https://testsachin.topcoder-dev.com/",
"algorithm": "RS256",
"audience": [
"BXWXUWnilVUPdN01t2Se29Tw2ZYNGZvH",
"https://m2m.topcoder-dev.com/"
],
"jwksUri": "https://testsachin.topcoder-dev.com/.well-known/jwks.json"
},
{
"issuer": "https://test-sachin-rs256.auth0.com/",
"algorithm": "RS256",
"audience": [
"BXWXUWnilVUPdN01t2Se29Tw2ZYNGZvH",
"https://m2m.topcoder-dev.com/"
],
"jwksUri": "https://test-sachin-rs256.auth0.com/.well-known/jwks.json"
}
]
11 changes: 11 additions & 0 deletions docs/identity-rs256-dev.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Identity RS256 preparation for dev

This PR pins tc-core-library-js 4.0.0-rc.4 at commit `c7c8fab502b7152dd06b1ce46cdb703e0e13b357`. It requires explicit issuer policies and retains verified-email and identity-denylist enforcement.

The public settings are staged in dev Parameter Store under `/config/identity-rs256-dev-staged/`; running services do not reference that namespace. The checked-in JSON is a reviewed configuration proposal, not an automatically applied deployment change.

Before merging/deploying, coordinate with Identity and all token consumers. Set `JWT_ISSUER_POLICIES` to the JSON in `deploy/dev-jwt-issuer-policies.json`, retaining the service's machine audience and authorization checks. Merely adding `AUTH_SECRET` no longer enables HMAC trust. If a transition needs HS256, configure only that exact issuer with a finite UTC retirement deadline, then replace it with RS256 at the coordinated cutover. Never accept both algorithms for one issuer.

Publish the Identity public key first; then test fresh login, expiry/refresh, logout, cross-app access, human authorization, machine authorization, wrong-audience rejection and legacy-HMAC rejection. Remove AUTH_SECRET only from public-key-only API verifiers; keep separate keys for application proofs, cursors, and independent local-login tokens. Existing browser sessions continue to use Auth0; do not put Identity-issued tokens into the Accounts connector cookie without implementing an Identity-aware refresh flow.

Production is not changed. This dev policy intentionally does not trust the production Topcoder issuer. Do not merge this into production without its separately reviewed environment policy and key.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
"pg": "8.23.0",
"reflect-metadata": "0.2.2",
"rxjs": "7.8.2",
"tc-core-library-js": "https://codeload.github.com/topcoder-platform/tc-core-library-js/tar.gz/58de37670180e183e8378c3d203df0112a0414f6"
"tc-core-library-js": "https://codeload.github.com/topcoder-platform/tc-core-library-js/tar.gz/c7c8fab502b7152dd06b1ce46cdb703e0e13b357"
},
"devDependencies": {
"@eslint/js": "9.39.2",
Expand Down
12 changes: 6 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ import {
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
import jwt from 'jsonwebtoken';
import { createJwtAuthenticator, type AuthenticatorRequest } from 'tc-core-library-js';
import {
createJwtAuthenticator,
type AuthenticatorRequest,
} from 'tc-core-library-js';
import { CONFIG, type AppConfig } from './config';

export type Permission = 'public' | 'manage' | 'report';
Expand All @@ -34,9 +37,7 @@ export interface ActorRequest extends Request {
/** Validates bearer JWTs and applies the v6 human-role / M2M-scope permission split. */
@Injectable()
export class AuthGuard implements CanActivate {
private readonly authenticator: ReturnType<
typeof createJwtAuthenticator
>;
private readonly authenticator: ReturnType<typeof createJwtAuthenticator>;

/**
* Injects configuration and route metadata for authentication.
Expand All @@ -48,6 +49,7 @@ export class AuthGuard implements CanActivate {
private readonly reflector: Reflector,
) {
this.authenticator = createJwtAuthenticator({
JWT_ISSUER_POLICIES: config.jwtIssuerPolicies,
AUTH0_AUDIENCE: config.machineAudience,
JWT_AUDIENCE: config.jwtAudience,
AUTH_SECRET: config.authSecret,
Expand Down
10 changes: 7 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ export interface AppConfig {
busApi?: BusApiConfiguration;
port: number;
origins: string[];
authSecret: string;
authSecret?: string;
jwtIssuerPolicies?: string;
jwtAudience?: string;
machineAudience?: string;
issuers: string[];
Expand All @@ -33,8 +34,10 @@ export function readConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
throw new Error('DATABASE_URL must be PostgreSQL using the forms schema.');
}
database.searchParams.set('schema', 'forms');
const authSecret = required(env, 'AUTH_SECRET');
if (authSecret.length < 32)
// Public-key issuer policies do not require a shared signing secret.
// The verifier still rejects an HS256 policy without a suitable secret.
const authSecret = env.AUTH_SECRET?.trim() || undefined;
if (authSecret && authSecret.length < 32)
throw new Error('AUTH_SECRET must contain at least 32 characters.');
const origins = (env.CORS_ORIGINS ?? '')
.split(',')
Expand All @@ -51,6 +54,7 @@ export function readConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
port: integerSetting(env.PORT ?? '3000', 1, 65535),
origins,
authSecret,
jwtIssuerPolicies: env.JWT_ISSUER_POLICIES,
jwtAudience: env.JWT_AUDIENCE,
machineAudience: env.AUTH0_AUDIENCE,
issuers,
Expand Down
8 changes: 4 additions & 4 deletions test/auth-rs256.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ function browserToken(
iss: issuer,
aud: 'BXWXUWnilVUPdN01t2Se29Tw2ZYNGZvH',
sub: 'auth0|12345',
emailVerified: true,
iat: now,
exp: now + 300,
...overrides,
Expand Down Expand Up @@ -75,7 +76,6 @@ beforeAll(async () => {
provide: CONFIG,
useValue: readConfig({
DATABASE_URL: 'postgresql://localhost/forms',
AUTH_SECRET: testSecret,
VALID_ISSUERS: JSON.stringify([
issuer,
'https://api.topcoder-dev.com',
Expand Down Expand Up @@ -112,9 +112,9 @@ describe('reports directory with the shared Topcoder authenticator', () => {
expect(directory).toHaveBeenCalledTimes(2);
});

it('still accepts legacy HS256 administrators on the same deployment', async () => {
it('rejects shared-secret administrator tokens in public-key-only mode', async () => {
const token = jwt.sign(
{ userId: '12345', roles: ['Administrator'] },
{ userId: '12345', emailVerified: true, roles: ['Administrator'] },
testSecret,
{
algorithm: 'HS256',
Expand All @@ -125,7 +125,7 @@ describe('reports directory with the shared Topcoder authenticator', () => {
await request(app.getHttpServer())
.get('/v6/forms/reports/directory')
.auth(token, { type: 'bearer' })
.expect(200);
.expect(401);
});

it.each([
Expand Down
20 changes: 18 additions & 2 deletions test/auth.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ import { testSecret } from './fixtures';
const config = readConfig({
DATABASE_URL: 'postgresql://localhost/forms',
AUTH_SECRET: testSecret,
JWT_ISSUER_POLICIES: JSON.stringify(
[
'https://api.topcoder-dev.com',
'https://api.topcoder.com',
'https://forms.test',
].map((issuer) => ({
issuer,
algorithm: 'HS256',
allowMissingAudience: true,
legacyHs256Until: new Date(Date.now() + 3_600_000).toISOString(),
})),
),
VALID_ISSUERS:
'https://api.topcoder-dev.com,https://api.topcoder.com,https://forms.test',
});
Expand All @@ -30,6 +42,7 @@ async function authenticate(
const now = Math.floor(Date.now() / 1000);
const jwt = await new SignJWT({
userId: '12345',
emailVerified: true,
roles: ['Administrator'],
iss: 'https://api.topcoder-dev.com',
iat: now,
Expand Down Expand Up @@ -131,9 +144,12 @@ describe('Topcoder bearer authentication', () => {
sub: 'client@clients',
aud: 'forms-api',
gty: 'client-credentials',
userId: undefined, roles: undefined,
userId: undefined,
roles: undefined,
};
await expect(authenticate(machine)).rejects.toMatchObject({ status: 401 });
await expect(authenticate({ ...machine, scope: 'read:forms-submissions' })).rejects.toMatchObject({ status: 401 });
await expect(
authenticate({ ...machine, scope: 'read:forms-submissions' }),
).rejects.toMatchObject({ status: 401 });
});
});
16 changes: 15 additions & 1 deletion test/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ export function testConfig() {
return readConfig({
DATABASE_URL: process.env.TEST_DATABASE_URL,
AUTH_SECRET: testSecret,
JWT_ISSUER_POLICIES: JSON.stringify([
{
issuer: 'https://forms.test',
algorithm: 'HS256',
allowMissingAudience: true,
legacyHs256Until: new Date(Date.now() + 3_600_000).toISOString(),
},
{
issuer: 'https://forms-machine.test',
algorithm: 'RS256',
audience: 'forms-api',
jwksUri: 'https://forms-machine.test/.well-known/jwks.json',
},
]),
VALID_ISSUERS: 'https://forms.test',
THROTTLE_LIMIT: '10000',
CORS_ORIGINS: 'https://www.topcoder.com',
Expand All @@ -28,7 +42,7 @@ export function testConfig() {
*/
export async function token(claims: Record<string, unknown>) {
const { SignJWT } = await import('jose');
return new SignJWT(claims)
return new SignJWT({ emailVerified: true, ...claims })
.setProtectedHeader({ alg: 'HS256' })
.setSubject('test-user')
.setIssuer('https://forms.test')
Expand Down
8 changes: 4 additions & 4 deletions test/forms.integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ describe('forms API with real PostgreSQL', () => {
algorithm: 'RS256',
keyid: machineKeyId,
subject: 'test-client@clients',
issuer: 'https://forms.test',
issuer: 'https://forms-machine.test',
audience: 'forms-api',
expiresIn: '5m',
},
Expand All @@ -62,7 +62,7 @@ describe('forms API with real PostgreSQL', () => {
const keys = generateKeyPairSync('rsa', { modulusLength: 2048 });
machineKey = keys.privateKey;
// Mock key discovery only; the shared authenticator still verifies RSA signatures.
nock('https://forms.test')
nock('https://forms-machine.test')
.get('/.well-known/jwks.json')
.reply(200, {
keys: [
Expand Down Expand Up @@ -1384,13 +1384,13 @@ describe('forms API with real PostgreSQL', () => {
algorithm: 'HS256',
},
{
issuer: 'https://forms.test',
issuer: 'https://forms-machine.test',
audience: 'forms-api',
expiration: '-1m',
algorithm: 'HS256',
},
{
issuer: 'https://forms.test',
issuer: 'https://forms-machine.test',
audience: 'forms-api',
expiration: '5m',
algorithm: 'HS384',
Expand Down
3 changes: 2 additions & 1 deletion test/policies.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,8 @@ describe('definition and deployment policies', () => {
DATABASE_URL: 'postgresql://localhost/topcoder-services?schema=public',
}),
).toThrow();
expect(() => readConfig({ ...env, AUTH_SECRET: '' })).toThrow();
expect(readConfig({ ...env, AUTH_SECRET: '' }).authSecret).toBeUndefined();
expect(() => readConfig({ ...env, AUTH_SECRET: 'short' })).toThrow();
expect(
readConfig({ ...env, VALID_ISSUERS: '["https://forms.test"]' }).issuers,
).toEqual(['https://forms.test']);
Expand Down
Loading