-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler.ts
More file actions
174 lines (139 loc) · 6.45 KB
/
handler.ts
File metadata and controls
174 lines (139 loc) · 6.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from "aws-lambda";
import { writeCompletedCheck } from "./helpers/write-completed-check";
import { NinoCheckFunctionConfig } from "./helpers/function-config";
import { saveTxn, handleResponseAndSaveAttempt } from "./helpers/nino";
import { getHmrcConfig } from "../../common/src/config/get-hmrc-config";
import { CriError, formatErrorResponse } from "@govuk-one-login/cri-error-response";
import { dynamoDBClient } from "../../common/src/util/dynamo";
import { logger } from "@govuk-one-login/cri-logger";
import { LambdaInterface } from "@aws-lambda-powertools/commons/types";
import { captureMetric, metrics } from "@govuk-one-login/cri-metrics";
import { getTokenFromOtg } from "../../common/src/hmrc-apis/otg";
import { callPdvMatchingApi } from "../../common/src/hmrc-apis/pdv";
import { safeStringifyError } from "../../common/src/util/stringify-error";
import { buildPdvInput } from "./helpers/build-pdv-input";
import { ParsedPdvMatchResponse } from "../../common/src/hmrc-apis/types/pdv";
import { getRecordBySessionId, getSessionBySessionId } from "../../common/src/database/get-record-by-session-id";
import { PersonIdentityItem } from "@govuk-one-login/cri-types";
import { getAttempts } from "../../common/src/database/get-attempts";
import { buildAndSendAuditEvent } from "@govuk-one-login/cri-audit";
import { AUDIT_EVENT_TYPE } from "../../common/src/types/audit";
const MAX_PAST_ATTEMPTS = 1;
type InputBody = {
nino: string;
};
class NinoCheckHandler implements LambdaInterface {
@logger.injectLambdaContext({ resetKeys: true })
@metrics.logMetrics({ throwOnEmptyMetrics: false, captureColdStartMetric: true })
public async handler({ body, headers }: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
try {
logger.info(`${context.functionName} invoked.`);
const sessionId = headers["session-id"] as string;
const deviceInformationHeader = headers["txma-audit-encoded"];
const { nino } = JSON.parse(body as string) as InputBody;
const functionConfig = new NinoCheckFunctionConfig();
logger.info(`Function initialised. Retrieving session...`);
const session = await getSessionBySessionId(functionConfig.tableNames.sessionTable, sessionId);
logger.appendKeys({
govuk_signin_journey_id: session.clientSessionId,
});
logger.info(`Identified government journey id: ${session.clientSessionId}. Retrieving HMRC config from SSM...`);
const hmrcApiConfig = await getHmrcConfig(session.clientId);
logger.info(`HMRC config retrieved from SSM.`);
const { count: pastAttemptCount } = await getAttempts(
functionConfig.tableNames.attemptTable,
dynamoDBClient,
sessionId
);
if (pastAttemptCount > MAX_PAST_ATTEMPTS) {
captureMetric(`AttemptsExceededMetric`);
logger.info(`Too many attempts. Returning requestRetry: false.`);
return { statusCode: 200, body: JSON.stringify({ requestRetry: false }) };
}
const isFinalAttempt = pastAttemptCount === MAX_PAST_ATTEMPTS;
logger.info(`User has ${pastAttemptCount} past attempts. Retrieving person identity...`);
const personIdentity = await getRecordBySessionId<PersonIdentityItem>(
dynamoDBClient,
functionConfig.tableNames.personIdentityTable,
sessionId,
"expiryDate"
);
logger.info(
`Retrieved session and person identity. isFinalAttempt=${isFinalAttempt}. Validating provided NINo information...`
);
const token = await getTokenFromOtg(hmrcApiConfig.otg);
logger.info(`Successfully retrieved OAuth token from HMRC. Proceeding with PDV request...`);
const auditDeviceInformation = deviceInformationHeader
? {
device_information: {
encoded: deviceInformationHeader,
},
}
: undefined;
await buildAndSendAuditEvent(
functionConfig.audit.queueUrl,
AUDIT_EVENT_TYPE.REQUEST_SENT,
functionConfig.audit.componentId,
session,
{
restricted: {
birthDate: personIdentity.birthDates,
name: personIdentity.names,
socialSecurityRecord: [
{
personalNumber: nino,
},
],
...auditDeviceInformation,
},
}
);
logger.info(`REQUEST_SENT event fired.`);
let parsedPdvMatchResponse: ParsedPdvMatchResponse;
try {
parsedPdvMatchResponse = await callPdvMatchingApi(
hmrcApiConfig.pdv,
token,
buildPdvInput(personIdentity, nino)
);
} catch (error) {
logger.error(`Error in ${context.functionName}: ${safeStringifyError(error)}`);
throw new CriError(500, "Unexpected error when validating NINo");
}
logger.info(`Called matching API successfully. Saving txn against user session...`);
await saveTxn(dynamoDBClient, functionConfig.tableNames.sessionTable, sessionId, parsedPdvMatchResponse.txn);
logger.info(`Saved txn.`);
await buildAndSendAuditEvent(
functionConfig.audit.queueUrl,
AUDIT_EVENT_TYPE.RESPONSE_RECEIVED,
functionConfig.audit.componentId,
session,
{
restricted: auditDeviceInformation,
extensions: { evidence: { txn: parsedPdvMatchResponse.txn } },
}
);
logger.info(`RESPONSE_RECEIVED event fired.`);
const ninoMatch = await handleResponseAndSaveAttempt(
dynamoDBClient,
functionConfig.tableNames.attemptTable,
session,
parsedPdvMatchResponse
);
logger.info(`Completed NINo verification - ninoMatch=${ninoMatch}.`);
if (!ninoMatch && !isFinalAttempt) {
captureMetric(`RetryAttemptsSentMetric`);
logger.info(`Failed to verify. This was not the last attempt - requesting the user retries.`);
return { statusCode: 200, body: JSON.stringify({ requestRetry: true }) };
}
logger.info(`No need for further retries. Issuing authorization code...`);
await writeCompletedCheck(dynamoDBClient, functionConfig.tableNames, session, nino);
logger.info(`Authorization code saved. Returning...`);
return { statusCode: 200, body: JSON.stringify({ requestRetry: false }) };
} catch (error) {
return formatErrorResponse(error);
}
}
}
const handlerClass = new NinoCheckHandler();
export const handler = handlerClass.handler.bind(handlerClass);