Skip to content
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

MIJN-9699-Bug - Bypasss IDP logout if token is expired #1633

Merged
merged 8 commits into from
Nov 28, 2024
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
4 changes: 1 addition & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ WORKDIR /build-space
COPY package-lock.json /build-space/
COPY package.json /build-space/
COPY vite.config.ts /build-space/
COPY .env.local.template /build-space/
COPY vendor /build-space/vendor
COPY mocks/fixtures /build-space/mocks/fixtures

Expand Down Expand Up @@ -74,9 +75,6 @@ ENV MA_TEST_ACCOUNTS=$MA_TEST_ACCOUNTS
ARG REACT_APP_BFF_API_URL=/api/v1
ENV REACT_APP_BFF_API_URL=$REACT_APP_BFF_API_URL

ARG REACT_APP_SENTRY_DSN=
ENV REACT_APP_SENTRY_DSN=$REACT_APP_SENTRY_DSN

ARG REACT_APP_ANALYTICS_ID=
ENV REACT_APP_ANALYTICS_ID=$REACT_APP_ANALYTICS_ID

Expand Down
50 changes: 29 additions & 21 deletions src/server/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,35 @@ describe('app', async () => {
vi.resetModules();
});

test('app middleware OT', async () => {
const appModule = await import('./app');
const app = appModule.forTesting.app;
expect(
app._router.stack.some((layer: ILayer) =>
'BFF_ID' in layer.handle ? layer.handle.BFF_ID === 'router-dev' : false
)
).toBe(true);
expect(
app._router.stack.some((layer: ILayer) =>
'BFF_ID' in layer.handle ? layer.handle.BFF_ID === 'router-oidc' : false
)
).toBe(false);
expect(
app._router.stack.some((layer: ILayer) =>
'BFF_ID' in layer.handle
? layer.handle.BFF_ID === 'router-protected'
: false
)
).toBe(true);
});
test(
'app middleware OT',
async () => {
const appModule = await import('./app');
const app = appModule.forTesting.app;
expect(
app._router.stack.some((layer: ILayer) =>
'BFF_ID' in layer.handle
? layer.handle.BFF_ID === 'router-dev'
: false
)
).toBe(true);
expect(
app._router.stack.some((layer: ILayer) =>
'BFF_ID' in layer.handle
? layer.handle.BFF_ID === 'router-oidc'
: false
)
).toBe(false);
expect(
app._router.stack.some((layer: ILayer) =>
'BFF_ID' in layer.handle
? layer.handle.BFF_ID === 'router-protected'
: false
)
).toBe(true);
},
{ timeout: 10000 }
);

test('app middleware AP', async () => {
mocks.IS_AP = true;
Expand Down
1 change: 0 additions & 1 deletion src/server/auth/auth-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ export const oidcConfigBase: ConfigParams = {
getFromEnv('MA_APP_MODE') !== 'unittest'
? getSessionStore(openIdAuth as typeof expressSession, {
tableName: OIDC_SESSIONS_TABLE_NAME,
ttlSeconds: OIDC_SESSION_MAX_AGE_SECONDS, // NOTE: Not sure if this works with rollingDuration
})
: undefined,
},
Expand Down
34 changes: 27 additions & 7 deletions src/server/auth/auth-helpers.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { millisecondsToSeconds } from 'date-fns';
import { Request } from 'express';

import {
Expand All @@ -23,6 +24,7 @@ import {
RequestMock,
ResponseMock,
} from '../../testing/utils';
import { ONE_MINUTE_SECONDS } from '../config/app';
import * as blacklist from '../services/session-blacklist';

describe('auth-helpers', () => {
Expand Down Expand Up @@ -56,6 +58,7 @@ describe('auth-helpers', () => {
aud: 'test1',
[EH_ATTR_PRIMARY_ID]: 'EHERKENNING-KVK',
sid: 'test',
id: 'xx-bsn-xx',
} as TokenData
);

Expand Down Expand Up @@ -123,6 +126,7 @@ describe('auth-helpers', () => {
aud: 'test1',
[EH_ATTR_PRIMARY_ID]: 'EH-KVK1',
sid: 'test3',
id: 'xx-bsn-xx',
} as TokenData
);

Expand All @@ -146,6 +150,7 @@ describe('auth-helpers', () => {
aud: 'test1',
[EH_ATTR_PRIMARY_ID_LEGACY]: 'EH-KVK1',
sid: 'test4',
id: 'xx-bsn-xx',
} as TokenData
);

Expand All @@ -170,6 +175,7 @@ describe('auth-helpers', () => {
[EH_ATTR_INTERMEDIATE_PRIMARY_ID]: 'EH-KVK1',
[EH_ATTR_INTERMEDIATE_SECONDARY_ID]: 'EH-KVK2',
sid: 'test5',
id: 'xx-bsn-xx',
} as TokenData
);

Expand All @@ -192,19 +198,21 @@ describe('auth-helpers', () => {

const resMock = ResponseMock.new();

(resMock as any).oidc = {
logout: vi.fn(),
};

const addToBlackListSpy = vi.spyOn(blacklist, 'addToBlackList');

const nowInSeconds = millisecondsToSeconds(Date.now());

beforeEach(() => {
resMock.oidc.logout.mockClear();
addToBlackListSpy.mockClear();
});

test('Authenticated IDP logout', async () => {
test('Authenticated IDP logout calls oidc.logout', async () => {
const handler = createLogoutHandler('http://foo.bar');

reqMock[OIDC_SESSION_COOKIE_NAME]!.expires_at =
nowInSeconds + ONE_MINUTE_SECONDS; // Expires in one minute

await handler(reqMock, resMock);

expect(resMock.oidc.logout).toHaveBeenCalledWith({
Expand All @@ -220,16 +228,28 @@ describe('auth-helpers', () => {
);
});

test('Local logout', async () => {
const handler2 = createLogoutHandler('http://foo.bar', false);
test('Expired authenticated IDP logout should not call oidc.logout', async () => {
const handler = createLogoutHandler('http://foo.bar');

reqMock[OIDC_SESSION_COOKIE_NAME]!.expires_at =
nowInSeconds - ONE_MINUTE_SECONDS; // Expired one minute ago

await handler(reqMock, resMock);

expect(resMock.oidc.logout).not.toHaveBeenCalled();
expect(addToBlackListSpy).not.toHaveBeenCalled();
});

test('Local logout should not call oidc.logout', async () => {
const handler2 = createLogoutHandler('http://foo.bar', false);
await handler2(reqMock, resMock);

expect(resMock.clearCookie).toHaveBeenCalled();
expect(resMock.redirect).toHaveBeenCalledWith('http://foo.bar');
expect(addToBlackListSpy).not.toHaveBeenCalled();
});
});

describe('getReturnToUrl', () => {
test('getReturnToUrl should return the corrent zaak-status url', () => {
const url = getReturnToUrl({
Expand Down
48 changes: 29 additions & 19 deletions src/server/auth/auth-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { millisecondsToSeconds } from 'date-fns/millisecondsToSeconds';
import type { Request, Response } from 'express';
import * as jose from 'jose';
import { ParsedQs } from 'qs';
Expand Down Expand Up @@ -89,6 +90,7 @@ export function getAuth(req: Request) {
return {
token: oidcToken,
profile,
expiresAt: maSession.expires_at,
};
}

Expand Down Expand Up @@ -126,31 +128,39 @@ export function decodeToken<T extends Record<string, string>>(
return jose.decodeJwt(jwtToken) as unknown as T;
}

function isIDPSessionExpired(expiresAtInSeconds: number) {
return expiresAtInSeconds < millisecondsToSeconds(Date.now());
}

export function createLogoutHandler(
postLogoutRedirectUrl: string,
doIDPLogout: boolean = true
) {
return async (req: AuthenticatedRequest, res: Response) => {
if (req.oidc.isAuthenticated() && doIDPLogout) {
const auth = getAuth(req);
if (auth) {
// Add the session ID to a blacklist. This way the jwt id_token, which itself has longer lifetime, cannot be reused after logging out at IDP.
if (auth.profile.sid) {
await addToBlackList(auth.profile.sid);
}

return res.oidc.logout({
returnTo: postLogoutRedirectUrl,
logoutParams: {
id_token_hint: !FeatureToggle.oidcLogoutHintActive
? auth.token
: null,
logout_hint: FeatureToggle.oidcLogoutHintActive
? req[OIDC_SESSION_COOKIE_NAME]?.TMASessionID
: null,
},
});
const auth = getAuth(req);
if (
doIDPLogout &&
auth &&
auth.expiresAt &&
!isIDPSessionExpired(auth.expiresAt) &&
req.oidc.isAuthenticated()
) {
// Add the session ID to a blacklist. This way the jwt id_token, which itself has longer lifetime, cannot be reused after logging out at IDP.
if (auth.profile.sid) {
await addToBlackList(auth.profile.sid);
}

return res.oidc.logout({
returnTo: postLogoutRedirectUrl,
logoutParams: {
id_token_hint: !FeatureToggle.oidcLogoutHintActive
? auth.token
: null,
logout_hint: FeatureToggle.oidcLogoutHintActive
? req[OIDC_SESSION_COOKIE_NAME]?.TMASessionID
: null,
},
});
}

if (hasSessionCookie(req)) {
Expand Down
2 changes: 0 additions & 2 deletions src/server/auth/auth-session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { pool } from '../services/db/postgres';

type SessionStoreOptions = {
tableName: string;
ttlSeconds?: number;
};

export function getSessionStore<T extends typeof expressSession>(
Expand All @@ -25,7 +24,6 @@ export function getSessionStore<T extends typeof expressSession>(
tableName: options.tableName,
pool,
createTableIfMissing: true,
ttl: options.ttlSeconds,
}) as unknown as SessionStore<Session>;
}

Expand Down
3 changes: 2 additions & 1 deletion src/server/auth/auth-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ export interface AuthProfile {
sid: SessionID;
}

export interface MaSession extends Session {
export interface MaSession extends Omit<Session, 'expires_at'> {
sid: SessionID;
TMASessionID: string; // TMA Session ID
profileType: ProfileType;
authMethod: AuthMethod;
expires_at: number;
}

export interface AuthProfileAndToken {
Expand Down
4 changes: 2 additions & 2 deletions src/server/helpers/file-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { describe, expect, it, vi } from 'vitest';
import FileCache from './file-cache';

vi.mock('flat-cache', () => {
const cache: { [key: string]: any } = {};
const cache: { [key: string]: unknown } = {};

return {
default: vi.fn(),
setKey: vi.fn(),
create: () => ({
set: (key: string, data: any) => {
set: (key: string, data: unknown) => {
cache[key] = data;
},
get: (key: string) => cache[key],
Expand Down
2 changes: 2 additions & 0 deletions src/server/routing/route-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,13 @@ export function verifyAuthenticated(
) {
return async (req: Request, res: Response) => {
if (await isRequestAuthenticated(req, authMethod)) {
const auth = getAuth(req);
return res.send(
apiSuccessResult({
isAuthenticated: true,
profileType,
authMethod,
expiresAt: auth?.expiresAt,
})
);
}
Expand Down
2 changes: 2 additions & 0 deletions src/server/routing/router-oidc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ describe('router-oids', () => {
authMethod: 'digid',
isAuthenticated: true,
profileType: 'private',
expiresAt: expect.any(Number),
},
status: 'OK',
});
Expand All @@ -64,6 +65,7 @@ describe('router-oids', () => {
authMethod: 'eherkenning',
isAuthenticated: true,
profileType: 'commercial',
expiresAt: expect.any(Number),
},
status: 'OK',
});
Expand Down
16 changes: 9 additions & 7 deletions src/server/services/buurt/buurt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
DEFAULT_TRIES_UNTIL_CONSIDERED_STALE,
DatasetConfig,
DatasetFeatureProperties,
DatasetFeatures,
} from './datasets';
import {
createDynamicFilterConfig,
Expand All @@ -28,7 +29,6 @@ import { jsonCopy, omit } from '../../../universal/helpers/utils';
import FileCache from '../../helpers/file-cache';
import { requestData } from '../../helpers/source-api-request';


const DUMMY_DATA_RESPONSE = apiSuccessResult([
{ properties: { foo: 'bar', bar: undefined } },
{ properties: { foo: 'hop', bar: true } },
Expand All @@ -54,7 +54,7 @@ const datasetId3 = 'test-dataset-error';
const datasetConfig: DatasetConfig = {
listUrl: 'http://url.to/api/foo',
detailUrl: 'http://url.to/api/detail/foo/',
transformList: (r: any) => r,
transformList: (r: unknown) => r as DatasetFeatures<DatasetFeatureProperties>,
featureType: 'Point',
cacheTimeMinutes: BUURT_CACHE_TTL_1_DAY_IN_MINUTES,
triesUntilConsiderdStale: 5,
Expand All @@ -63,7 +63,7 @@ const datasetConfig: DatasetConfig = {
const datasetConfig2: DatasetConfig = {
listUrl: 'http://url.to/api/hello',
detailUrl: 'http://url.to/api/detail/hello/',
transformList: (r: any) => r,
transformList: (r: unknown) => r as DatasetFeatures<DatasetFeatureProperties>,
featureType: 'Point',
cacheTimeMinutes: BUURT_CACHE_TTL_1_DAY_IN_MINUTES,
triesUntilConsiderdStale: 5,
Expand All @@ -72,7 +72,7 @@ const datasetConfig2: DatasetConfig = {
const datasetConfig3: DatasetConfig = {
listUrl: 'http://url.to/api/not-found',
detailUrl: 'http://url.to/api/not-found/hello/',
transformList: (r: any) => r,
transformList: (r: unknown) => r as DatasetFeatures<DatasetFeatureProperties>,
featureType: 'Point',
cacheTimeMinutes: BUURT_CACHE_TTL_1_DAY_IN_MINUTES,
triesUntilConsiderdStale: 5,
Expand Down Expand Up @@ -382,15 +382,17 @@ describe('Buurt services', () => {
const detailItemId = 'x-detail';

datasetConfig2.transformDetail = (
responseData: any,
responseData: unknown,
options: DatasetFeatureProperties
) => {
const cachedFeatures = options.datasetCache.getKey('features');
const cachedFeatures = (options.datasetCache as FileCache).getKey<
string[]
>('features');
expect(responseData).toBe(null);
expect(options.id).toBe(detailItemId);
expect(options.datasetId).toBe(datasetId);
expect(cachedFeatures).toStrictEqual(features);
return cachedFeatures[0];
return cachedFeatures?.[0];
};

(getDatasetEndpointConfig as Mock).mockReturnValueOnce([
Expand Down
Loading