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
5 changes: 5 additions & 0 deletions .changeset/new-lies-film.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wallet-frontend": patch
---

Accept, store and return engine authorization context
161 changes: 155 additions & 6 deletions src/hooks/useOID4VCIFlow.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import type { ReactNode } from 'react';
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook } from '@testing-library/react';
import CredentialsContext, { type CredentialsContextValue } from '@/context/CredentialsContext';
import CredentialsContext, {
type CredentialsContextValue,
} from '@/context/CredentialsContext';
import SessionContext, {
type SessionContextValue,
} from '@/context/SessionContext';
import type { OID4VCIFlowResult } from '@/lib/openid-flow/types/OID4VCITypes';
import useOID4VCIFlow from './useOID4VCIFlow';

const { transport } = vi.hoisted(() => ({
Expand All @@ -17,10 +23,39 @@
}));

// The credentials context has no default value: the hook needs a provider (only the engine is read here).
const credentials = { credentialEngine: new Promise(() => undefined) } as unknown as CredentialsContextValue;
const credentials = {
credentialEngine: new Promise(() => undefined),
} as unknown as CredentialsContextValue;
const session = {
oidFlowClientAuthMaterialManager: {
exportAuthMaterial: vi.fn().mockResolvedValue(undefined),
seedMaterial: vi.fn(),
},
} as unknown as SessionContextValue;
const wrapper = ({ children }: { children: ReactNode }) => (
<CredentialsContext.Provider value={credentials}>{children}</CredentialsContext.Provider>
<SessionContext.Provider value={session}>
<CredentialsContext.Provider value={credentials}>
{children}
</CredentialsContext.Provider>
</SessionContext.Provider>
);

const OFFER_URL = new URL(
'openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer',
);
const OFFER = {
credential_issuer: 'https://issuer.example.com',
credential_configuration_ids: ['pid'],
};
const AUTHORIZATION_RESULT: OID4VCIFlowResult = {
success: true,
authorizationUrl: 'https://as.example.com/authorize?request_uri=urn:x',
codeVerifier: 'saved-verifier',
issuerState: 'saved-state',
authorizationContext: 'signed.authorization.context',
credentialOffer: OFFER,
};
const CONTEXT_LIFETIME_MS = 5 * 60 * 1000;

describe('useOID4VCIFlow: aborting a flow reaches the transport', () => {
it('releases what the transport holds for the flow when the hook unmounts', () => {
Expand All @@ -43,7 +78,11 @@
}),
);
const { result, unmount } = renderHook(() => useOID4VCIFlow(), { wrapper });
const outcome = result.current.handleCredentialOffer(new URL('openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer'));
const outcome = result.current.handleCredentialOffer(
new URL(
'openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer',
),
);
await vi.waitFor(() => expect(failStart).toBeTypeOf('function'));

unmount();
Expand All @@ -60,9 +99,119 @@
transport.startOID4VCIFlow.mockRejectedValue(new Error('boom'));
const { result } = renderHook(() => useOID4VCIFlow(), { wrapper });

const outcome = await result.current.handleCredentialOffer(new URL('openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer'));
const outcome = await result.current.handleCredentialOffer(
new URL(
'openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer',
),
);

expect(outcome.success).toBe(false);
expect(transport.releaseFlow).toHaveBeenCalled();
});
});

describe('useOID4VCIFlow: resuming after a same-tab redirect', () => {
beforeEach(() => {
sessionStorage.clear();
transport.startOID4VCIFlow.mockReset();
});

afterEach(() => {
vi.useRealTimers();
});

it('sends the saved context and verifier with the callback state and iss after a remount', async () => {
await saveAuthorizationResult(AUTHORIZATION_RESULT);
transport.startOID4VCIFlow.mockResolvedValueOnce({ success: true });
const { result } = renderHook(() => useOID4VCIFlow(), { wrapper });

const outcome = await result.current.handleAuthorizationResponse(
'auth-code',
'saved-state',
'https://as.example.com',
);

expect(outcome.success).toBe(true);
expect(transport.startOID4VCIFlow).toHaveBeenLastCalledWith(
expect.objectContaining({
credentialOffer: JSON.stringify(OFFER),
authorizationCode: 'auth-code',
codeVerifier: 'saved-verifier',
state: 'saved-state',
authorizationResponseIssuer: 'https://as.example.com',
authorizationContext: 'signed.authorization.context',
}),
);
});

it('saves and sends the context when the authorization result has no verifier', async () => {
await saveAuthorizationResult({
...AUTHORIZATION_RESULT,
codeVerifier: undefined,
});
transport.startOID4VCIFlow.mockResolvedValueOnce({ success: true });
const { result } = renderHook(() => useOID4VCIFlow(), { wrapper });

const outcome = await result.current.handleAuthorizationResponse(
'auth-code',
'saved-state',
undefined,
);

expect(outcome.success).toBe(true);
const [params] = transport.startOID4VCIFlow.mock.lastCall!;
expect(params.authorizationContext).toBe('signed.authorization.context');
expect(params.state).toBe('saved-state');
expect(params.codeVerifier).toBeUndefined();
expect(params.authorizationResponseIssuer).toBeUndefined();
});

it('still resumes at exactly five minutes', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
await saveAuthorizationResult(AUTHORIZATION_RESULT);
vi.setSystemTime(Date.now() + CONTEXT_LIFETIME_MS);
transport.startOID4VCIFlow.mockResolvedValueOnce({ success: true });
const { result } = renderHook(() => useOID4VCIFlow(), { wrapper });

const outcome = await result.current.handleAuthorizationResponse(
'auth-code',
'saved-state',
'https://as.example.com',
);

expect(outcome.success).toBe(true);
expect(transport.startOID4VCIFlow).toHaveBeenCalledTimes(2);
});

it('drops the saved flow once five minutes have passed and never resumes it', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
await saveAuthorizationResult(AUTHORIZATION_RESULT);
vi.setSystemTime(Date.now() + CONTEXT_LIFETIME_MS + 1);
const { result } = renderHook(() => useOID4VCIFlow(), { wrapper });

const outcome = await result.current.handleAuthorizationResponse(
'auth-code',
'saved-state',
'https://as.example.com',
);

expect(outcome.success).toBe(false);
expect(transport.startOID4VCIFlow).toHaveBeenCalledTimes(1);
expect(sessionStorage.length).toBe(0);

Check warning on line 200 in src/hooks/useOID4VCIFlow.test.tsx

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer "expect(sessionStorage).toHaveLength(0)" over this generic assertion for better reporting; it works on any object with a numeric length property.

See more on https://sonarcloud.io/project/issues?id=sirosfoundation_wallet-frontend&issues=AaHuwosPxlSrwDLugjSp&open=AaHuwosPxlSrwDLugjSp&pullRequest=456
});
});

/**
* Runs a credential offer that ends in an authorization redirect, then unmounts the hook like the page leaving.
*/
async function saveAuthorizationResult(
authorizationResult: OID4VCIFlowResult,
): Promise<void> {
transport.startOID4VCIFlow.mockResolvedValueOnce(authorizationResult);
const { result, unmount } = renderHook(() => useOID4VCIFlow(), { wrapper });

const outcome = await result.current.handleCredentialOffer(OFFER_URL);

expect(outcome.authorizationUrl).toBe(authorizationResult.authorizationUrl);
unmount();
}
16 changes: 11 additions & 5 deletions src/hooks/useOID4VCIFlow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export interface UseOID4VCIFlowReturn {
/**
* Continue flow with authorization code (after redirect)
*/
handleAuthorizationResponse: (authCode: string, state?: string) => Promise<OID4VCIFlowResult>;
handleAuthorizationResponse: (authCode: string, state?: string, iss?: string) => Promise<OID4VCIFlowResult>;
/**
* Continue flow with pre-authorized code and optional TX code
*/
Expand Down Expand Up @@ -191,7 +191,7 @@ export function useOID4VCIFlow(options: UseOID4VCIFlowOptions = {}): UseOID4VCIF

assertNotAborted();

if (result.authorizationUrl && result.codeVerifier) {
if (result.authorizationUrl && result.authorizationContext) {
// Persist the flow's client-held key (+ its WIA) so the
// post-redirect token leg reuses it: the issuer binds the
// WIA to the issuance session, so PAR and token must carry
Expand All @@ -203,6 +203,7 @@ export function useOID4VCIFlow(options: UseOID4VCIFlowOptions = {}): UseOID4VCIF
flowId: result.transactionId,
codeVerifier: result.codeVerifier,
state: result.issuerState,
authorizationContext: result.authorizationContext,
Comment thread
smncd marked this conversation as resolved.
Resolved
credentialOffer: result.credentialOffer
? JSON.stringify(result.credentialOffer)
: undefined,
Expand Down Expand Up @@ -261,7 +262,8 @@ export function useOID4VCIFlow(options: UseOID4VCIFlowOptions = {}): UseOID4VCIF
*/
const handleAuthorizationResponse = useCallback(async (
authCode: string,
state?: string
state?: string,
iss?: string,
): Promise<OID4VCIFlowResult> => {
setIsLoading(true);
setError(null);
Expand Down Expand Up @@ -290,6 +292,9 @@ export function useOID4VCIFlow(options: UseOID4VCIFlowOptions = {}): UseOID4VCIF
credentialOffer: storedFlow?.credentialOffer,
authorizationCode: authCode,
codeVerifier: storedFlow?.codeVerifier,
state,
authorizationResponseIssuer: iss,
authorizationContext: storedFlow?.authorizationContext,
redirectUri: OPENID4VCI_REDIRECT_URI,
});

Expand Down Expand Up @@ -537,6 +542,7 @@ export interface PendingOID4VCIFlow {
flowId?: string;
codeVerifier?: string;
state?: string;
authorizationContext?: string;
credentialOffer?: string;
clientAuthKey?: SerializedClientAuthMaterial;
timestamp: number;
Expand All @@ -560,8 +566,8 @@ function loadAndClearPendingFlow(): PendingOID4VCIFlow | null {

try {
const flow = JSON.parse(stored) as PendingOID4VCIFlow;
// Expire after 10 minutes
if (Date.now() - flow.timestamp > 10 * 60 * 1000) {
// Matches the backend's authorization_context lifetime
if (Date.now() - flow.timestamp > 5 * 60 * 1000) {
return null;
}
return flow;
Expand Down
65 changes: 65 additions & 0 deletions src/lib/openid-flow/__tests__/OIDFlowWebSocketTransport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ describe('OIDFlowWebSocketTransport', () => {
const flowPromise = transport.startOID4VCIFlow({
authorizationCode: 'auth-code-123',
codeVerifier: 'verifier-abc',
state: 'state-xyz',
authorizationResponseIssuer: 'https://as.example.com',
});

await vi.waitFor(() => {
Expand All @@ -232,6 +234,8 @@ describe('OIDFlowWebSocketTransport', () => {
expect(sentMessage.action).toBe('authorization_complete');
expect(sentMessage.payload.code).toBe('auth-code-123');
expect(sentMessage.payload.code_verifier).toBe('verifier-abc');
expect(sentMessage.payload.state).toBe('state-xyz');
expect(sentMessage.payload.iss).toBe('https://as.example.com');

// Respond with credential
sockets[0].simulateMessage({
Expand All @@ -244,6 +248,67 @@ describe('OIDFlowWebSocketTransport', () => {
expect(result.success).toBe(true);
});

it('should resume a same-tab redirect with state, iss and authorization_context', async () => {
const transport = new OIDFlowWebSocketTransport(wsUrl, authToken);
await transport.connect();

const flowPromise = transport.startOID4VCIFlow({
credentialOffer: '{"credential_issuer":"https://issuer.example.com"}',
authorizationCode: 'auth-code-123',
codeVerifier: 'verifier-abc',
state: 'state-xyz',
authorizationResponseIssuer: 'https://as.example.com',
authorizationContext: 'signed.context.jwt',
redirectUri: 'https://wallet.example.com/cb',
});

await vi.waitFor(() => {
expect(sockets[0].sentMessages.length).toBeGreaterThan(1);
});

const sentMessage = JSON.parse(sockets[0].sentMessages[1]);
expect(sentMessage.type).toBe('flow_start');
expect(sentMessage.auth_code).toBe('auth-code-123');
expect(sentMessage.state).toBe('state-xyz');
expect(sentMessage.iss).toBe('https://as.example.com');
expect(sentMessage.authorization_context).toBe('signed.context.jwt');

sockets[0].simulateMessage({
flow_id: sentMessage.flow_id,
type: 'flow_complete',
credential: 'eyJ...',
});

const result = await flowPromise;
expect(result.success).toBe(true);
});

it('should omit iss on resume when the callback had none', async () => {
const transport = new OIDFlowWebSocketTransport(wsUrl, authToken);
await transport.connect();

const flowPromise = transport.startOID4VCIFlow({
credentialOffer: '{"credential_issuer":"https://issuer.example.com"}',
authorizationCode: 'auth-code-123',
state: 'state-xyz',
authorizationContext: 'signed.context.jwt',
});

await vi.waitFor(() => {
expect(sockets[0].sentMessages.length).toBeGreaterThan(1);
});

const sentMessage = JSON.parse(sockets[0].sentMessages[1]);
expect(sentMessage).not.toHaveProperty('iss');

sockets[0].simulateMessage({
flow_id: sentMessage.flow_id,
type: 'flow_complete',
credential: 'eyJ...',
});
await flowPromise;
});

it('should handle error responses by returning success: false', async () => {
const transport = new OIDFlowWebSocketTransport(wsUrl, authToken);
await transport.connect();
Expand Down
7 changes: 7 additions & 0 deletions src/lib/openid-flow/transports/OIDFlowWebSocketTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,9 @@ export class OIDFlowWebSocketTransport implements IOIDFlowTransport {
redirect_uri: params.redirectUri,
auth_code: params.authorizationCode,
code_verifier: params.codeVerifier,
state: params.state,
iss: params.authorizationResponseIssuer,
authorization_context: params.authorizationContext,
});

return this.mapOID4VCIResponse(response);
Expand Down Expand Up @@ -532,6 +535,7 @@ export class OIDFlowWebSocketTransport implements IOIDFlowTransport {
code: params.authorizationCode,
code_verifier: params.codeVerifier,
state: params.state,
iss: params.authorizationResponseIssuer,
},
});

Expand Down Expand Up @@ -637,6 +641,9 @@ export class OIDFlowWebSocketTransport implements IOIDFlowTransport {
if (payload?.state) {
result.issuerState = payload.state as string;
}
if (payload?.authorization_context) {
result.authorizationContext = payload.authorization_context as string;
}

// Credential offer (for storage and resumption after redirect)
if (payload?.credential_offer) {
Expand Down
9 changes: 9 additions & 0 deletions src/lib/openid-flow/types/OID4VCITypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ export interface OID4VCIFlowParams {
/** PKCE code verifier */
codeVerifier?: string;

/** RFC 9207 `iss` from the authorization response, exactly as received */
authorizationResponseIssuer?: string;

/** Opaque backend-signed context saved before the redirect */
authorizationContext?: string;

// ===== Resumption context (for same-tab redirect flow) =====

/** Issuer identifier for resumption */
Expand Down Expand Up @@ -127,6 +133,9 @@ export interface OID4VCIFlowResult {
/** Issuer state (for authorization flow) */
issuerState?: string;

/** Opaque backend-signed context, required to resume after a same-tab redirect */
authorizationContext?: string;

// ===== Pre-authorized flow =====

/** Pre-authorized code */
Expand Down
Loading
Loading