Skip to content

feat: handshake outage resiliency WIP #6288

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
11 changes: 10 additions & 1 deletion packages/backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export type ClerkOptions = CreateBackendApiOptions &
Partial<
Pick<
CreateAuthenticateRequestOptions['options'],
'audience' | 'jwtKey' | 'proxyUrl' | 'secretKey' | 'publishableKey' | 'domain' | 'isSatellite'
'audience' | 'jwtKey' | 'proxyUrl' | 'secretKey' | 'publishableKey' | 'domain' | 'isSatellite' | 'outageResilienceConfig'
>
> & { sdkMetadata?: SDKMetadata; telemetry?: Pick<TelemetryCollectorOptions, 'disabled' | 'debug'> };

Expand Down Expand Up @@ -164,3 +164,12 @@ export type {
*/
export type { AuthObject, InvalidTokenAuthObject } from './tokens/authObjects';
export type { SessionAuthObject, MachineAuthObject } from './tokens/types';

/**
* Outage resilience
*/
export type {
OutageResilienceConfig,
SdkCapabilityResult,
SdkCapabilityIndicators
} from './tokens/outageResilience';
5 changes: 5 additions & 0 deletions packages/backend/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ export type {
InferAuthObjectFromTokenArray,
GetAuthFn,
} from './tokens/types';
export type {
OutageResilienceConfig,
SdkCapabilityResult,
SdkCapabilityIndicators,
} from './tokens/outageResilience';

export { TokenType } from './tokens/tokenTypes';
export type { SessionTokenType, MachineTokenType } from './tokens/tokenTypes';
Expand Down
235 changes: 235 additions & 0 deletions packages/backend/src/tokens/__tests__/outageResilience.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
import { describe, expect, it, vi } from 'vitest';

import type { AuthenticateContext } from '../authenticateContext';
import type { SdkCapabilityResult } from '../outageResilience';
import { OutageResilienceService } from '../outageResilience';

describe('OutageResilienceService', () => {
let service: OutageResilienceService;
let mockContext: Partial<AuthenticateContext>;

beforeEach(() => {
service = new OutageResilienceService();
mockContext = {
request: {
headers: new Map(),
} as any,
getQueryParam: vi.fn(),
};
});

describe('hasBuiltInOutageResiliency', () => {
it('should detect resilience via explicit header', () => {
const headers = new Map([
['X-Clerk-Outage-Resilient', 'true'],
['X-Clerk-SDK', 'clerk-js'],
['X-Clerk-SDK-Version', '5.72.0'],
['X-Clerk-Handshake-Retry', '2'],
]);
mockContext.request = { headers } as any;

const result = service.hasBuiltInOutageResiliency(mockContext as AuthenticateContext);

expect(result).toEqual({
hasBuiltInOutageResiliency: true,
sdkIdentifier: 'clerk-js',
sdkVersion: '5.72.0',
retryAttempt: 2,
reason: 'Explicit outage resilience header detected',
});
});

it('should detect resilience via User-Agent pattern', () => {
const headers = new Map([['User-Agent', 'Mozilla/5.0 (compatible; @clerk/[email protected])']]);
mockContext.request = { headers } as any;

const result = service.hasBuiltInOutageResiliency(mockContext as AuthenticateContext);

expect(result).toEqual({
hasBuiltInOutageResiliency: true,
sdkIdentifier: 'clerk-js',
sdkVersion: '5.72.1',
reason: 'SDK [email protected] supports outage resilience',
});
});

it('should reject older SDK versions', () => {
const headers = new Map([['User-Agent', 'Mozilla/5.0 (compatible; @clerk/[email protected])']]);
mockContext.request = { headers } as any;

const result = service.hasBuiltInOutageResiliency(mockContext as AuthenticateContext);

expect(result).toEqual({
hasBuiltInOutageResiliency: false,
sdkIdentifier: 'clerk-js',
sdkVersion: '5.71.0',
reason: 'SDK [email protected] does not support outage resilience',
});
});

it('should detect resilience via query parameter fallback', () => {
mockContext.getQueryParam = vi.fn().mockReturnValue('true');

const result = service.hasBuiltInOutageResiliency(mockContext as AuthenticateContext);

expect(result).toEqual({
hasBuiltInOutageResiliency: true,
reason: 'Outage resilience query parameter detected',
});
expect(mockContext.getQueryParam).toHaveBeenCalledWith('outage_resilient');
});

it('should return false when no indicators found', () => {
mockContext.request = { headers: new Map() } as any;
mockContext.getQueryParam = vi.fn().mockReturnValue(undefined);

const result = service.hasBuiltInOutageResiliency(mockContext as AuthenticateContext);

expect(result).toEqual({
hasBuiltInOutageResiliency: false,
reason: 'No resilience indicators found',
});
});

it('should return false when globally disabled', () => {
service = new OutageResilienceService({ enabled: false });

const result = service.hasBuiltInOutageResiliency(mockContext as AuthenticateContext);

expect(result).toEqual({
hasBuiltInOutageResiliency: false,
reason: 'Outage resilience disabled globally',
});
});
});

describe('shouldServeErrorPage', () => {
it('should serve error page for non-resilient clients', () => {
mockContext.request = { headers: new Map() } as any;
mockContext.getQueryParam = vi.fn().mockReturnValue(undefined);

const result = service.shouldServeErrorPage(mockContext as AuthenticateContext, '/v1/client/handshake');

expect(result).toEqual({
shouldServeErrorPage: true,
reason: 'SDK does not support outage resilience: No resilience indicators found',
});
});

it('should skip error page for resilient clients', () => {
const headers = new Map([['X-Clerk-Outage-Resilient', 'true']]);
mockContext.request = { headers } as any;

const result = service.shouldServeErrorPage(mockContext as AuthenticateContext, '/v1/client/handshake');

expect(result).toEqual({
shouldServeErrorPage: false,
reason: 'SDK supports outage resilience: Explicit outage resilience header detected',
});
});

it('should serve error page for unsupported endpoints', () => {
const headers = new Map([['X-Clerk-Outage-Resilient', 'true']]);
mockContext.request = { headers } as any;

const result = service.shouldServeErrorPage(mockContext as AuthenticateContext, '/v1/users');

expect(result).toEqual({
shouldServeErrorPage: true,
reason: 'Endpoint does not support outage resilience',
});
});
});

describe('createResilienceHeaders', () => {
it('should create appropriate headers for resilient clients', () => {
const capability: SdkCapabilityResult = {
hasBuiltInOutageResiliency: true,
sdkIdentifier: 'clerk-js',
retryAttempt: 3,
reason: 'Test',
};

const headers = service.createResilienceHeaders(capability);

expect(headers.get('X-Clerk-Outage-Resiliency')).toBe('active');
expect(headers.get('X-Clerk-SDK-Detected')).toBe('clerk-js');
expect(headers.get('X-Clerk-Retry-Attempt')).toBe('3');
expect(headers.get('Cache-Control')).toBe('no-cache, no-store, must-revalidate');
expect(headers.get('Pragma')).toBe('no-cache');
expect(headers.get('Expires')).toBe('0');
});

it('should create cache headers for non-resilient clients', () => {
const capability: SdkCapabilityResult = {
hasBuiltInOutageResiliency: false,
reason: 'Test',
};

const headers = service.createResilienceHeaders(capability);

expect(headers.get('X-Clerk-Outage-Resiliency')).toBeNull();
expect(headers.get('Cache-Control')).toBe('no-cache, no-store, must-revalidate');
expect(headers.get('Pragma')).toBe('no-cache');
expect(headers.get('Expires')).toBe('0');
});
});

describe('SDK version detection', () => {
const testCases = [
{
userAgent: '@clerk/[email protected]',
expected: { hasResilience: true, name: 'nextjs', version: '5.8.0' },
},
{
userAgent: '@clerk/[email protected]',
expected: { hasResilience: false, name: 'nextjs', version: '5.7.9' },
},
{
userAgent: '@clerk/[email protected]',
expected: { hasResilience: true, name: 'clerk-react', version: '5.12.1' },
},
{
userAgent: '@clerk/[email protected]',
expected: { hasResilience: false, name: 'clerk-react', version: '5.11.9' },
},
];

testCases.forEach(({ userAgent, expected }) => {
it(`should correctly detect ${expected.name}@${expected.version} resilience: ${expected.hasResilience}`, () => {
const headers = new Map([['User-Agent', userAgent]]);
mockContext.request = { headers } as any;

const result = service.hasBuiltInOutageResiliency(mockContext as AuthenticateContext);

expect(result.hasBuiltInOutageResiliency).toBe(expected.hasResilience);
expect(result.sdkIdentifier).toBe(expected.name);
expect(result.sdkVersion).toBe(expected.version);
});
});
});

describe('configuration options', () => {
it('should respect custom endpoint configuration', () => {
service = new OutageResilienceService({
supportedEndpoints: ['/custom/endpoint'],
});

expect(service.isEndpointSupported('/v1/client/handshake')).toBe(false);
expect(service.isEndpointSupported('/custom/endpoint')).toBe(true);
});

it('should respect retry attempt limits', () => {
service = new OutageResilienceService({
maxRetryAttempts: 3,
});

const headers = new Map([['X-Clerk-Handshake-Retry', '5']]);
mockContext.request = { headers } as any;

const result = service.hasBuiltInOutageResiliency(mockContext as AuthenticateContext);

expect(result.retryAttempt).toBe(3); // Capped at maxRetryAttempts
});
});
});
34 changes: 32 additions & 2 deletions packages/backend/src/tokens/handshake.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { AuthErrorReason, signedIn, signedOut } from './authStatus';
import { getCookieName, getCookieValue } from './cookie';
import { loadClerkJWKFromLocal, loadClerkJWKFromRemote } from './keys';
import type { OrganizationMatcher } from './organizationMatcher';
import type { OutageResilienceConfig, SdkCapabilityResult } from './outageResilience';
import { OutageResilienceService } from './outageResilience';
import { TokenType } from './tokenTypes';
import type { OrganizationSyncOptions, OrganizationSyncTarget } from './types';
import type { VerifyTokenOptions } from './verify';
Expand Down Expand Up @@ -87,15 +89,17 @@ export class HandshakeService {
private readonly authenticateContext: AuthenticateContext;
private readonly organizationMatcher: OrganizationMatcher;
private readonly options: { organizationSyncOptions?: OrganizationSyncOptions };
private readonly outageResilienceService: OutageResilienceService;

constructor(
authenticateContext: AuthenticateContext,
options: { organizationSyncOptions?: OrganizationSyncOptions },
options: { organizationSyncOptions?: OrganizationSyncOptions; outageResilienceConfig?: Partial<OutageResilienceConfig> },
organizationMatcher: OrganizationMatcher,
) {
this.authenticateContext = authenticateContext;
this.options = options;
this.organizationMatcher = organizationMatcher;
this.outageResilienceService = new OutageResilienceService(options.outageResilienceConfig);
}

/**
Expand All @@ -122,6 +126,20 @@ export class HandshakeService {
return false;
}

/**
* Determines if the current request has built-in outage resilience support
*/
hasBuiltInOutageResiliency(): SdkCapabilityResult {
return this.outageResilienceService.hasBuiltInOutageResiliency(this.authenticateContext);
}

/**
* Determines if we should serve an error page or redirect directly for outages
*/
shouldServeErrorPage(endpoint: string): { shouldServeErrorPage: boolean; reason: string } {
return this.outageResilienceService.shouldServeErrorPage(this.authenticateContext, endpoint);
}

/**
* Builds the redirect headers for a handshake request
* @param reason - The reason for the handshake (e.g. 'session-token-expired')
Expand Down Expand Up @@ -163,7 +181,19 @@ export class HandshakeService {
});
}

return new Headers({ [constants.Headers.Location]: url.href });
// Create base headers with Location
const headers = new Headers({ [constants.Headers.Location]: url.href });

// Add outage resilience headers if applicable
const capability = this.hasBuiltInOutageResiliency();
const resilienceHeaders = this.outageResilienceService.createResilienceHeaders(capability);

// Merge resilience headers into the response headers
resilienceHeaders.forEach((value, key) => {
headers.set(key, value);
});

return headers;
}

/**
Expand Down
Loading
Loading