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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ __pycache__/

# OpenCode local state
.opencode/

secure/pdm-service/tls/
29 changes: 28 additions & 1 deletion docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ Set the certificate ARNs before deploying. Devbox already exports `REGION=ap-sou
export VERIFIER_CERT_ARN=<verifier-acm-certificate-arn>
export VERIFIER_ATTEST_CERT_ARN=<verifier-attest-acm-certificate-arn>
export PDM_CERT_ARN=<pdm-acm-certificate-arn>
export PDM_MTLS_CERT_ARN=<pdm-mtls-acm-certificate-arn>
export KMS_CERT_ARN=<kms-acm-certificate-arn>
export LOG_CERT_ARN=<log.sr-acm-certificate-arn>
export TELEMETRY_CERT_ARN=<telemetry.sr-acm-certificate-arn>
Expand Down Expand Up @@ -217,7 +218,9 @@ VERIFIER_JWKS_PUBKEY_SHA256="$VERIFIER_ATTEST_PIN" \
(cd secure/pdm-service && bun install && bunx serverless deploy \
--param="region=$REGION" \
--param="domainName=pdm.sr.secure-rads.org" \
--param="certificateArn=$PDM_CERT_ARN")
--param="certificateArn=$PDM_CERT_ARN" \
--param="mtlsDomainName=pdm-mtls.sr.secure-rads.org" \
--param="mtlsCertificateArn=$PDM_MTLS_CERT_ARN")
(cd secure/log-service && bun install && bunx serverless deploy \
--param="region=$REGION" \
--param="domainName=log.sr.secure-rads.org" --param="certificateArn=$LOG_CERT_ARN")
Expand All @@ -230,6 +233,30 @@ VERIFIER_JWKS_PUBKEY_SHA256="$VERIFIER_ATTEST_PIN" \
--param="certificateArn=$SECURE_COST_CERT_ARN")
```

Generate the execution-service client certificate, store it for the Lambda, then upload the truststore and redeploy PDM with its version:

```sh
make -C secure/pdm-service gen-client-cert
make -C secure/pdm-service store-client-cert
PDM_TRUSTSTORE_BUCKET=$(aws cloudformation describe-stacks --region "$REGION" \
--stack-name secure-rads-pdm-service-dev \
--query "Stacks[0].Outputs[?OutputKey=='PdmTruststoreBucketName'].OutputValue" --output text)
PDM_TRUSTSTORE_VERSION=$(aws s3api put-object --bucket "$PDM_TRUSTSTORE_BUCKET" \
--key truststore.pem --body secure/pdm-service/tls/client.crt \
--query VersionId --output text)
VERIFIER_JWKS_URL=https://verifier-attest.sr.secure-rads.org/.well-known/jwks.json \
VERIFIER_JWKS_PUBKEY_SHA256="$VERIFIER_ATTEST_PIN" \
(cd secure/pdm-service && bunx serverless deploy \
--param="region=$REGION" \
--param="domainName=pdm.sr.secure-rads.org" \
--param="certificateArn=$PDM_CERT_ARN" \
--param="mtlsDomainName=pdm-mtls.sr.secure-rads.org" \
--param="mtlsCertificateArn=$PDM_MTLS_CERT_ARN" \
--param="truststoreVersionId=$PDM_TRUSTSTORE_VERSION")
```

Create a DNS-only CNAME for `pdm-mtls.sr.secure-rads.org` from the `PdmMtlsRegionalDomainName` output.

For the baseline tree, deploy its log, telemetry, and cost services with the `*.r.secure-rads.org` certificates:

```sh
Expand Down
1 change: 1 addition & 0 deletions rads/pdm-service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Serverless Framework v4, TypeScript. The Personal Data Management Service for th
## Endpoints

- `GET /records` - `?algorithmId=` selects which records are returned. Paginated via `?cursor=` (base64url of DynamoDB's `LastEvaluatedKey`), 500 items per page. The response also carries a standalone `dataSubjectIds` list aligned with `records`: the rads host assembles the GDPR access trail from it after a successful DC app run, and `records` stays `{recordId, data}`, so the DC app never sees subject ids. PDM itself writes nothing to the log on retrieval.
- `GET /count` - public metadata endpoint used by execution-service's size check. Returns the seeded record count for `?algorithmId=` and stops early when `?size=` is supplied. Never returns personal data.
- `GET /subject/{dataSubjectId}` - the public data-subject access-request endpoint. No auth (the identifier is an opaque UUID) and rate-limited via a small reserved concurrency; it relays to log-service's `/subject-access/{dataSubjectId}` and returns which algorithms/runs touched that data subject. Never returns personal data.

The baseline PDM is fully trusted: there is no access token, verifier round-trip, or envelope encryption, and records are stored and returned as plaintext. Both routes are plain server-auth TLS and the HTTP API sets `cors: true` for the transparency portal.
Expand Down
7 changes: 7 additions & 0 deletions rads/pdm-service/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ functions:
- httpApi:
method: GET
path: /records
count:
handler: src/handlers/count.handler
timeout: 29
events:
- httpApi:
method: GET
path: /count
subject:
handler: src/handlers/subject.handler
reservedConcurrency: 5
Expand Down
73 changes: 73 additions & 0 deletions rads/pdm-service/src/handlers/count.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, QueryCommand } from "@aws-sdk/lib-dynamodb";
import { CostPhase, costEvent, recordRequest } from "@srads/common/cost";
import { requiredEnv } from "@srads/common/env";
import type { APIGatewayProxyHandlerV2 } from "aws-lambda";

const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const table = requiredEnv("PDM_TABLE");

const MAX_QUERY_ATTEMPTS = 8;

async function queryWithRetry(command: QueryCommand) {
for (let attempt = 1; ; attempt++) {
try {
return await ddb.send(command);
} catch (error) {
if (!(error instanceof Error) || error.name !== "ThrottlingException" || attempt >= MAX_QUERY_ATTEMPTS) {
throw error;
}
const backoffMs = 50 * 2 ** attempt + Math.random() * 100;
await new Promise((resolve) => setTimeout(resolve, backoffMs));
}
}
}

function jsonResponse(statusCode: number, body: unknown) {
return { statusCode, headers: { "content-type": "application/json" }, body: JSON.stringify(body) };
}

// Metadata-only count used by execution-service's size check. When `size` is set the count may stop early and
// be a lower bound; callers only need to know whether at least that many records exist.
export const handler: APIGatewayProxyHandlerV2 = async (event) => {
const startedAt = process.hrtime.bigint();
const algorithmId = event.queryStringParameters?.algorithmId;
if (!algorithmId) {
return jsonResponse(400, { error: "missing algorithmId" });
}

const size = event.queryStringParameters?.size;
let atLeast: number | undefined;
if (size !== undefined) {
const parsed = Number(size);
if (!Number.isInteger(parsed) || parsed <= 0) {
return jsonResponse(400, { error: "invalid size" });
}
atLeast = parsed;
}

const runId = event.headers["x-run-id"] ?? "";
let count = 0;
let readCapacityUnits = 0;
let exclusiveStartKey: Record<string, unknown> | undefined;
do {
const page = await queryWithRetry(
new QueryCommand({
TableName: table,
KeyConditionExpression: "AlgorithmId = :a",
ExpressionAttributeValues: { ":a": algorithmId },
Select: "COUNT",
ExclusiveStartKey: exclusiveStartKey,
ReturnConsumedCapacity: "TOTAL",
}),
);
count += page.Count ?? 0;
readCapacityUnits += page.ConsumedCapacity?.CapacityUnits ?? 0;
if (atLeast !== undefined && count >= atLeast) break;
exclusiveStartKey = page.LastEvaluatedKey as Record<string, unknown> | undefined;
} while (exclusiveStartKey);

await costEvent(algorithmId, runId, CostPhase.Execution, "dynamodb", "read-capacity", readCapacityUnits);
await recordRequest(algorithmId, runId, CostPhase.Execution, startedAt);
return jsonResponse(200, { algorithmId, count });
};
3 changes: 1 addition & 2 deletions rads/sce/execution-service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ run it, and returns immediately. Results come back asynchronously through the sh

`POST /run` is fire-and-forget: it assigns a `runId`, looks up `{Bucket, Key}` for the `AlgorithmId` in the
`rads-algorithms` DynamoDB table (PK `AlgorithmId`), and — when `size` is set — rejects the request if that
count exceeds the rows already seeded for the algorithm in PDM. It then launches a per-run EC2 executor, and returns
count exceeds the rows already seeded for the algorithm in PDM. The check calls PDM's public `/count` endpoint; this Lambda has no DynamoDB access to PDM. It then launches a per-run EC2 executor, and returns
`202 {runId, algorithmId, instanceId, status: "pending"}`. The executor installs AWS CLI + Docker, downloads
`rads-host-tools` from `s3://<images-bucket>/executor/rads-host-tools`, `aws s3 cp`s the image tar into place,
`docker load`s it, fetches PDM records up to the requested size into `/opt/rads/run/records.json`, then `docker run`s the
Expand Down Expand Up @@ -45,7 +45,6 @@ bunx serverless deploy \
--param="runResultsQueueUrl=<rads-run-results queue URL>" \
--param="runResultsQueueArn=<rads-run-results queue ARN>" \
--param="pdmUrl=https://pdm.example.org" \
--param="pdmTable=rads-personal-data" \
--param="vpcId=<VPC id>"
```

Expand Down
4 changes: 0 additions & 4 deletions rads/sce/execution-service/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ provider:
Resource:
- !Sub "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${param:algorithmTable}"
- !Sub "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${param:runResultsTable}"
- Effect: Allow
Action: dynamodb:Query
Resource: !Sub "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${param:pdmTable}"
- Effect: Allow
Action: ec2:RunInstances
Resource:
Expand All @@ -51,7 +48,6 @@ provider:
TELEMETRY_HOST: ${env:TELEMETRY_HOST_RADS}
COST_HOST: ${env:COST_HOST_RADS}
PDM_URL: ${param:pdmUrl}
PDM_TABLE: ${param:pdmTable}
# Pinned to match secure-rads ENCLAVE_AMI_ID so both trees boot the same AL2023 arm64 build.
EXECUTOR_AMI_ID: ${env:RADS_EXECUTOR_AMI_ID}
EXECUTOR_INSTANCE_TYPE: ${param:instanceType, 'c6g.large'}
Expand Down
23 changes: 4 additions & 19 deletions rads/sce/execution-service/src/handlers/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { CostPhase, costEvent, recordRequest } from "@srads/common/cost";
import { requiredEnv } from "@srads/common/env";
import { emitEvent } from "@srads/common/log";
import type { APIGatewayProxyHandlerV2 } from "aws-lambda";
import { countAlgorithmRecords, isThrottlingError } from "../lib/pdmCount.js";
import { fetchAlgorithmRecordCount } from "../lib/pdmCount.js";
import { userData } from "../lib/userdata.js";

const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
Expand All @@ -15,7 +15,6 @@ const algorithmTable = requiredEnv("ALGORITHM_TABLE");
const runResultsTable = requiredEnv("RUN_RESULTS_TABLE");
const runResultsQueueUrl = requiredEnv("RUN_RESULTS_QUEUE_URL");
const pdmUrl = requiredEnv("PDM_URL");
const pdmTable = requiredEnv("PDM_TABLE");
const logHost = requiredEnv("LOG_HOST");
const telemetryHost = requiredEnv("TELEMETRY_HOST");
const costHost = requiredEnv("COST_HOST");
Expand Down Expand Up @@ -104,30 +103,16 @@ export const create: APIGatewayProxyHandlerV2 = async (event) => {
}
} else {
try {
const { count: available, readCapacityUnits } = await countAlgorithmRecords(
ddb,
pdmTable,
request.algorithmId,
request.size,
);
await costEvent(
request.algorithmId,
runId,
CostPhase.Execution,
"dynamodb",
"read-capacity",
readCapacityUnits,
);
const available = await fetchAlgorithmRecordCount(pdmUrl, request.algorithmId, request.size, runId);
if (request.size > available) {
await recordRequest(request.algorithmId, runId, CostPhase.Execution, startedAt);
return jsonResponse(400, {
error: `size ${request.size} exceeds seeded dataset (${available} records)`,
});
}
} catch (error) {
// A concurrent sweep can throttle the fallback count; the executor caps at size anyway.
if (!isThrottlingError(error)) throw error;
console.warn("record count throttled; skipping size validation");
// The executor caps at size anyway, so a count outage should not block runs.
console.warn("record count failed; skipping size validation", error);
}
}
}
Expand Down
60 changes: 23 additions & 37 deletions rads/sce/execution-service/src/lib/pdmCount.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,27 @@
import { type DynamoDBDocumentClient, QueryCommand } from "@aws-sdk/lib-dynamodb";
const COUNT_TIMEOUT_MS = 5000;

export async function countAlgorithmRecords(
ddb: DynamoDBDocumentClient,
table: string,
// The count lives in PDM, not in this Lambda's DynamoDB permissions. `size` lets PDM stop early; the result
// may then be a lower bound, which is enough for the size check.
export async function fetchAlgorithmRecordCount(
pdmUrl: string,
algorithmId: string,
// Stop once we know at least this many rows exist (size checks only need a lower bound).
atLeast?: number,
): Promise<{ count: number; readCapacityUnits: number }> {
let total = 0;
let readCapacityUnits = 0;
let exclusiveStartKey: Record<string, unknown> | undefined;
do {
const page = await ddb.send(
new QueryCommand({
TableName: table,
KeyConditionExpression: "AlgorithmId = :a",
ExpressionAttributeValues: { ":a": algorithmId },
Select: "COUNT",
ReturnConsumedCapacity: "TOTAL",
ExclusiveStartKey: exclusiveStartKey,
}),
);
total += page.Count ?? 0;
readCapacityUnits += page.ConsumedCapacity?.CapacityUnits ?? 0;
if (atLeast !== undefined && total >= atLeast) return { count: total, readCapacityUnits };
exclusiveStartKey = page.LastEvaluatedKey as Record<string, unknown> | undefined;
} while (exclusiveStartKey);
return { count: total, readCapacityUnits };
}

const THROTTLING_ERRORS = new Set([
"ThrottlingException",
"ProvisionedThroughputExceededException",
"RequestLimitExceeded",
"TooManyRequestsException",
]);
atLeast: number,
runId: string,
): Promise<number> {
const url = new URL("/count", pdmUrl);
url.searchParams.set("algorithmId", algorithmId);
url.searchParams.set("size", String(atLeast));

export function isThrottlingError(error: unknown): boolean {
return error instanceof Error && THROTTLING_ERRORS.has(error.name);
const response = await fetch(url, {
headers: { "x-run-id": runId },
signal: AbortSignal.timeout(COUNT_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`PDM count returned ${response.status}`);
}
const body = (await response.json()) as { count?: unknown };
if (typeof body.count !== "number") {
throw new Error("PDM count response missing count");
}
return body.count;
}
22 changes: 22 additions & 0 deletions secure/pdm-service/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
include ../../mk/env.mk

REGION := $(AWS_REGION)
CERT_PARAM := /secure-rads/pdm-service/client-cert
KEY_PARAM := /secure-rads/pdm-service/client-key

.PHONY: gen-client-cert store-client-cert

# Self-signed client cert for the execution-service -> PDM count call. PoC only.
gen-client-cert:
mkdir -p tls
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -days 3650 -nodes \
-keyout tls/client.key -out tls/client.crt \
-subj "/CN=execution-service"

# Store the cert/key where execution-service reads them at cold start.
store-client-cert:
@test -f tls/client.crt -a -f tls/client.key || { echo "run make gen-client-cert first"; exit 1; }
aws ssm put-parameter --region $(REGION) --name $(CERT_PARAM) --type SecureString \
--value "file://tls/client.crt" --overwrite
aws ssm put-parameter --region $(REGION) --name $(KEY_PARAM) --type SecureString \
--value "file://tls/client.key" --overwrite
Loading