diff --git a/Makefile b/Makefile
index ef4d21b..44d244c 100644
--- a/Makefile
+++ b/Makefile
@@ -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.
@@ -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=
ALGORITHM_ID=.
# Builds the arm64 image, ships it to the csav host, and registers it under ALGORITHM_ID.
@@ -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= ALGORITHM_ID=.
# Builds the arm64 image, gets a presigned S3 PUT URL from /upload, uploads the tarball straight to S3, then
@@ -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=.
# Fires /run (202 + runId), then polls GET /run/{runId} until the runner reports back.
diff --git a/benchmark/src/execute.py b/benchmark/src/execute.py
index 2dbb247..215aa18 100644
--- a/benchmark/src/execute.py
+++ b/benchmark/src/execute.py
@@ -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
diff --git a/rads/pdm-service/README.md b/rads/pdm-service/README.md
index 101956c..063e241 100644
--- a/rads/pdm-service/README.md
+++ b/rads/pdm-service/README.md
@@ -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 `-`, and serves them to the executor. The stack does not own the tables; seeding creates them.
## Endpoints
diff --git a/rads/pdm-service/serverless.yml b/rads/pdm-service/serverless.yml
index 35d60d7..f23cb7f 100644
--- a/rads/pdm-service/serverless.yml
+++ b/rads/pdm-service/serverless.yml
@@ -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}
@@ -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
diff --git a/rads/pdm-service/src/handlers/count.ts b/rads/pdm-service/src/handlers/count.ts
index 8c935c0..23205e1 100644
--- a/rads/pdm-service/src/handlers/count.ts
+++ b/rads/pdm-service/src/handlers/count.ts
@@ -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;
@@ -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;
@@ -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",
diff --git a/rads/pdm-service/src/handlers/records.ts b/rads/pdm-service/src/handlers/records.ts
index bfd1f4f..908ad25 100644
--- a/rads/pdm-service/src/handlers/records.ts
+++ b/rads/pdm-service/src/handlers/records.ts
@@ -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;
@@ -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 | undefined;
@@ -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,
diff --git a/secure/pdm-service/README.md b/secure/pdm-service/README.md
index 8f06e79..ee43b3a 100644
--- a/secure/pdm-service/README.md
+++ b/secure/pdm-service/README.md
@@ -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 `-`, 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
diff --git a/secure/pdm-service/serverless.yml b/secure/pdm-service/serverless.yml
index ff1ae35..e88a483 100644
--- a/secure/pdm-service/serverless.yml
+++ b/secure/pdm-service/serverless.yml
@@ -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}
@@ -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:
@@ -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:
diff --git a/secure/pdm-service/src/handlers/count.ts b/secure/pdm-service/src/handlers/count.ts
index 8c935c0..23205e1 100644
--- a/secure/pdm-service/src/handlers/count.ts
+++ b/secure/pdm-service/src/handlers/count.ts
@@ -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;
@@ -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;
@@ -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",
diff --git a/secure/pdm-service/src/handlers/records.ts b/secure/pdm-service/src/handlers/records.ts
index f92439b..35245e2 100644
--- a/secure/pdm-service/src/handlers/records.ts
+++ b/secure/pdm-service/src/handlers/records.ts
@@ -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;
@@ -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 | undefined;
@@ -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,
diff --git a/seeding/README.md b/seeding/README.md
index 313acde..48d0c1b 100644
--- a/seeding/README.md
+++ b/seeding/README.md
@@ -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 `-`; 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= DATA_KEY_TABLE= ALGORITHM_TABLE= bun run seed-secure-rads
+PDM_TABLE_PREFIX= DATA_KEY_TABLE= ALGORITHM_TABLE= bun run seed-secure-rads
+PDM_TABLE_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
diff --git a/seeding/lib/dynamo.ts b/seeding/lib/dynamo.ts
index d779c73..465177f 100644
--- a/seeding/lib/dynamo.ts
+++ b/seeding/lib/dynamo.ts
@@ -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(
@@ -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)
);
diff --git a/seeding/lib/tables.ts b/seeding/lib/tables.ts
new file mode 100644
index 0000000..ce0bad1
--- /dev/null
+++ b/seeding/lib/tables.ts
@@ -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 {
+ 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 {
+ try {
+ await client.send(new DescribeTableCommand({ TableName: table }));
+ return true;
+ } catch (error) {
+ if (error instanceof Error && error.name === "ResourceNotFoundException") return false;
+ throw error;
+ }
+}
diff --git a/seeding/seed-rads.ts b/seeding/seed-rads.ts
index 71d2b00..26e1455 100644
--- a/seeding/seed-rads.ts
+++ b/seeding/seed-rads.ts
@@ -1,8 +1,9 @@
import { readDatasetMeta, resolveSeedNames, streamDatasetRecords } from "./lib/datasets";
-import { documentClient, writeAll } from "./lib/dynamo";
+import { documentClient, dynamoClient, writeAll } from "./lib/dynamo";
import { requireEnv } from "./lib/env";
+import { ensurePdmTable, pdmTableName } from "./lib/tables";
-const table = requireEnv("RADS_PDM_TABLE");
+const tablePrefix = requireEnv("PDM_TABLE_PREFIX");
const BATCH_SIZE = 25;
const flushEvery = Math.max(25, Number(process.env.SEED_FLUSH_BATCHES ?? 400));
const pipelineDepth = Math.max(1, Number(process.env.SEED_PIPELINE ?? 2));
@@ -10,9 +11,12 @@ const skip = Math.max(0, Number(process.env.SEED_SKIP ?? 0));
const region = process.env.AWS_REGION ?? "ap-southeast-2";
const client = documentClient(region);
+const tables = dynamoClient(region);
for (const name of resolveSeedNames()) {
const meta = await readDatasetMeta(name);
+ const table = pdmTableName(tablePrefix, meta.algorithmId);
+ await ensurePdmTable(tables, table);
const progress = { written: skip, total: meta.expectedCount };
console.log(
`${meta.name} (${meta.algorithmId}): seeding${meta.expectedCount ? ` ${meta.expectedCount}` : ""} records` +
diff --git a/seeding/seed-secure-rads.ts b/seeding/seed-secure-rads.ts
index f4d16ee..e77cbe4 100644
--- a/seeding/seed-secure-rads.ts
+++ b/seeding/seed-secure-rads.ts
@@ -1,12 +1,13 @@
import { createCipheriv, randomBytes } from "node:crypto";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
-import { GenerateDataKeyCommand, KMSClient } from "@aws-sdk/client-kms";
-import { GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb";
+import { CreateKeyCommand, GenerateDataKeyCommand, KMSClient } from "@aws-sdk/client-kms";
+import { GetCommand, PutCommand, UpdateCommand } from "@aws-sdk/lib-dynamodb";
import { readDatasetMeta, resolveSeedNames, streamDatasetRecords } from "./lib/datasets";
-import { documentClient, writeAll } from "./lib/dynamo";
+import { documentClient, dynamoClient, writeAll } from "./lib/dynamo";
import { requireEnv } from "./lib/env";
+import { ensurePdmTable, pdmTableName, tableExists } from "./lib/tables";
-const table = requireEnv("PDM_TABLE");
+const tablePrefix = requireEnv("PDM_TABLE_PREFIX");
const algorithmTable = requireEnv("ALGORITHM_TABLE");
const dataKeyTable = requireEnv("DATA_KEY_TABLE");
const BATCH_SIZE = 25;
@@ -17,6 +18,7 @@ const forceNewKey = process.env.SEED_FORCE_NEW_KEY === "1";
const region = process.env.AWS_REGION ?? "ap-southeast-2";
const client = documentClient(region);
+const tables = dynamoClient(region);
const kms = new KMSClient({ region });
function dekCachePath(algorithmId: string): string {
@@ -53,8 +55,34 @@ async function loadOrCreateDek(algorithmId: string, kmsKeyArn: string): Promise<
return dek;
}
+async function loadOrCreateTableKey(algorithmId: string, existingKeyArn: string | undefined): Promise {
+ if (existingKeyArn) return existingKeyArn;
+
+ const created = await kms.send(
+ new CreateKeyCommand({
+ Description: `dynamodb table key for algorithm ${algorithmId}`,
+ KeyUsage: "ENCRYPT_DECRYPT",
+ KeySpec: "SYMMETRIC_DEFAULT",
+ }),
+ );
+ const keyArn = created.KeyMetadata?.Arn;
+ if (!keyArn) {
+ throw new Error(`CreateKey returned no key for algorithm ${algorithmId}`);
+ }
+ await client.send(
+ new UpdateCommand({
+ TableName: algorithmTable,
+ Key: { AlgorithmId: algorithmId },
+ UpdateExpression: "SET PdmTableKeyArn = :k",
+ ExpressionAttributeValues: { ":k": keyArn },
+ }),
+ );
+ return keyArn;
+}
+
for (const name of resolveSeedNames()) {
const meta = await readDatasetMeta(name);
+ const table = pdmTableName(tablePrefix, meta.algorithmId);
const progress = { written: skip, total: meta.expectedCount };
console.log(
`${meta.name} (${meta.algorithmId}): seeding${meta.expectedCount ? ` ${meta.expectedCount}` : ""} records` +
@@ -67,6 +95,11 @@ for (const name of resolveSeedNames()) {
throw new Error(`${meta.name}: no KMS key for algorithm ${meta.algorithmId}; build it first`);
}
+ if (!(await tableExists(tables, table))) {
+ const tableKeyArn = await loadOrCreateTableKey(meta.algorithmId, algo.Item?.PdmTableKeyArn as string | undefined);
+ await ensurePdmTable(tables, table, tableKeyArn);
+ }
+
const dekBuf = await loadOrCreateDek(meta.algorithmId, kmsKeyArn);
let seen = 0;
let batch: Record[] = [];