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

[DCMAW-10830] update session state in /async/biometricToken #340

Merged
merged 15 commits into from
Jan 21, 2025
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
8 changes: 8 additions & 0 deletions backend-api/docs/sessionStateMachine.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Session State Machine

The auth session for the async backend follows a forward-only state machine, as illustrated below.

```mermaid
flowchart LR
ASYNC_AUTH_SESSION_CREATED == start biometric session ==> ASYNC_BIOMETRIC_TOKEN_ISSUED
```
64 changes: 57 additions & 7 deletions backend-api/src/functions/adapters/dynamoDbAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
QueryCommand,
QueryCommandInput,
QueryCommandOutput,
UpdateItemCommand,
} from "@aws-sdk/client-dynamodb";
import { CreateSessionAttributes } from "../services/session/sessionService";
import { NodeHttpHandler } from "@smithy/node-http-handler";
Expand All @@ -14,14 +15,19 @@ import {
NativeAttributeValue,
unmarshall,
} from "@aws-sdk/util-dynamodb";

const sessionStates = {
ASYNC_AUTH_SESSION_CREATED: "ASYNC_AUTH_SESSION_CREATED",
};
import { UpdateSessionOperation } from "../common/session/updateOperations/UpdateSessionOperation";
import { emptySuccess, errorResult, Result } from "../utils/result";
import {
SessionRegistry,
UpdateSessionError,
} from "../common/session/SessionRegistry";
import { logger } from "../common/logging/logger";
import { LogMessage } from "../common/logging/LogMessage";
import { SessionState } from "../common/session/session";

export type DatabaseRecord = Record<string, NativeAttributeValue>;

export class DynamoDbAdapter {
export class DynamoDbAdapter implements SessionRegistry {
private readonly tableName: string;
private readonly dynamoDbClient = new DynamoDBClient({
region: process.env.REGION,
Expand All @@ -48,7 +54,7 @@ export class DynamoDbAdapter {
FilterExpression: "sessionState = :sessionState",
ExpressionAttributeValues: {
":subjectIdentifier": marshall(subjectIdentifier),
":sessionState": marshall(sessionStates.ASYNC_AUTH_SESSION_CREATED),
":sessionState": marshall(SessionState.AUTH_SESSION_CREATED),
":currentTimeInSeconds": marshall(this.getTimeNowInSeconds()),
},
ProjectionExpression: this.formatAsProjectionExpression(attributesToGet),
Expand Down Expand Up @@ -94,7 +100,7 @@ export class DynamoDbAdapter {
createdAt: Date.now(),
issuer: issuer,
sessionId: sessionId,
sessionState: sessionStates.ASYNC_AUTH_SESSION_CREATED,
sessionState: SessionState.AUTH_SESSION_CREATED,
clientState: state,
subjectIdentifier: sub,
timeToLive: timeToLive,
Expand All @@ -114,6 +120,50 @@ export class DynamoDbAdapter {
}
}

async updateSession(
sessionId: string,
updateOperation: UpdateSessionOperation,
): Promise<Result<void, UpdateSessionError>> {
const updateExpressionDataToLog = {
updateExpression: updateOperation.getDynamoDbUpdateExpression(),
conditionExpression: updateOperation.getDynamoDbConditionExpression(),
};

try {
logger.debug(LogMessage.UPDATE_SESSION_ATTEMPT, {
data: updateExpressionDataToLog,
});
await this.dynamoDbClient.send(
new UpdateItemCommand({
TableName: this.tableName,
Key: {
sessionId: { S: sessionId },
},
UpdateExpression: updateOperation.getDynamoDbUpdateExpression(),
jmooney-dd marked this conversation as resolved.
Show resolved Hide resolved
ConditionExpression: updateOperation.getDynamoDbConditionExpression(),
ExpressionAttributeValues:
updateOperation.getDynamoDbExpressionAttributeValues(),
}),
);
} catch (error) {
if (error instanceof ConditionalCheckFailedException) {
logger.error(LogMessage.UPDATE_SESSION_CONDITIONAL_CHECK_FAILURE, {
error: error.message,
data: updateExpressionDataToLog,
});
return errorResult(UpdateSessionError.CONDITIONAL_CHECK_FAILURE);
} else {
logger.error(LogMessage.UPDATE_SESSION_UNEXPECTED_FAILURE, {
error: error,
data: updateExpressionDataToLog,
});
return errorResult(UpdateSessionError.INTERNAL_SERVER_ERROR);
}
}
logger.debug(LogMessage.UPDATE_SESSION_SUCCESS);
return emptySuccess();
}

private getTimeNowInSeconds() {
return Math.floor(Date.now() / 1000);
}
Expand Down
150 changes: 150 additions & 0 deletions backend-api/src/functions/adapters/tests/dynamoDbAdapter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { expect } from "@jest/globals";
import "dotenv/config";
import "../../testUtils/matchers";
import { DynamoDbAdapter } from "../dynamoDbAdapter";
import { BiometricTokenIssued } from "../../common/session/updateOperations/BiometricTokenIssued/BiometricTokenIssued";
import {
SessionRegistry,
UpdateSessionError,
} from "../../common/session/SessionRegistry";
import {
ConditionalCheckFailedException,
DynamoDBClient,
UpdateItemCommand,
} from "@aws-sdk/client-dynamodb";
import { mockClient } from "aws-sdk-client-mock";
import { emptySuccess, errorResult, Result } from "../../utils/result";
import { UpdateSessionOperation } from "../../common/session/updateOperations/UpdateSessionOperation";

const mockDynamoDbClient = mockClient(DynamoDBClient);

let sessionRegistry: SessionRegistry;
let consoleErrorSpy: jest.SpyInstance;
let consoleDebugSpy: jest.SpyInstance;

describe("DynamoDbAdapter", () => {
beforeEach(() => {
sessionRegistry = new DynamoDbAdapter("mock_table_name");
consoleErrorSpy = jest.spyOn(console, "error");
consoleDebugSpy = jest.spyOn(console, "debug");
});
describe("updateSession", () => {
let result: Result<void, UpdateSessionError>;

const updateOperation: UpdateSessionOperation = new BiometricTokenIssued(
"NFC_PASSPORT",
"mock_opaque_id",
);

describe("On every attempt", () => {
beforeEach(async () => {
await sessionRegistry.updateSession("mock_session_id", updateOperation);
});

it("Logs the attempt", () => {
expect(consoleDebugSpy).toHaveBeenCalledWithLogFields({
messageCode: "MOBILE_ASYNC_UPDATE_SESSION_ATTEMPT",
data: {
updateExpression: updateOperation.getDynamoDbUpdateExpression(),
conditionExpression:
updateOperation.getDynamoDbConditionExpression(),
},
});
});
});

describe("When a conditional check fails", () => {
beforeEach(async () => {
mockDynamoDbClient.on(UpdateItemCommand).rejects(
new ConditionalCheckFailedException({
$metadata: {},
message: "Conditional check failed",
}),
);
result = await sessionRegistry.updateSession(
"mock_session_id",
updateOperation,
);
});

it("Logs the failure", () => {
expect(consoleErrorSpy).toHaveBeenCalledWithLogFields({
messageCode: "MOBILE_ASYNC_UPDATE_SESSION_CONDITIONAL_CHECK_FAILURE",
error: "Conditional check failed",
data: {
updateExpression: updateOperation.getDynamoDbUpdateExpression(),
conditionExpression:
updateOperation.getDynamoDbConditionExpression(),
},
});
});

it("Returns failure with conditional check failure error", () => {
chris-cooksley-gds marked this conversation as resolved.
Show resolved Hide resolved
expect(result).toEqual(
errorResult(UpdateSessionError.CONDITIONAL_CHECK_FAILURE),
);
});
});

describe("When there is an unexpected error updating the session", () => {
beforeEach(async () => {
mockDynamoDbClient.on(UpdateItemCommand).rejects("mock_error");
result = await sessionRegistry.updateSession(
"mock_session_id",
updateOperation,
);
});

it("Logs the failure", () => {
expect(consoleErrorSpy).toHaveBeenCalledWithLogFields({
messageCode: "MOBILE_ASYNC_UPDATE_SESSION_UNEXPECTED_FAILURE",
data: {
updateExpression: updateOperation.getDynamoDbUpdateExpression(),
conditionExpression:
updateOperation.getDynamoDbConditionExpression(),
},
});
});

it("Returns failure with server error", () => {
expect(result).toEqual(
errorResult(UpdateSessionError.INTERNAL_SERVER_ERROR),
);
});
});

describe("Given the session is successfully updated", () => {
beforeEach(async () => {
const expectedUpdateItemCommandInput = {
TableName: "mock_table_name",
Key: {
sessionId: { S: "mock_session_id" },
},
UpdateExpression: updateOperation.getDynamoDbUpdateExpression(),
ConditionExpression: updateOperation.getDynamoDbConditionExpression(),
ExpressionAttributeValues:
updateOperation.getDynamoDbExpressionAttributeValues(),
};
mockDynamoDbClient
.onAnyCommand() // default
.rejects("Did not receive expected input")
.on(UpdateItemCommand, expectedUpdateItemCommandInput, true) // match to expected input
.resolves({});
result = await sessionRegistry.updateSession(
"mock_session_id",
updateOperation,
);
});

it("Logs the success", () => {
expect(consoleDebugSpy).toHaveBeenCalledWithLogFields({
messageCode: "MOBILE_ASYNC_UPDATE_SESSION_SUCCESS",
});
});

it("Returns an empty success", () => {
expect(result).toEqual(emptySuccess());
});
});
});
});
Loading