Skip to content
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
12 changes: 6 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ instance_ip = $(shell aws ec2 describe-instances --region $(REGION) --instance-i
CSAV_IP = $(call instance_ip,secure-rads-csav,CsavInstanceId)
EXECUTION_API_URL = $(shell aws cloudformation describe-stacks --stack-name secure-rads-execution-service-dev --region $(REGION) \
--query "Stacks[0].Outputs[?OutputKey=='ExecutionApiUrl'].OutputValue" --output text)
PDM_TABLE = $(shell aws cloudformation describe-stacks --stack-name secure-rads-pdm-service-dev --region $(REGION) \
--query "Stacks[0].Outputs[?OutputKey=='PersonalDataTableName'].OutputValue" --output text)
PDM_TABLE_PREFIX = $(shell aws cloudformation describe-stacks --stack-name secure-rads-pdm-service-dev --region $(REGION) \
--query "Stacks[0].Outputs[?OutputKey=='PdmTablePrefix'].OutputValue" --output text)
DATA_KEY_TABLE = $(shell aws cloudformation describe-stacks --stack-name secure-rads-pdm-service-dev --region $(REGION) \
--query "Stacks[0].Outputs[?OutputKey=='DataKeyTableName'].OutputValue" --output text)
# registry-service stores each algorithm's per-algo KMS key ARN here; seeding reads it to encrypt the records.
Expand Down Expand Up @@ -198,7 +198,7 @@ secure-rads-ready:
# envelope-encrypted under each algorithm's per-algo KMS key, so the algorithm must be built first
# (make secure-rads-build), which provisions that key and stores its ARN in the AlgorithmTable.
secure-rads-seed:
cd seeding && bun install && bun run generate && PDM_TABLE=$(PDM_TABLE) DATA_KEY_TABLE=$(DATA_KEY_TABLE) ALGORITHM_TABLE=$(ALGORITHM_TABLE) AWS_REGION=$(REGION) bun run seed-secure-rads
cd seeding && bun install && bun run generate && PDM_TABLE_PREFIX=$(PDM_TABLE_PREFIX) DATA_KEY_TABLE=$(DATA_KEY_TABLE) ALGORITHM_TABLE=$(ALGORITHM_TABLE) AWS_REGION=$(REGION) bun run seed-secure-rads

# Build phase (one app): make secure-rads-build APP=<dir> ALGORITHM_ID=<id>.
# Builds the arm64 image, ships it to the csav host, and registers it under ALGORITHM_ID.
Expand Down Expand Up @@ -262,8 +262,8 @@ RADS_REGISTRY_URL = $(shell aws cloudformation describe-stacks --stack-name rads
--query "Stacks[0].Outputs[?OutputKey=='HttpApiUrl'].OutputValue" --output text)
RADS_EXECUTION_API_URL = $(shell aws cloudformation describe-stacks --stack-name rads-execution-service-dev --region $(REGION) \
--query "Stacks[0].Outputs[?OutputKey=='HttpApiUrl'].OutputValue" --output text)
RADS_PDM_TABLE = $(shell aws cloudformation describe-stacks --stack-name rads-pdm-service-dev --region $(REGION) \
--query "Stacks[0].Outputs[?OutputKey=='PersonalDataTableName'].OutputValue" --output text)
RADS_PDM_TABLE_PREFIX = $(shell aws cloudformation describe-stacks --stack-name rads-pdm-service-dev --region $(REGION) \
--query "Stacks[0].Outputs[?OutputKey=='PdmTablePrefix'].OutputValue" --output text)

# Build phase (one app): make rads-build APP=<dir> ALGORITHM_ID=<id>.
# Builds the arm64 image, gets a presigned S3 PUT URL from /upload, uploads the tarball straight to S3, then
Expand All @@ -290,7 +290,7 @@ rads-build-all:

# Seed all five context datasets into the rads PDM table as plaintext, each under its fixed algorithmId.
rads-seed:
cd seeding && bun install && bun run generate && RADS_PDM_TABLE=$(RADS_PDM_TABLE) AWS_REGION=$(REGION) bun run seed-rads
cd seeding && bun install && bun run generate && PDM_TABLE_PREFIX=$(RADS_PDM_TABLE_PREFIX) AWS_REGION=$(REGION) bun run seed-rads

# Execution phase (one run): make rads-run ALGORITHM_ID=<id>.
# Fires /run (202 + runId), then polls GET /run/{runId} until the runner reports back.
Expand Down
3 changes: 1 addition & 2 deletions benchmark/src/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,9 @@ def generate() -> None:

def _seed_env(tree: Tree, outputs: SeedOutputs, dataset: str) -> dict[str, str]:
env = {"AWS_REGION": config.REGION, "SEED_DATASET": dataset}
env["PDM_TABLE_PREFIX"] = outputs[tree]["pdm"].get("PdmTablePrefix", "")
if tree is Tree.RADS:
env["RADS_PDM_TABLE"] = outputs[Tree.RADS]["pdm"].get("PersonalDataTableName", "")
return env
env["PDM_TABLE"] = outputs[Tree.SECURE_RADS]["pdm"].get("PersonalDataTableName", "")
env["DATA_KEY_TABLE"] = outputs[Tree.SECURE_RADS]["pdm"].get("DataKeyTableName", "")
env["ALGORITHM_TABLE"] = outputs[Tree.SECURE_RADS]["registry_storage"].get("AlgorithmTableName", "")
return env
Expand Down
2 changes: 1 addition & 1 deletion rads/pdm-service/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# rads-pdm-service

Serverless Framework v4, TypeScript. The Personal Data Management Service for the baseline: stores per-user personal-data records keyed by `AlgorithmId` in DynamoDB as plaintext JSON and serves them to the executor.
Serverless Framework v4, TypeScript. The Personal Data Management Service for the baseline: stores per-user personal-data records as plaintext JSON in one DynamoDB table per algorithm, named `<PDM_TABLE_PREFIX>-<algorithmId>`, and serves them to the executor. The stack does not own the tables; seeding creates them.

## Endpoints

Expand Down
24 changes: 4 additions & 20 deletions rads/pdm-service/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ provider:
statements:
- Effect: Allow
Action: dynamodb:Query
Resource: !GetAtt PersonalDataTable.Arn
Resource: !Sub "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/rads-personal-data-*"
environment:
PDM_TABLE: !Ref PersonalDataTable
PDM_TABLE_PREFIX: rads-personal-data
LOG_HOST: ${env:LOG_HOST_RADS}
COST_HOST: ${env:COST_HOST_RADS}

Expand Down Expand Up @@ -64,24 +64,8 @@ resources:
ApiId: !Ref HttpApi
Stage: !Ref HttpApiStage

PersonalDataTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: rads-personal-data
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: AlgorithmId
AttributeType: S
- AttributeName: RecordId
AttributeType: S
KeySchema:
- AttributeName: AlgorithmId
KeyType: HASH
- AttributeName: RecordId
KeyType: RANGE

Outputs:
PersonalDataTableName:
Value: !Ref PersonalDataTable
PdmTablePrefix:
Value: rads-personal-data
ApiRegionalDomainName:
Value: !GetAtt ApiCustomDomain.RegionalDomainName
8 changes: 6 additions & 2 deletions rads/pdm-service/src/handlers/count.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { requiredEnv } from "@srads/common/env";
import type { APIGatewayProxyHandlerV2 } from "aws-lambda";

const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const table = requiredEnv("PDM_TABLE");
const tablePrefix = requiredEnv("PDM_TABLE_PREFIX");
const ALGORITHM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

const MAX_QUERY_ATTEMPTS = 8;

Expand Down Expand Up @@ -35,6 +36,9 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
if (!algorithmId) {
return jsonResponse(400, { error: "missing algorithmId" });
}
if (!ALGORITHM_ID.test(algorithmId)) {
return jsonResponse(400, { error: "invalid algorithmId" });
}

const size = event.queryStringParameters?.size;
let atLeast: number | undefined;
Expand All @@ -53,7 +57,7 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
do {
const page = await queryWithRetry(
new QueryCommand({
TableName: table,
TableName: `${tablePrefix}-${algorithmId}`,
KeyConditionExpression: "AlgorithmId = :a",
ExpressionAttributeValues: { ":a": algorithmId },
Select: "COUNT",
Expand Down
8 changes: 6 additions & 2 deletions rads/pdm-service/src/handlers/records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { requiredEnv } from "@srads/common/env";
import type { APIGatewayProxyHandlerV2 } from "aws-lambda";

const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const table = requiredEnv("PDM_TABLE");
const tablePrefix = requiredEnv("PDM_TABLE_PREFIX");
const ALGORITHM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

const PAGE_SIZE = 500;
const MAX_QUERY_ATTEMPTS = 8;
Expand Down Expand Up @@ -44,6 +45,9 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
if (!algorithmId) {
return jsonResponse(400, { error: "missing algorithmId" });
}
if (!ALGORITHM_ID.test(algorithmId)) {
return jsonResponse(400, { error: "invalid algorithmId" });
}
const runId = event.headers["x-run-id"] ?? "";

let exclusiveStartKey: Record<string, unknown> | undefined;
Expand All @@ -57,7 +61,7 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {

const result = await queryWithRetry(
new QueryCommand({
TableName: table,
TableName: `${tablePrefix}-${algorithmId}`,
KeyConditionExpression: "AlgorithmId = :a",
ExpressionAttributeValues: { ":a": algorithmId },
Limit: PAGE_SIZE,
Expand Down
2 changes: 1 addition & 1 deletion secure/pdm-service/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# pdm-service

Serverless Framework v4, TypeScript. The Personal Data Management Service: stores per-user personal-data records keyed by `AlgorithmId` in DynamoDB and serves them to an attested enclave.
Serverless Framework v4, TypeScript. The Personal Data Management Service: stores per-user personal-data records in one DynamoDB table per algorithm, named `<PDM_TABLE_PREFIX>-<algorithmId>`, and serves them to an attested enclave. Seeding creates the tables and encrypts each one at rest with a dedicated per-algorithm table key, separate from the PCR-bound enclave key.

## Endpoints

Expand Down
29 changes: 10 additions & 19 deletions secure/pdm-service/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,15 @@ provider:
statements:
- Effect: Allow
Action: dynamodb:Query
Resource: !GetAtt PersonalDataTable.Arn
Resource: !Sub "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/secure-rads-personal-data-*"
- Effect: Allow
Action: kms:Decrypt
Resource: !Sub "arn:aws:kms:${AWS::Region}:${AWS::AccountId}:key/*"
Condition:
StringEquals:
"kms:ViaService": !Sub "dynamodb.${AWS::Region}.amazonaws.com"
environment:
PDM_TABLE: !Ref PersonalDataTable
PDM_TABLE_PREFIX: secure-rads-personal-data
LOG_HOST: ${env:LOG_HOST_SECURE_RADS}
COST_HOST: ${env:COST_HOST_SECURE_RADS}
VERIFIER_JWKS_URL: ${env:VERIFIER_JWKS_URL}
Expand Down Expand Up @@ -56,21 +62,6 @@ resources:
- ""

Resources:
PersonalDataTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: AlgorithmId
AttributeType: S
- AttributeName: RecordId
AttributeType: S
KeySchema:
- AttributeName: AlgorithmId
KeyType: HASH
- AttributeName: RecordId
KeyType: RANGE

DataKeyTable:
Type: AWS::DynamoDB::Table
Properties:
Expand Down Expand Up @@ -171,8 +162,8 @@ resources:
PdmMtlsRegionalDomainName:
Condition: HasTruststoreVersion
Value: !GetAtt CountApiCustomDomain.RegionalDomainName
PersonalDataTableName:
Value: !Ref PersonalDataTable
PdmTablePrefix:
Value: secure-rads-personal-data
DataKeyTableName:
Value: !Ref DataKeyTable
ApiRegionalDomainName:
Expand Down
8 changes: 6 additions & 2 deletions secure/pdm-service/src/handlers/count.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { requiredEnv } from "@srads/common/env";
import type { APIGatewayProxyHandlerV2 } from "aws-lambda";

const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const table = requiredEnv("PDM_TABLE");
const tablePrefix = requiredEnv("PDM_TABLE_PREFIX");
const ALGORITHM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

const MAX_QUERY_ATTEMPTS = 8;

Expand Down Expand Up @@ -35,6 +36,9 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
if (!algorithmId) {
return jsonResponse(400, { error: "missing algorithmId" });
}
if (!ALGORITHM_ID.test(algorithmId)) {
return jsonResponse(400, { error: "invalid algorithmId" });
}

const size = event.queryStringParameters?.size;
let atLeast: number | undefined;
Expand All @@ -53,7 +57,7 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
do {
const page = await queryWithRetry(
new QueryCommand({
TableName: table,
TableName: `${tablePrefix}-${algorithmId}`,
KeyConditionExpression: "AlgorithmId = :a",
ExpressionAttributeValues: { ":a": algorithmId },
Select: "COUNT",
Expand Down
8 changes: 6 additions & 2 deletions secure/pdm-service/src/handlers/records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import type { APIGatewayProxyHandlerV2 } from "aws-lambda";
import { verifyAccessToken } from "../lib/jwt.js";

const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const table = requiredEnv("PDM_TABLE");
const tablePrefix = requiredEnv("PDM_TABLE_PREFIX");
const ALGORITHM_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

const PAGE_SIZE = 500;
const MAX_QUERY_ATTEMPTS = 8;
Expand Down Expand Up @@ -51,6 +52,9 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {
if (!validation) {
return jsonResponse(401, { error: "invalid token" });
}
if (!ALGORITHM_ID.test(validation.algorithmId)) {
return jsonResponse(401, { error: "invalid token" });
}
const runId = validation.runId;

let exclusiveStartKey: Record<string, unknown> | undefined;
Expand All @@ -64,7 +68,7 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {

const result = await queryWithRetry(
new QueryCommand({
TableName: table,
TableName: `${tablePrefix}-${validation.algorithmId}`,
KeyConditionExpression: "AlgorithmId = :a",
ExpressionAttributeValues: { ":a": validation.algorithmId },
Limit: PAGE_SIZE,
Expand Down
9 changes: 5 additions & 4 deletions seeding/README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
# Seeding

Seed-data platform for the PDM DynamoDB table. Standalone bun + TypeScript, not part of any service.
Seed-data platform for the PDM DynamoDB tables. Standalone bun + TypeScript, not part of any service.

`generate.ts` produces the JSON datasets in `datasets/` using `@faker-js/faker` with a fixed seed per dataset, so regeneration is byte-identical. `seed-secure-rads.ts` envelope-encrypts each record, batch-writes `{AlgorithmId, RecordId, Data}` into the PDM table, and puts the CMK-wrapped DEK in the data-key table.
`generate.ts` produces the JSON datasets in `datasets/` using `@faker-js/faker` with a fixed seed per dataset, so regeneration is byte-identical. Each dataset gets its own PDM table named `<PDM_TABLE_PREFIX>-<algorithmId>`; the seeder creates it if missing. `seed-secure-rads.ts` envelope-encrypts each record, batch-writes `{AlgorithmId, RecordId, Data}` into the algorithm's table, puts the CMK-wrapped DEK in the data-key table, and encrypts the table at rest with a dedicated per-algorithm KMS key (`PdmTableKeyArn` on the registry's algorithm table). `seed-rads.ts` writes plaintext tables.

## Usage

```sh
bun install
bun run generate
PDM_TABLE=<table> DATA_KEY_TABLE=<table> ALGORITHM_TABLE=<table> bun run seed-secure-rads
PDM_TABLE_PREFIX=<prefix> DATA_KEY_TABLE=<table> ALGORITHM_TABLE=<table> bun run seed-secure-rads
PDM_TABLE_PREFIX=<prefix> bun run seed-rads
```

Region comes from `AWS_REGION` (default `ap-southeast-2`).
Region comes from `AWS_REGION` (default `ap-southeast-2`). Creating tables and the secure per-algorithm table key needs `dynamodb:CreateTable`/`DescribeTable` and `kms:CreateKey`, plus `dynamodb:UpdateItem` on the algorithm table.

## Datasets

Expand Down
27 changes: 15 additions & 12 deletions seeding/lib/dynamo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,21 @@ import pMap from "p-map";
const MAX_RETRIES = 16;
const CONCURRENCY = Math.max(1, Number(process.env.SEED_WRITE_CONCURRENCY ?? 40));

export function documentClient(region: string): DynamoDBDocumentClient {
return DynamoDBDocumentClient.from(
new DynamoDBClient({
region,
maxAttempts: 3,
requestHandler: new NodeHttpHandler({
connectionTimeout: 5_000,
requestTimeout: 30_000,
throwOnRequestTimeout: true,
socketTimeout: 30_000,
}),
export function dynamoClient(region: string): DynamoDBClient {
return new DynamoDBClient({
region,
maxAttempts: 3,
requestHandler: new NodeHttpHandler({
connectionTimeout: 5_000,
requestTimeout: 30_000,
throwOnRequestTimeout: true,
socketTimeout: 30_000,
}),
);
});
}

export function documentClient(region: string): DynamoDBDocumentClient {
return DynamoDBDocumentClient.from(dynamoClient(region));
}

export async function writeAll(
Expand Down Expand Up @@ -48,6 +50,7 @@ function isRetryable(error: unknown): boolean {
error.name === "ThrottlingException" ||
error.name === "ProvisionedThroughputExceededException" ||
error.name === "RequestLimitExceeded" ||
error.name === "InternalServerError" ||
error.name === "TimeoutError" ||
/throughput|throttl|timeout/i.test(error.message)
);
Expand Down
50 changes: 50 additions & 0 deletions seeding/lib/tables.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {
CreateTableCommand,
type DynamoDBClient,
DescribeTableCommand,
waitUntilTableExists,
} from "@aws-sdk/client-dynamodb";

export function pdmTableName(prefix: string, algorithmId: string): string {
return `${prefix}-${algorithmId}`;
}

export async function ensurePdmTable(
client: DynamoDBClient,
table: string,
kmsKeyArn?: string,
): Promise<void> {
if (await tableExists(client, table)) return;

try {
await client.send(
new CreateTableCommand({
TableName: table,
BillingMode: "PAY_PER_REQUEST",
AttributeDefinitions: [
{ AttributeName: "AlgorithmId", AttributeType: "S" },
{ AttributeName: "RecordId", AttributeType: "S" },
],
KeySchema: [
{ AttributeName: "AlgorithmId", KeyType: "HASH" },
{ AttributeName: "RecordId", KeyType: "RANGE" },
],
SSESpecification: kmsKeyArn ? { Enabled: true, SSEType: "KMS", KMSMasterKeyId: kmsKeyArn } : undefined,
}),
);
} catch (error) {
if (!(error instanceof Error) || error.name !== "ResourceInUseException") throw error;
}

await waitUntilTableExists({ client, maxWaitTime: 120 }, { TableName: table });
}

export async function tableExists(client: DynamoDBClient, table: string): Promise<boolean> {
try {
await client.send(new DescribeTableCommand({ TableName: table }));
return true;
} catch (error) {
if (error instanceof Error && error.name === "ResourceNotFoundException") return false;
throw error;
}
}
Loading
Loading