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

CAMS-446 - Okta ad group bug #930

Merged
merged 4 commits into from
Sep 23, 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: 2 additions & 2 deletions backend/functions/azure/application-context-creator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import MockData from '../../../common/src/cams/test-utilities/mock-data';
import { ApplicationContext } from '../lib/adapters/types/basic';
import * as FeatureFlags from '../lib/adapters/utils/feature-flag';
import { ApplicationConfiguration } from '../lib/configs/application-configuration';
import { MockUserSessionGateway } from '../lib/testing/mock-gateways/mock-user-session-gateway';
import { MockUserSessionUseCase } from '../lib/testing/mock-gateways/mock-user-session-use-case';
import { createMockApplicationContext } from '../lib/testing/testing-utilities';
import ContextCreator from './application-context-creator';
import { createMockAzureFunctionContext, createMockAzureFunctionRequest } from './testing-helpers';
Expand Down Expand Up @@ -78,7 +78,7 @@ describe('Application Context Creator', () => {
const mockContext = await createMockApplicationContext();
mockContext.request = request;
const lookupSpy = jest
.spyOn(MockUserSessionGateway.prototype, 'lookup')
.spyOn(MockUserSessionUseCase.prototype, 'lookup')
.mockResolvedValue(MockData.getCamsSession());
await ContextCreator.getApplicationContextSession(mockContext);
expect(lookupSpy).toHaveBeenCalled();
Expand Down
7 changes: 3 additions & 4 deletions backend/functions/azure/application-context-creator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import { getFeatureFlags } from '../lib/adapters/utils/feature-flag';
import { LoggerImpl } from '../lib/adapters/services/logger.service';
import { azureToCamsHttpRequest } from './functions';
import { UnauthorizedError } from '../lib/common-errors/unauthorized-error';
import { getUserSessionGateway } from '../lib/factory';
import { SessionGateway } from '../lib/adapters/utils/session-gateway';
import { getUserSessionUseCase } from '../lib/factory';

const MODULE_NAME = 'APPLICATION-CONTEXT-CREATOR';

Expand Down Expand Up @@ -77,8 +76,8 @@ async function getApplicationContextSession(context: ApplicationContext) {
});
}

const sessionGateway: SessionGateway = getUserSessionGateway(context);
const session = await sessionGateway.lookup(
const sessionUseCase = getUserSessionUseCase(context);
const session = await sessionUseCase.lookup(
context,
accessToken,
context.config.authConfig.provider,
Expand Down
36 changes: 17 additions & 19 deletions backend/functions/lib/adapters/gateways/okta/okta-gateway.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ describe('Okta gateway tests', () => {
userInfoUri: 'something',
};
jest.spyOn(AuthorizationConfiguration, 'getAuthorizationConfig').mockReturnValue(authConfig);
await expect(gateway.verifyToken('test')).rejects.toThrow('Invalid provider.');
await expect(gateway.getUser('test')).rejects.toThrow('Invalid provider.');
});

test('Should receive invalid issuer error', async () => {
Expand All @@ -42,7 +42,7 @@ describe('Okta gateway tests', () => {
userInfoUri: 'something',
};
jest.spyOn(AuthorizationConfiguration, 'getAuthorizationConfig').mockReturnValue(authConfig);
await expect(gateway.verifyToken('test')).rejects.toThrow('Issuer not provided.');
await expect(gateway.getUser('test')).rejects.toThrow('Issuer not provided.');
});

test('Should receive invalid audience error', async () => {
Expand All @@ -53,18 +53,19 @@ describe('Okta gateway tests', () => {
userInfoUri: 'something',
};
jest.spyOn(AuthorizationConfiguration, 'getAuthorizationConfig').mockReturnValue(authConfig);
await expect(gateway.verifyToken('test')).rejects.toThrow('Audience not provided.');
await expect(gateway.getUser('test')).rejects.toThrow('Audience not provided.');
});

test('Should return valid Jwt when given valid token and audience', async () => {
test('Should return valid user with Jwt when given valid token and audience', async () => {
const token = 'testToken';
const jwtClaims = {
iss: 'https://fake.okta.com/oauth2/default',
sub: '[email protected]',
aud: 'api://default',
iat: 0,
exp: Math.floor(Date.now() / 1000) + 600,
groups: [],
ad_groups: ['groupA', 'groupB'],
groups: ['groupB', 'groupC'],
};
const jwtHeader = {
alg: 'RS256',
Expand All @@ -79,27 +80,24 @@ describe('Okta gateway tests', () => {
isNotBefore: jest.fn(),
};
jest.spyOn(Verifier, 'verifyAccessToken').mockResolvedValue(jwt);
const actual = await gateway.verifyToken(token);
expect(actual).toEqual(jwt);
});

test('Should throw UnauthorizedError if not given valid input ', async () => {
const token = 'testToken';
jest.spyOn(Verifier, 'verifyAccessToken').mockRejectedValue(new Error('Test error'));
await expect(gateway.verifyToken(token)).rejects.toThrow('Unauthorized');
});

test('getUser should return a valid response with user.name', async () => {
const userInfo = {
name: 'Test Name',
testAttribute: '',
};
const mockFetchResponse = MockFetch.ok(userInfo);
jest.spyOn(global, 'fetch').mockImplementation(mockFetchResponse);
const actualResponse = await gateway.getUser('testAccessToken');
const actual = await gateway.getUser(token);
expect(actual).toEqual({
user: { id: undefined, name: userInfo.name },
groups: ['groupA', 'groupB', 'groupC'],
jwt,
});
});

expect(actualResponse).not.toEqual(expect.objectContaining({ testAttribute: '' }));
expect(actualResponse).toEqual(expect.objectContaining({ name: 'Test Name' }));
test('Should throw UnauthorizedError if not given valid input ', async () => {
const token = 'testToken';
jest.spyOn(Verifier, 'verifyAccessToken').mockRejectedValue(new Error('Test error'));
await expect(gateway.getUser(token)).rejects.toThrow('Unauthorized');
});

test('getUser should throw Error if call failed', async () => {
Expand Down
30 changes: 24 additions & 6 deletions backend/functions/lib/adapters/gateways/okta/okta-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { UnauthorizedError } from '../../../common-errors/unauthorized-error';
import { verifyAccessToken } from './HumbleVerifier';
import { CamsUser } from '../../../../../../common/src/cams/users';
import { CamsJwt } from '../../../../../../common/src/cams/jwt';
import { isCamsError } from '../../../common-errors/cams-error';

const MODULE_NAME = 'OKTA-GATEWAY';

Expand Down Expand Up @@ -43,34 +44,51 @@ async function verifyToken(token: string): Promise<CamsJwt> {
}
}

async function getUser(accessToken: string): Promise<CamsUser> {
async function getUser(
accessToken: string,
): Promise<{ user: CamsUser; groups: string[]; jwt: CamsJwt }> {
const { userInfoUri } = getAuthorizationConfig();

try {
const jwt = await verifyToken(accessToken);
if (!jwt) {
throw new UnauthorizedError(MODULE_NAME, {
message: 'Unable to verify token.',
});
}

const response = await fetch(userInfoUri, {
method: 'GET',
headers: { authorization: 'Bearer ' + accessToken },
});

if (response.ok) {
const oktaUser = (await response.json()) as OktaUserInfo;
// TODO: We need to decide on the claim we will map to CamsUser.id
const camsUser: CamsUser = {
const user: CamsUser = {
id: oktaUser.sub,
name: oktaUser.name,
};

return camsUser;
type DojLoginUnifiedGroupClaims = {
ad_groups?: string[];
groups?: string[];
};

const claims = jwt.claims as unknown as DojLoginUnifiedGroupClaims;
const groups = Array.from(new Set<string>([].concat(claims.ad_groups, claims.groups)));

return { user, groups, jwt };
} else {
throw new Error('Failed to retrieve user info from Okta.');
}
} catch (originalError) {
throw new UnauthorizedError(MODULE_NAME, { originalError });
throw isCamsError(originalError)
? originalError
: new UnauthorizedError(MODULE_NAME, { originalError });
}
}

const OktaGateway: OpenIdConnectGateway = {
verifyToken,
getUser,
};

Expand Down
3 changes: 1 addition & 2 deletions backend/functions/lib/adapters/types/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ export type AuthorizationConfig = {
};

export interface OpenIdConnectGateway {
verifyToken: (accessToken: string) => Promise<CamsJwt>;
getUser: (accessToken: string) => Promise<CamsUser>;
getUser: (accessToken: string) => Promise<{ user: CamsUser; groups: string[]; jwt: CamsJwt }>;
}

export interface UserGroupGateway {
Expand Down
6 changes: 0 additions & 6 deletions backend/functions/lib/adapters/utils/session-gateway.ts

This file was deleted.

11 changes: 5 additions & 6 deletions backend/functions/lib/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ import { OpenIdConnectGateway, UserGroupGateway } from './adapters/types/authori
import OktaGateway from './adapters/gateways/okta/okta-gateway';
import { UserSessionCacheRepository } from './adapters/gateways/user-session-cache.repository';
import { UserSessionCacheCosmosDbRepository } from './adapters/gateways/user-session-cache.cosmosdb.repository';
import { SessionGateway } from './adapters/utils/session-gateway';
import { UserSessionGateway } from './adapters/gateways/user-session-gateway';
import { MockUserSessionGateway } from './testing/mock-gateways/mock-user-session-gateway';
import { MockUserSessionUseCase } from './testing/mock-gateways/mock-user-session-use-case';
import MockOpenIdConnectGateway from './testing/mock-gateways/mock-oauth2-gateway';
import { StorageGateway } from './adapters/types/storage';
import LocalStorageGateway from './adapters/gateways/storage/local-storage-gateway';
Expand All @@ -43,6 +41,7 @@ import { MockOrdersGateway } from './testing/mock-gateways/mock.orders.gateway';
import { MockOfficesGateway } from './testing/mock-gateways/mock.offices.gateway';
import { OfficesCosmosDbRepository } from './adapters/gateways/offices.cosmosdb.repository';
import OktaUserGroupGateway from './adapters/gateways/okta/okta-user-group-gateway';
import { UserSessionUseCase } from './use-cases/user-session/user-session';

export const getAttorneyGateway = (): AttorneyGatewayInterface => {
return MockAttorneysGateway;
Expand Down Expand Up @@ -147,11 +146,11 @@ export const getAuthorizationGateway = (context: ApplicationContext): OpenIdConn
return null;
};

export const getUserSessionGateway = (context: ApplicationContext): SessionGateway => {
export const getUserSessionUseCase = (context: ApplicationContext) => {
if (context.config.authConfig.provider === 'mock') {
return new MockUserSessionGateway();
return new MockUserSessionUseCase();
}
return new UserSessionGateway();
return new UserSessionUseCase();
};

export const getUserSessionCacheRepository = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,10 @@ export async function getUser(accessToken: string) {
const decodedToken = jwt.decode(accessToken);
const mockUser = mockUsers.find((role) => role.sub === decodedToken.sub);
addSuperUserOffices(mockUser.user);
return mockUser.user;
return { user: mockUser.user, groups: [], jwt: {} as CamsJwt };
}

const MockOpenIdConnectGateway: OpenIdConnectGateway = {
verifyToken,
getUser,
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as jwt from 'jsonwebtoken';
import { ApplicationContext } from '../../adapters/types/basic';
import { SessionGateway } from '../../adapters/utils/session-gateway';
import { getUser } from './mock-oauth2-gateway';
import { OFFICES } from '../../../../../common/src/cams/test-utilities/offices.mock';
import { CamsSession } from '../../../../../common/src/cams/session';
Expand All @@ -9,13 +8,13 @@ import { CamsJwtClaims } from '../../../../../common/src/cams/jwt';

const cache = new Map<string, CamsSession>();

export class MockUserSessionGateway implements SessionGateway {
export class MockUserSessionUseCase {
async lookup(
context: ApplicationContext,
accessToken: string,
provider: string,
): Promise<CamsSession> {
const user = await getUser(accessToken);
const { user } = await getUser(accessToken);

const parts = accessToken.split('.');
const key = parts[2];
Expand Down
Loading
Loading