-
Notifications
You must be signed in to change notification settings - Fork 2
OJ-3227 - Implement initial issue-credential function #648
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
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| export type AccessTokenIndexSessionItem = { | ||
| sessionId: string; | ||
| accessToken: string; | ||
| subject: string; | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| import type { Config } from "jest"; | ||
| import baseConfig from "../../jest.config.base"; | ||
|
|
||
| export default { | ||
| ...baseConfig, | ||
| displayName: "lambdas/issue-credential", | ||
| } satisfies Config; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| { | ||
| "name": "issue-credential-handler", | ||
| "description": "", | ||
| "scripts": { | ||
| "lint": "eslint .", | ||
| "lint:fix": "eslint . --fix", | ||
| "unit": "jest --silent", | ||
| "test": "npm run unit --", | ||
| "test:coverage": "npm run unit -- --coverage", | ||
| "deploy": "../../deploy.sh", | ||
| "compile": "tsc" | ||
| }, | ||
| "dependencies": { | ||
| "@aws-lambda-powertools/commons": "1.14.2", | ||
| "@aws-lambda-powertools/logger": "2.3.0", | ||
| "@aws-lambda-powertools/parameters": "2.21.0", | ||
| "@aws-sdk/client-dynamodb": "3.828.0", | ||
| "@aws-sdk/client-eventbridge": "3.828.0", | ||
| "@aws-sdk/util-dynamodb": "3.828.0" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/aws-lambda": "^8.10.150", | ||
| "@types/jest": "^29.5.5", | ||
| "@typescript-eslint/eslint-plugin": "^8.13.0", | ||
| "@typescript-eslint/parser": "^8.13.0", | ||
| "aws-sdk-client-mock": "4.1.0", | ||
| "aws-sdk-client-mock-jest": "4.1.0", | ||
| "eslint": "^8.53.0", | ||
| "eslint-config-prettier": "^9.1.0", | ||
| "eslint-plugin-prettier": "^5.2.1", | ||
| "jest": "^29.7.0", | ||
| "prettier": "^3.1.0", | ||
| "ts-jest": "^29.1.1", | ||
| "ts-node": "^10.9.2", | ||
| "typescript": "^5.3.2" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from "aws-lambda"; | ||
| import { initOpenTelemetry } from "../../open-telemetry/src/otel-setup"; | ||
| import { BaseFunctionConfig } from "../../common/src/config/base-function-config"; | ||
| import { CriError } from "../../common/src/errors/cri-error"; | ||
| import { handleErrorResponse } from "../../common/src/errors/cri-error-response"; | ||
| import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; | ||
| import { logger } from "../../common/src/util/logger"; | ||
| import { retrieveSessionIdByAccessToken } from "./helpers/retrieve-session-by-access-token"; | ||
| import { metrics } from "../../common/src/util/metrics"; | ||
| import { countAttempts } from "../../common/src/database/count-attempts"; | ||
| import { retrieveNinoUser } from "./helpers/retrieve-nino-user"; | ||
| import { LambdaInterface } from "@aws-lambda-powertools/commons"; | ||
| import { getRecordBySessionId } from "../../common/src/database/get-record-by-session-id"; | ||
| import { SessionItem } from "../../common/src/database/types/session-item"; | ||
|
|
||
| initOpenTelemetry(); | ||
|
|
||
| const dynamoClient = new DynamoDBClient(); | ||
|
|
||
| const functionConfig = new BaseFunctionConfig(); | ||
|
|
||
| class IssueCredentialHandler implements LambdaInterface { | ||
| @logger.injectLambdaContext({ resetKeys: true }) | ||
| @metrics.logMetrics({ throwOnEmptyMetrics: false, captureColdStartMetric: true }) | ||
| public async handler({ headers }: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> { | ||
| try { | ||
| logger.info(`${context.functionName} invoked.`); | ||
|
|
||
| const accessToken = (headers["Authorization"]?.match(/^Bearer [a-zA-Z0-9_-]+$/) ?? [])[0]; | ||
|
|
||
| if (!accessToken) throw new CriError(400, "You must provide a valid access token"); | ||
|
|
||
| const sessionId = await retrieveSessionIdByAccessToken( | ||
| functionConfig.tableNames.sessionTable, | ||
| dynamoClient, | ||
| accessToken | ||
| ); | ||
|
|
||
| const session = await getRecordBySessionId<SessionItem>( | ||
| dynamoClient, | ||
| functionConfig.tableNames.sessionTable, | ||
| sessionId, | ||
| "expiryDate" | ||
| ); | ||
|
|
||
| logger.appendKeys({ | ||
| govuk_signin_journey_id: session.clientSessionId, | ||
| }); | ||
| logger.info(`Identified government journey id: ${session.clientSessionId}`); | ||
|
|
||
| const failedAttemptCount = await countAttempts( | ||
| functionConfig.tableNames.attemptTable, | ||
| dynamoClient, | ||
| session.sessionId, | ||
| "FAIL" | ||
| ); | ||
| logger.info(`Identified ${failedAttemptCount} failed attempts.`); | ||
|
|
||
| const personIdentity = await getRecordBySessionId( | ||
| dynamoClient, | ||
| functionConfig.tableNames.personIdentityTable, | ||
| session.sessionId, | ||
| "expiryDate" | ||
| ); | ||
| logger.info(`Retrieved person identity.`); | ||
|
|
||
| const ninoUser = await retrieveNinoUser(functionConfig.tableNames.ninoUserTable, dynamoClient, session.sessionId); | ||
| logger.info(`Retrieved NINo-user entry.`); | ||
|
|
||
| return { | ||
| statusCode: 200, | ||
| body: JSON.stringify({ failedAttemptCount, personIdentity, ninoUser }), | ||
| }; | ||
| } catch (error) { | ||
| return handleErrorResponse(error, logger); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const handlerClass = new IssueCredentialHandler(); | ||
| export const handler = handlerClass.handler.bind(handlerClass); |
28 changes: 28 additions & 0 deletions
28
lambdas/issue-credential/src/helpers/retrieve-nino-user.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| import { getRecordBySessionId } from "../../../common/src/database/get-record-by-session-id"; | ||
| import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; | ||
| import { logger } from "../../../common/src/util/logger"; | ||
| import { RecordNotFoundError } from "../../../common/src/database/exceptions/errors"; | ||
| import { CriError } from "../../../common/src/errors/cri-error"; | ||
| import { safeStringifyError } from "../../../common/src/util/stringify-error"; | ||
| import { NinoUser } from "../../../common/src/types/nino-user"; | ||
|
|
||
| export async function retrieveNinoUser( | ||
| ninoUserTableName: string, | ||
| dynamoClient: DynamoDBClient, | ||
| sessionId: string | ||
| ): Promise<NinoUser> { | ||
| try { | ||
| const ninoUser = await getRecordBySessionId<NinoUser>(dynamoClient, ninoUserTableName, sessionId, "ttl"); | ||
|
|
||
| return ninoUser; | ||
| } catch (error) { | ||
| if (error instanceof RecordNotFoundError) { | ||
| logger.info(`No valid NINo user record found.`); | ||
| throw new CriError(500, `No NINo user entry found for the given session ID.`); | ||
| } | ||
|
|
||
| logger.error(`Caught unexpected NINo user retrieval error: ${safeStringifyError(error)}`); | ||
|
|
||
| throw new CriError(500, "Unexpected error getting NINo user"); | ||
| } | ||
| } |
53 changes: 53 additions & 0 deletions
53
lambdas/issue-credential/src/helpers/retrieve-session-by-access-token.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb"; | ||
| import { AccessTokenIndexSessionItem } from "../../../common/src/types/access-token-index-session-item"; | ||
| import { logger } from "../../../common/src/util/logger"; | ||
| import { CriError } from "../../../common/src/errors/cri-error"; | ||
| import { safeStringifyError } from "../../../common/src/util/stringify-error"; | ||
| import { unmarshall } from "@aws-sdk/util-dynamodb"; | ||
| import { withRetry } from "../../../common/src/util/retry"; | ||
|
|
||
| export async function retrieveSessionIdByAccessToken( | ||
| sessionTableName: string, | ||
| dynamoClient: DynamoDBClient, | ||
| accessToken: string | ||
| ): Promise<string> { | ||
| try { | ||
| async function sendQueryCommand() { | ||
| const command = new QueryCommand({ | ||
| TableName: sessionTableName, | ||
| IndexName: "access-token-index", | ||
| KeyConditionExpression: "accessToken = :value", | ||
| ExpressionAttributeValues: { | ||
| ":value": { | ||
| S: accessToken, | ||
| }, | ||
| }, | ||
| }); | ||
|
|
||
| const result = await dynamoClient.send(command); | ||
|
|
||
| if (result.Count === 0 || !result.Items) { | ||
| throw new CriError(400, `No session entry found for the given access token`); | ||
| } | ||
|
|
||
| const retrievedRecords = result.Items.map((v) => unmarshall(v)) as AccessTokenIndexSessionItem[]; | ||
|
|
||
| if (retrievedRecords.length > 1) { | ||
| throw new CriError(500, `Found ${retrievedRecords.length} session records but was only expecting 1.`); | ||
| } | ||
|
|
||
| return retrievedRecords[0].sessionId; | ||
| } | ||
|
|
||
| return await withRetry(sendQueryCommand, logger, { | ||
| maxRetries: 3, | ||
| baseDelay: 300, | ||
| }); | ||
| } catch (error) { | ||
| if (error instanceof CriError) throw error; | ||
|
|
||
| logger.error(`Caught unexpected session retrieval error: ${safeStringifyError(error)}`); | ||
|
|
||
| throw new CriError(500, "Unexpected error getting session information"); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.