diff --git a/.env.example b/.env.example index 02a2dee9..f911aeb2 100644 --- a/.env.example +++ b/.env.example @@ -22,7 +22,7 @@ TRANSPARENCY_DOMAIN_RADS=transparency.r.secure-rads.org TRANSPARENCY_DOMAIN_SECURE_RADS=transparency.sr.secure-rads.org LOG_HOST_RADS=log.r.secure-rads.org LOG_HOST_SECURE_RADS=log.sr.secure-rads.org -# mTLS domain for internal producers (registry, execution-service, result-consumer). +# mTLS domain for internal producers (registry, execution-service). TELEMETRY_HOST_RADS=telemetry.r.secure-rads.org TELEMETRY_HOST_SECURE_RADS=telemetry.sr.secure-rads.org COST_HOST_RADS=cost.r.secure-rads.org diff --git a/CLAUDE.md b/CLAUDE.md index c8a540b0..abffbf3f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ The human user is the technical lead. The agent is a supporting engineer that he ## Project Context -This repo is a PoC of the Secure Computing Environment (SCE), running on AWS Nitro Enclaves. It covers the end-to-end workflow: a build phase (Registry Service, part of the CSAV, turns a Data Controller's OCI image into a single EIF, layering the SCE Unit and nsjail on top, stores the artifact in S3, records `AlgorithmId` -> S3 path in DynamoDB) and an execution phase (enclave provisioning, remote attestation against the Verifier Service, data fetch from the Personal Data Management Service and KMS, computation over decrypted records files inside the enclave (`RECORDS_PATH` / `RESULT_PATH`, same contract as rads), async result delivery through SQS and a result-consumer Lambda, polled via `GET /run/{runId}`). See the architecture section in `README.md` and the docs it links before making assumptions about scope or design. +This repo is a PoC of the Secure Computing Environment (SCE), running on AWS Nitro Enclaves. It covers the end-to-end workflow: a build phase (Registry Service, part of the CSAV, turns a Data Controller's OCI image into a single EIF, layering the SCE Unit and nsjail on top, stores the artifact in S3, records `AlgorithmId` -> S3 path in DynamoDB) and an execution phase (enclave provisioning, remote attestation against the Verifier Service, data fetch from the Personal Data Management Service and KMS, computation over decrypted records files inside the enclave (`RECORDS_PATH` / `RESULT_PATH`, same contract as rads), async result delivery by signed webhook to a per-run URL, with result-consumer as the store-backed receiver, verifiable via verifier-service). See the architecture section in `README.md` and the docs it links before making assumptions about scope or design. ## Operating Rules diff --git a/Makefile b/Makefile index 44d244c1..735773b0 100644 --- a/Makefile +++ b/Makefile @@ -93,6 +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) +RESULT_WEBHOOK_URL = $(shell aws cloudformation describe-stacks --stack-name secure-rads-result-consumer-dev --region $(REGION) \ + --query "Stacks[0].Outputs[?OutputKey=='ResultWebhookUrl'].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) \ @@ -219,14 +221,16 @@ secure-rads-build-all: $(MAKE) secure-rads-build APP=$$app ALGORITHM_ID=$$id || exit 1; \ done -# Execution phase (one run): make secure-rads-run ALGORITHM_ID=. -# Fires /run (202 + runId), then polls GET /run/{runId} until the enclave reports back. +# Execution phase (one run): make secure-rads-run ALGORITHM_ID= WEBHOOK_URL=. +# Fires /run with the required webhook. When the webhook is result-consumer, GET /run/{runId} is polled. secure-rads-run: @test -n "$(ALGORITHM_ID)" || { echo "ALGORITHM_ID is required"; exit 1; } + @test -n "$(WEBHOOK_URL)" || { echo "WEBHOOK_URL is required"; exit 1; } @api=$(EXECUTION_API_URL); \ runId=$$(curl -sS -X POST "$$api/run" -H 'Content-Type: application/json' \ - -d '{"algorithmId":"$(ALGORITHM_ID)"}' | python3 -c 'import sys,json; print(json.load(sys.stdin)["runId"])'); \ + -d '{"algorithmId":"$(ALGORITHM_ID)","webhookUrl":"$(WEBHOOK_URL)"}' | python3 -c 'import sys,json; print(json.load(sys.stdin)["runId"])'); \ echo "runId=$$runId"; \ + if [ "$(WEBHOOK_URL)" != "$(RESULT_WEBHOOK_URL)" ]; then echo "webhook run; result goes to $(WEBHOOK_URL)"; exit 0; fi; \ for i in $$(seq 1 132); do \ res=$$(curl -sS "$$api/run/$$runId?algorithmId=$(ALGORITHM_ID)"); \ status=$$(echo "$$res" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("status",""))'); \ @@ -241,14 +245,16 @@ secure-rads-run: # Fire and poll every sample app in turn (sequential - each spins up its own enclave). secure-rads-run-all: + @test -n "$(WEBHOOK_URL)" || { echo "WEBHOOK_URL is required"; exit 1; } @for pair in $(SAMPLE_APPS); do \ app=$${pair%%:*}; id=$${pair##*:}; \ - $(MAKE) secure-rads-run ALGORITHM_ID=$$id || exit 1; \ + $(MAKE) secure-rads-run ALGORITHM_ID=$$id WEBHOOK_URL="$(WEBHOOK_URL)" || exit 1; \ done # Start the existing hosts, then build, seed, and run the whole fleet. Build comes first because it # provisions the per-algorithm KMS keys used by seeding. secure-rads-all: + @test -n "$(WEBHOOK_URL)" || { echo "WEBHOOK_URL is required"; exit 1; } $(MAKE) secure-rads-ready $(MAKE) secure-rads-build-all $(MAKE) secure-rads-seed diff --git a/README.md b/README.md index a30860fc..1511d871 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Every rads AWS resource is prefixed `rads-`; every secure-rads resource is prefi **Build phase (CSAV).** A Data Controller uploads an OCI image and assigns it an `algorithmId`. registry-service unpacks the image (daemonless: skopeo + umoci), layers the SCE Unit and nsjail on top, and builds a single Nitro Enclave Image File (EIF). It registers the EIF's PCR measurements against that `algorithmId` with the Verifier Service (over mTLS) and stores the EIF in S3, recording `algorithmId -> S3 path` in DynamoDB. -**Execution phase (SCE).** A caller POSTs an `algorithmId` to the API Gateway and Lambda execution-service control plane, which launches a per-run Nitro Enclave parent EC2 instance. Inside, the SCE Unit seeds enclave entropy from the NSM, attests to the Verifier Service, and - once attestation passes - fetches that algorithm's records from the PDM Service, gets the data key unwrapped by the KMS Service, decrypts them, and writes `records.json` for the jailed Data Controller app (`RECORDS_PATH` / `RESULT_PATH`, same file contract as rads). Results come back asynchronously: `/run` returns a `runId` immediately, the enclave host publishes the result to SQS, a consumer Lambda persists it, and the caller polls `GET /run/{runId}`. +**Execution phase (SCE).** A caller POSTs an `algorithmId` to the API Gateway and Lambda execution-service control plane, which launches a per-run Nitro Enclave parent EC2 instance. Inside, the SCE Unit seeds enclave entropy from the NSM, attests to the Verifier Service, and - once attestation passes - fetches that algorithm's records from the PDM Service, gets the data key unwrapped by the KMS Service, decrypts them, and writes `records.json` for the jailed Data Controller app (`RECORDS_PATH` / `RESULT_PATH`, same file contract as rads). Results come back asynchronously: `/run` returns a `runId` immediately, the enclave signs the result with its attested key and POSTs it to a per-run webhook; when that webhook is result-consumer, it verifies the signature and `GET /run/{runId}` reads the stored result. Throughout both phases every component posts timestamped events to the telemetry-service, so a run's full timeline - build to execution - can be exported for benchmarking. The log-service records only the subject-access trail. Components also report selected, attributable AWS operations to the cost-service, keyed by the same `(AlgorithmId, runId)`, so their estimated costs can be summed per AWS service ([`docs/cost-service.md`](docs/cost-service.md)). Event-by-event plaintext flows: [`docs/e2e-rads.txt`](docs/e2e-rads.txt), [`docs/e2e-secure-rads.txt`](docs/e2e-secure-rads.txt). diff --git a/benchmark/src/lib/catalog.py b/benchmark/src/lib/catalog.py index 84936afc..8f780b19 100644 --- a/benchmark/src/lib/catalog.py +++ b/benchmark/src/lib/catalog.py @@ -22,6 +22,8 @@ class ApiGatewayService(BaseModel): has_url: bool = True # Env var holding the caller-facing hostname, for stacks whose URL is a custom domain. host_env: str | None = None + # Stack output that holds the URL, when it is not HttpApiUrl. + url_output: str = "HttpApiUrl" class Ec2HttpService(BaseModel): @@ -61,6 +63,10 @@ class Ec2HttpService(BaseModel): ), "pdm": ApiGatewayService(stack="secure-rads-pdm-service-dev"), "execution": ApiGatewayService(stack="secure-rads-execution-service-dev"), + "result_consumer": ApiGatewayService( + stack="secure-rads-result-consumer-dev", + url_output="ResultWebhookUrl", + ), "log": ApiGatewayService( stack="secure-rads-log-service-dev", host_env="LOG_HOST_SECURE_RADS", diff --git a/benchmark/src/lib/config.py b/benchmark/src/lib/config.py index 39227f3a..9b664fc3 100644 --- a/benchmark/src/lib/config.py +++ b/benchmark/src/lib/config.py @@ -49,18 +49,18 @@ def stack_outputs(stack: str) -> dict[str, str]: return outputs -def _api_gateway_url(outputs: dict[str, str], host_env: str | None) -> str: +def _api_gateway_url(outputs: dict[str, str], host_env: str | None, url_output: str) -> str: if host_env: host = os.environ.get(host_env) if not host: msg = f"{host_env} is required to resolve the service URL" raise RuntimeError(msg) return f"https://{host}" - if url := outputs.get("HttpApiUrl"): + if url := outputs.get(url_output): return url domain = outputs.get("ApiRegionalDomainName") if not domain: - msg = "stack outputs missing HttpApiUrl and ApiRegionalDomainName" + msg = f"stack outputs missing {url_output} and ApiRegionalDomainName" raise RuntimeError(msg) return f"https://{domain}" @@ -91,7 +91,7 @@ def _ec2_http_url(service: Ec2HttpService, outputs: dict[str, str]) -> str: def _service_url(service: ApiGatewayService | Ec2HttpService, outputs: dict[str, str]) -> str: if service.kind is ServiceKind.API_GATEWAY: - return _api_gateway_url(outputs, service.host_env) + return _api_gateway_url(outputs, service.host_env, service.url_output) if service.kind is ServiceKind.EC2_HTTP: return _ec2_http_url(service, outputs) msg = f"unknown service kind {service.kind!r}" diff --git a/benchmark/src/lib/trees/__init__.py b/benchmark/src/lib/trees/__init__.py index f0364325..174e6b3a 100644 --- a/benchmark/src/lib/trees/__init__.py +++ b/benchmark/src/lib/trees/__init__.py @@ -13,6 +13,6 @@ def harness_for(tree: Tree, endpoints: dict[str, str]) -> TreeHarness: if tree is Tree.RADS: return RadsHarness(endpoints["registry"], endpoints["execution"]) if tree is Tree.SECURE_RADS: - return SecureRadsHarness(endpoints["registry"], endpoints["execution"]) + return SecureRadsHarness(endpoints["registry"], endpoints["execution"], endpoints["result_consumer"]) msg = f"unknown tree {tree!r}" raise ValueError(msg) diff --git a/benchmark/src/lib/trees/secure_rads.py b/benchmark/src/lib/trees/secure_rads.py index 152bb98c..39d1f877 100644 --- a/benchmark/src/lib/trees/secure_rads.py +++ b/benchmark/src/lib/trees/secure_rads.py @@ -16,6 +16,34 @@ class SecureRadsHarness(TreeHarness): name: ClassVar[Tree] = Tree.SECURE_RADS + def __init__(self, registry_url: str, execution_url: str, result_webhook_url: str) -> None: + super().__init__(registry_url, execution_url) + self._webhook = result_webhook_url + + async def execute(self, client: httpx.AsyncClient, algorithm_id: str, size: int) -> tuple[str, str, str]: + status, body = await http.arequest( + client, + "POST", + f"{self._execution}/run", + json={"algorithmId": algorithm_id, "size": size, "webhookUrl": self._webhook}, + ) + http.require(status, http.HTTP_ACCEPTED, "/run", body) + + run_id = http.parse_json(body)["runId"] + deadline = asyncio.get_running_loop().time() + http.POLL_TIMEOUT_SECONDS + while asyncio.get_running_loop().time() < deadline: + status, result_body = await http.arequest( + client, "GET", f"{self._execution}/run/{run_id}?algorithmId={algorithm_id}" + ) + http.require(status, http.HTTP_OK, f"/run/{run_id}", result_body) + result = http.parse_json(result_body) + if result.get("status") != "pending": + return run_id, result.get("status", ""), result.get("output", "") or "" + await asyncio.sleep(http.POLL_INTERVAL_SECONDS) + + msg = f"timed out after {http.POLL_TIMEOUT_SECONDS:.0f}s waiting for runId={run_id}" + raise http.FlowError(msg) + async def upload(self, client: httpx.AsyncClient, algorithm_id: str) -> None: tar_path = await asyncio.to_thread(self.build_sample_tar, self.name) content = await asyncio.to_thread(tar_path.read_bytes) diff --git a/docs/cost-service.md b/docs/cost-service.md index 166b302e..a00a99cb 100644 --- a/docs/cost-service.md +++ b/docs/cost-service.md @@ -52,17 +52,19 @@ rads (`csav/registry-service`, Lambdas): - execution-service `POST /run`: `apigateway:request`, `lambda:invocation`, `lambda:compute`, `dynamodb:read-capacity` (algorithm lookup and record-count check; actual `ConsumedCapacity.CapacityUnits`). It also stamps the launch epoch into the host user-data. -- execution-service `GET /run/{runId}?algorithmId={algorithmId}` (each poll): `apigateway:request`, `lambda:invocation`, +- execution-service `GET /run/{runId}?algorithmId={algorithmId}` (both trees; secure-rads webhook runs stored by result-consumer): `apigateway:request`, `lambda:invocation`, `lambda:compute`, `dynamodb:read-capacity`. `algorithmId` is required so pending-run polls can be attributed. -- executor host (user-data, both trees): `s3:get` (artifact; rads also the host tools), `sqs:send` (result), +- executor host (user-data): `s3:get` (artifact; rads also the host tools), `sqs:send` (rads result only), `ec2:instance` (seconds from launch to the terminate call). - pdm-service `/records`: `apigateway:request`, `lambda:invocation`, `lambda:compute`, `dynamodb:read-capacity` (each records `Query` page). - kms-service `/decrypt` (secure-rads): `apigateway:request`, `lambda:invocation`, `lambda:compute`, `dynamodb:read-capacity` (algorithm and data-key `GetItem`s). -- result-consumer (`batchSize` 1, so each run's receive + invoke lands on that run): `sqs:receive` (message +- rads result-consumer (`batchSize` 1, so each run's receive + invoke lands on that run): `sqs:receive` (message bytes), `sqs:delete` (one request when the handler succeeds; Lambda performs the deletion), `dynamodb:write-capacity`, `lambda:invocation`, `lambda:compute`. +- secure-rads result-consumer (`POST /results`): `apigateway:request`, `lambda:invocation`, `lambda:compute`, + `dynamodb:write-capacity` for each verified webhook result. - verifier-service (secure-rads): `/challenge`, `/attest` and `/refresh` (the enclave's challenge, attestation and token refresh, keyed by the run) and `/algorithms` (build-time PCR registration, keyed by `algorithmId`): `dynamodb:read-capacity` and `dynamodb:write-capacity` where attributable, plus `apigateway:request`, `lambda:invocation`, `lambda:compute`. @@ -103,7 +105,7 @@ per-run against Cost Explorer. - log-service, telemetry-service, and cost-service self-cost (ingest API Gateway/Lambda/queue/DynamoDB). - Ongoing storage (S3 EIF/artifact objects, DynamoDB table storage), CloudWatch Logs ingestion/storage, CloudWatch alarms, the persistent CSAV host, and data transfer (internet egress, cross-AZ). -- SQS queue-cost of result delivery is metered as `sqs:send`, `sqs:receive`, and `sqs:delete`. Receive requests +- rads result delivery SQS cost is metered as `sqs:send`, `sqs:receive`, and `sqs:delete`. Receive requests that invoke the handler with an attributable result are counted, including redeliveries; idle polling, empty receives, and messages without parseable run identifiers cannot be attributed to a run. - Attributed DynamoDB events use each response's `ConsumedCapacity.CapacityUnits`; an invalid verifier refresh lookup diff --git a/docs/e2e-secure-rads.txt b/docs/e2e-secure-rads.txt index 75253731..e8759717 100644 --- a/docs/e2e-secure-rads.txt +++ b/docs/e2e-secure-rads.txt @@ -34,7 +34,7 @@ Input: 6 cost dynamodb:read-capacity // execution-service Query on the PDM table 7 RunInstances(Nitro parent, userdata ← ⟨a, runId, n, key, launchEpoch⟩) 8 emit executor-launched -9 cost apigateway:request + lambda // per control-plane request/poll (GET /run/{runId}?algorithmId=... too) +9 cost apigateway:request + lambda // per control-plane request 10 return runId @@ -50,23 +50,21 @@ Input: 4 cost s3:get // EIF pull 5 EIF ← GET-S3(key) 6 emit artifact-retrieved // direct, auth none -7 start vsock listeners // output :5000, runInfo :5001 +7 start vsock listeners // runInfo :5001, webhook :8006 8 configure vsock-proxy -9 RUN-ENCLAVE(EIF) +9 RUN-ENCLAVE(EIF) // on failure: emit enclave-launch-failed {runEnclave log tail}, go to 12 10 emit enclave-launched // direct, auth none -11 wait for enclave exit -12 publish result to SQS -13 cost sqs:send // message bytes -14 emit executor-finished // direct, auth none -15 cost ec2:instance // captured before the cost POST and terminate request -16 terminate instance +11 wait for enclave exit // absent from describe-enclaves for 5 consecutive polls +12 emit executor-finished // direct, auth none +13 cost ec2:instance // captured before the cost POST and terminate request +14 terminate instance SCE-UNIT(a) Input: a ← algorithm id 1 cfg ← LOAD-RUN-CONFIG() -2 ⟨runId, n⟩ ← READ-RUNINFO(:5001) +2 ⟨runId, n, webhookUrl⟩ ← READ-RUNINFO(:5001) 3 emit enclave-started // no token yet, auth none 4 SEED-ENTROPY from NSM // no AWS cost 5 emit unit-ready // no token yet, auth none @@ -87,9 +85,10 @@ Input: 20 wait for nsjail exit 21 output ← read /data/result.json 22 emit dc-app-completed // on success, else run-failed -23 STREAM output to parent // vsock :5000 -24 emit output-sent -25 // on failure: emit run-failed +23 SIGN result // signature key registered at attestation +24 SEND signed envelope to webhook // CA-verified TLS via vsock :8006; retry transport/429/5xx only +25 emit output-sent +26 // on failure: emit run-failed; before attestation no signed result is sent @@ -109,9 +108,8 @@ Input: SECURE-RADS-RESULT-CONSUMER(result) Input: - result ← processing result returned by the SCE-UNIT -1 SQS delivers result batch; invoke Lambda // receive is billed before the handler runs -2 persist result to DynamoDB -3 cost dynamodb:write-capacity; emit result-persisted -4 cost sqs:receive + lambda:invocation + lambda:compute // reported by handler after processing -5 cost sqs:delete // reported on success; Lambda deletes after return + result ← signed envelope POSTed by the SCE-UNIT webhook +1 key ← GET-VERIFIER-RUN-ATTESTATION(result.runId) // verifier GET /runs/{runId} +2 if not VERIFY-SIGNATURE(key, result) then reject +3 persist verified result to DynamoDB +4 cost dynamodb:write-capacity; emit result-persisted diff --git a/docs/getting-started.md b/docs/getting-started.md index db98dea0..75b8a08d 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -161,13 +161,7 @@ export SECURE_COST_CERT_ARN= export RADS_COST_CERT_ARN= ``` -Deploy the result consumer first because the execution-service stack needs its queue and table: - -```sh -(cd secure/result-consumer && bun install && bunx serverless deploy --param="region=$REGION") -``` - -Generate the mTLS client certificate, then deploy verifier-service once to create its truststore bucket: +Generate the mTLS client certificate, then deploy verifier-service once to create its truststore bucket and run-attestation table: ```sh make -C secure/csav/registry-service gen-client-cert @@ -179,6 +173,12 @@ make -C secure/csav/registry-service gen-client-cert --param="publicCertificateArn=$VERIFIER_ATTEST_CERT_ARN") ``` +Deploy the result consumer next so the execution-service stack can use its receiver URL and results table: + +```sh +(cd secure/result-consumer && bun install && bunx serverless deploy --param="region=$REGION") +``` + Upload the truststore, then deploy verifier-service again with its immutable S3 object version: ```sh diff --git a/docs/running.md b/docs/running.md index be551bbe..0050ef5d 100644 --- a/docs/running.md +++ b/docs/running.md @@ -37,13 +37,14 @@ and `AWS_DEFAULT_REGION` as `ap-southeast-2`, and uses the ignored local AWS fil devbox shell make up # start the CSAV EC2 host and wait for registry-service make status # show the CSAV, SCE, and rads stacks -make secure-rads # build, seed, and run all five samples +make secure-rads WEBHOOK_URL=... # build, seed, and run all five samples make down # stop the CSAV EC2 host when finished ``` `make secure-rads` is a persistent, repeatable fleet: it registers each sample under its fixed `algorithmId`, seeds its data, and runs it. Building happens before seeding because registration -creates the KMS key used to encrypt each dataset. +creates the KMS key used to encrypt each dataset. Results go to the required per-run webhook; use +result-consumer's `ResultWebhookUrl` to store them and poll `GET /run`, or a DC URL. Useful root targets: @@ -51,7 +52,7 @@ Useful root targets: make secure-rads-ready # start and verify the CSAV host make secure-rads-build-all # build and register all samples make secure-rads-seed # generate and seed all datasets -make secure-rads-run-all # run all samples +make secure-rads-run-all WEBHOOK_URL=... # run all samples make benchmark # Exp1/Exp2 size sweep (override REPS= TREES= …) make benchmark-report # export sweep CSV + figures make logs # tail the CSAV host and all Lambda logs @@ -65,7 +66,7 @@ Single app (APP is a secure/samples/ dir, ALGORITHM_ID its fixed id): ```sh make secure-rads-build APP=health-risk-python ALGORITHM_ID=662fa378-dc53-425d-9225-a187b11ea7dc -make secure-rads-run ALGORITHM_ID=662fa378-dc53-425d-9225-a187b11ea7dc +make secure-rads-run ALGORITHM_ID=662fa378-dc53-425d-9225-a187b11ea7dc WEBHOOK_URL=... ``` Export a run's timeline (build through execution) as CSV: diff --git a/packages/common/package.json b/packages/common/package.json index 556e362a..2844507c 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -19,6 +19,10 @@ "./jwt": { "types": "./src/jwt.ts", "import": "./src/jwt.ts" + }, + "./tls": { + "types": "./src/tls.ts", + "import": "./src/tls.ts" } }, "scripts": { diff --git a/scripts/lib/units.sh b/scripts/lib/units.sh index 396e2166..f4205013 100644 --- a/scripts/lib/units.sh +++ b/scripts/lib/units.sh @@ -30,7 +30,7 @@ units_rads=( declare -A DEPENDS=( [secure/storage]="" [secure/verifier-service]="" - [secure/result-consumer]="" + [secure/result-consumer]="secure/verifier-service" [secure/log-service]="secure/verifier-service" [secure/telemetry-service]="" [secure/cost-service]="" @@ -55,7 +55,7 @@ unit_secure_storage() { } unit_secure_result_consumer() { - need TELEMETRY_HOST_SECURE_RADS COST_HOST_SECURE_RADS + need TELEMETRY_HOST_SECURE_RADS COST_HOST_SECURE_RADS VERIFIER_ATTEST_HOST VERIFIER_PUBKEY_SHA256 sls secure/result-consumer --param="region=$region" } @@ -271,11 +271,11 @@ unit_rads_transparency_portal() { deploy_unit() { case "$1" in secure/storage) unit_secure_storage ;; - secure/result-consumer) unit_secure_result_consumer ;; secure/log-service) unit_secure_log_service ;; secure/telemetry-service) unit_secure_telemetry_service ;; secure/cost-service) unit_secure_cost_service ;; secure/verifier-service) unit_secure_verifier_service ;; + secure/result-consumer) unit_secure_result_consumer ;; secure/pdm-service) unit_secure_pdm_service ;; secure/kms-service) unit_secure_kms_service ;; secure/csav) unit_secure_csav ;; diff --git a/secure/result-consumer/README.md b/secure/result-consumer/README.md index 58cca5db..40427ed9 100644 --- a/secure/result-consumer/README.md +++ b/secure/result-consumer/README.md @@ -1,24 +1,25 @@ # result-consumer -Serverless Framework v4, TypeScript. The consumer half of the async run-result flow: an SQS-triggered Lambda that reads enclave run-result messages and writes them to the `RunResults` DynamoDB table (keyed by `RunId`), where execution-service's `GET /run/{runId}` reads them back. +Serverless Framework v4, TypeScript. HTTPS receiver for the enclave's signed run result. -## Resources +## Flow -- `RunResultsQueue` - standard SQS queue the enclave host produces JSON run results to. 60s visibility timeout, 14-day retention, redrive to `RunResultsDLQ` after 3 receives. -- `RunResultsDLQ` - dead-letter queue for messages that keep failing. -- `RunResultsTable` - PAY_PER_REQUEST DynamoDB table, PK `RunId`. +`POST /results` accepts the signed envelope `{ runId, algorithmId, payload, signature }`: -The `consume` Lambda parses each message `{ runId, instanceId?, algorithmId?, status?, output?, diag? }` and `PutItem`s it (idempotent on `RunId`). A message with no valid `runId` is skipped, not thrown, so it can't block the rest of the batch; it ages out to the DLQ. DynamoDB errors throw so the batch retries. +1. Fetch the run's attested public key from verifier-service `GET /runs/{runId}`, pinned to the verifier leaf SPKI. +2. Check the returned `runId` matches, then verify the signature and signed `algorithmId`. +3. `PutItem` the verified fields into `RunResultsTable`, which execution-service reads back at `GET /run/{runId}`. -When `algorithmId` is present it also writes `result-persisted` to telemetry-service over plain HTTPS. It does not emit host or terminal events; the enclave owns those. +Returns `200` on success, `400` for malformed input, `404` when the run has not attested, and `401` for an invalid signature. DynamoDB errors return `500` so the enclave's webhook retry can try again. -The stack Outputs (`RunResultsQueueUrl`, `RunResultsQueueArn`, `RunResultsTableName`, `RunResultsTableArn`) are consumed by execution-service. +## Resources -Bun is used as the local dev/bundle tool only (`bun install`) - the Lambda itself runs on the standard `nodejs24.x` runtime, no custom Bun runtime layer. +- `RunResultsTable` - PAY_PER_REQUEST DynamoDB table, PK `RunId`. +- `ResultWebhookUrl` - pass this as `webhookUrl` on `POST /run` when you want results stored for `GET /run/{runId}`. -## Deploy +Deploy verifier-service first so `GET /runs/{runId}` exists: ```sh bun install -bunx serverless deploy +bunx serverless deploy --param="region=$REGION" ``` diff --git a/secure/result-consumer/serverless.yml b/secure/result-consumer/serverless.yml index bdf7a09d..946e10b5 100644 --- a/secure/result-consumer/serverless.yml +++ b/secure/result-consumer/serverless.yml @@ -1,7 +1,5 @@ service: secure-rads-result-consumer -# Bundled as CJS, not ESM, same as pdm-service - esbuild's ESM output can't interop with plain -# top-level require() in some deps, and nothing here actually needs ESM at runtime. build: esbuild: format: cjs @@ -20,31 +18,21 @@ provider: Resource: !GetAtt RunResultsTable.Arn environment: RUN_RESULTS_TABLE: !Ref RunResultsTable + VERIFIER_ATTEST_HOST: ${env:VERIFIER_ATTEST_HOST} + VERIFIER_ATTEST_PUBKEY_SHA256: ${env:VERIFIER_PUBKEY_SHA256} TELEMETRY_HOST: ${env:TELEMETRY_HOST_SECURE_RADS} COST_HOST: ${env:COST_HOST_SECURE_RADS} functions: - consume: - handler: src/handlers/consume.handler + receive: + handler: src/handlers/receive.handler events: - - sqs: - arn: !GetAtt RunResultsQueue.Arn - batchSize: 1 + - httpApi: + method: POST + path: /results resources: Resources: - RunResultsQueue: - Type: AWS::SQS::Queue - Properties: - VisibilityTimeout: 60 - MessageRetentionPeriod: 1209600 - RedrivePolicy: - deadLetterTargetArn: !GetAtt RunResultsDLQ.Arn - maxReceiveCount: 3 - - RunResultsDLQ: - Type: AWS::SQS::Queue - RunResultsTable: Type: AWS::DynamoDB::Table Properties: @@ -57,10 +45,8 @@ resources: KeyType: HASH Outputs: - RunResultsQueueUrl: - Value: !Ref RunResultsQueue - RunResultsQueueArn: - Value: !GetAtt RunResultsQueue.Arn + ResultWebhookUrl: + Value: !Sub "https://${HttpApi}.execute-api.${AWS::Region}.amazonaws.com/results" RunResultsTableName: Value: !Ref RunResultsTable RunResultsTableArn: diff --git a/secure/result-consumer/src/handlers/consume.ts b/secure/result-consumer/src/handlers/consume.ts deleted file mode 100644 index 71d467eb..00000000 --- a/secure/result-consumer/src/handlers/consume.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; -import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb"; -import { CostPhase, costEvent, recordLambda } from "@srads/common/cost"; -import { requiredEnv } from "@srads/common/env"; -import { emitEvent } from "@srads/common/log"; -import type { SQSHandler, SQSRecord } from "aws-lambda"; - -const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})); -const table = requiredEnv("RUN_RESULTS_TABLE"); - -interface RunResultMessage { - runId: string; - instanceId?: string; - algorithmId?: string; - status?: string; - output?: string; - diag?: unknown; -} - -function messageId(record: SQSRecord): { algorithmId: string; runId: string } | undefined { - try { - const message = JSON.parse(record.body) as RunResultMessage; - if (typeof message.algorithmId === "string" && typeof message.runId === "string") { - return { algorithmId: message.algorithmId, runId: message.runId }; - } - } catch { - return undefined; - } - return undefined; -} - -// Consumes enclave run-result messages off RunResultsQueue and persists them to the RunResults table, -// where execution-service's GET /run/{runId} reads them back. The batch's records are handled concurrently. -async function persist(record: SQSRecord): Promise { - const message: RunResultMessage = JSON.parse(record.body); - // A malformed message shouldn't poison the batch and block good ones - skip it, let it age to the DLQ. - if (typeof message.runId !== "string") { - console.error("skipping message with missing/invalid runId", record.messageId); - return; - } - - const item = { - RunId: message.runId, - InstanceId: message.instanceId, - AlgorithmId: message.algorithmId, - Status: message.status, - Output: message.output ?? "", - Diag: message.diag ?? null, - ReceivedAt: new Date().toISOString(), - }; - - // PutItem is idempotent on RunId, so a batch retry on a DynamoDB error is safe. - const write = await ddb.send(new PutCommand({ TableName: table, Item: item, ReturnConsumedCapacity: "TOTAL" })); - - if (message.algorithmId) { - await costEvent( - message.algorithmId, - message.runId, - CostPhase.Execution, - "dynamodb", - "write-capacity", - write.ConsumedCapacity?.CapacityUnits ?? 0, - ); - await emitEvent(message.algorithmId, message.runId, "result-persisted", { status: message.status }); - } -} - -export const handler: SQSHandler = async (event) => { - const startedAt = process.hrtime.bigint(); - const first = event.Records.map(messageId).find((ids) => ids !== undefined); - try { - await Promise.all(event.Records.map(persist)); - } finally { - if (first) { - // batchSize is 1 so this message can be charged its SQS receive and Lambda costs. - const bytes = event.Records.reduce((total, record) => total + Buffer.byteLength(record.body), 0); - await costEvent(first.algorithmId, first.runId, CostPhase.Execution, "sqs", "receive", Math.max(1, bytes)); - await recordLambda(first.algorithmId, first.runId, CostPhase.Execution, startedAt); - } - } - - if (first) await costEvent(first.algorithmId, first.runId, CostPhase.Execution, "sqs", "delete", 1); -}; diff --git a/secure/result-consumer/src/handlers/receive.ts b/secure/result-consumer/src/handlers/receive.ts new file mode 100644 index 00000000..0afe6077 --- /dev/null +++ b/secure/result-consumer/src/handlers/receive.ts @@ -0,0 +1,63 @@ +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; +import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb"; +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 { fetchRunAttestation } from "../lib/attestation.js"; +import { type SignedResultMessage, verifySignedResult } from "../lib/verify.js"; + +const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})); +const table = requiredEnv("RUN_RESULTS_TABLE"); +const verifierAttestHost = requiredEnv("VERIFIER_ATTEST_HOST"); +const verifierAttestPin = requiredEnv("VERIFIER_ATTEST_PUBKEY_SHA256"); + +function jsonResponse(statusCode: number, body: unknown) { + return { statusCode, headers: { "content-type": "application/json" }, body: JSON.stringify(body) }; +} + +// A DynamoDB failure returns 500 so the enclave's webhook retry tries again. +export const handler: APIGatewayProxyHandlerV2 = async (event) => { + const startedAt = process.hrtime.bigint(); + let message: SignedResultMessage; + try { + message = JSON.parse(event.body ?? "") as SignedResultMessage; + } catch { + return jsonResponse(400, { error: "invalid JSON" }); + } + if (typeof message.runId !== "string") return jsonResponse(400, { error: "runId is required" }); + + const attested = await fetchRunAttestation(verifierAttestHost, verifierAttestPin, message.runId); + if (!attested || attested.runId !== message.runId) { + return jsonResponse(404, { error: "run has not attested" }); + } + + const result = verifySignedResult(message, attested.algorithmId, attested.publicKey); + if (!result) return jsonResponse(401, { error: "invalid signature" }); + + const write = await ddb.send( + new PutCommand({ + TableName: table, + Item: { + RunId: result.runId, + AlgorithmId: result.algorithmId, + Status: result.status, + Output: result.output, + ReceivedAt: new Date().toISOString(), + }, + ReturnConsumedCapacity: "TOTAL", + }), + ); + + await costEvent( + result.algorithmId, + result.runId, + CostPhase.Execution, + "dynamodb", + "write-capacity", + write.ConsumedCapacity?.CapacityUnits ?? 0, + ); + await recordRequest(result.algorithmId, result.runId, CostPhase.Execution, startedAt); + await emitEvent(result.algorithmId, result.runId, "result-persisted", { status: result.status }); + return jsonResponse(200, { runId: result.runId }); +}; diff --git a/secure/result-consumer/src/lib/attestation.ts b/secure/result-consumer/src/lib/attestation.ts new file mode 100644 index 00000000..8f26d51a --- /dev/null +++ b/secure/result-consumer/src/lib/attestation.ts @@ -0,0 +1,46 @@ +import https from "node:https"; +import { pinnedServerIdentity } from "@srads/common/tls"; + +export interface RunAttestation { + runId: string; + algorithmId: string; + publicKey: string; +} + +// Pinned to the verifier leaf SPKI, the same way downstream services pin the JWKS endpoint. +export function fetchRunAttestation( + host: string, + pinSha256: string, + runId: string, +): Promise { + const checkServerIdentity = pinnedServerIdentity(pinSha256, "verifier attestation server"); + const url = new URL(`https://${host}/runs/${encodeURIComponent(runId)}`); + + return new Promise((resolve, reject) => { + https + .get(url, { rejectUnauthorized: true, checkServerIdentity }, async (res) => { + try { + const chunks: Buffer[] = []; + for await (const chunk of res) chunks.push(chunk as Buffer); + if (res.statusCode === 404) { + resolve(undefined); + return; + } + if (res.statusCode !== 200) throw new Error(`run attestation fetch returned ${res.statusCode}`); + + const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record; + if ( + typeof parsed.runId !== "string" || + typeof parsed.algorithmId !== "string" || + typeof parsed.publicKey !== "string" + ) { + throw new Error("unexpected run attestation response shape"); + } + resolve({ runId: parsed.runId, algorithmId: parsed.algorithmId, publicKey: parsed.publicKey }); + } catch (err) { + reject(err); + } + }) + .on("error", reject); + }); +} diff --git a/secure/result-consumer/src/lib/verify.ts b/secure/result-consumer/src/lib/verify.ts new file mode 100644 index 00000000..dc9ed647 --- /dev/null +++ b/secure/result-consumer/src/lib/verify.ts @@ -0,0 +1,76 @@ +import { createPublicKey, verify as verifySignature } from "node:crypto"; + +const SIGNATURE_CONTEXT = "sce-result-v1\n"; + +export interface SignedResultMessage { + runId?: unknown; + algorithmId?: unknown; + payload?: unknown; + signature?: unknown; +} + +export interface VerifiedResult { + runId: string; + algorithmId: string; + status: string; + output: string; +} + +interface ResultPayload { + runId: string; + algorithmId: string; + status: string; + output: string; +} + +function isResultPayload(value: unknown): value is ResultPayload { + if (typeof value !== "object" || value === null) return false; + const payload = value as Record; + return ( + typeof payload.runId === "string" && + typeof payload.algorithmId === "string" && + typeof payload.status === "string" && + typeof payload.output === "string" + ); +} + +// The enclave signs the exact payload bytes it sent, so verification never depends on JSON re-serialization. +export function verifySignedResult( + message: SignedResultMessage, + attestedAlgorithmId: string, + publicKeyBase64: string, +): VerifiedResult | undefined { + if ( + typeof message.runId !== "string" || + typeof message.payload !== "string" || + typeof message.signature !== "string" + ) { + return undefined; + } + + let payload: unknown; + try { + payload = JSON.parse(Buffer.from(message.payload, "base64").toString("utf8")); + } catch { + return undefined; + } + if (!isResultPayload(payload)) return undefined; + if (payload.runId !== message.runId || payload.algorithmId !== attestedAlgorithmId) return undefined; + + try { + const payloadBytes = Buffer.from(message.payload, "base64"); + const key = createPublicKey({ key: Buffer.from(publicKeyBase64, "base64"), format: "der", type: "spki" }); + const signature = Buffer.from(message.signature, "base64"); + const signedBytes = Buffer.concat([Buffer.from(SIGNATURE_CONTEXT), payloadBytes]); + if (!verifySignature("sha256", signedBytes, { key, dsaEncoding: "der" }, signature)) return undefined; + } catch { + return undefined; + } + + return { + runId: payload.runId, + algorithmId: payload.algorithmId, + status: payload.status, + output: payload.output, + }; +} diff --git a/secure/sce-unit/README.md b/secure/sce-unit/README.md index a6245c85..308955be 100644 --- a/secure/sce-unit/README.md +++ b/secure/sce-unit/README.md @@ -5,9 +5,12 @@ challenge, attests to the Verifier Service with that challenge as the NSM nonce, fetches and decrypts PDM records, writes `records.json` under the DC rootfs `/data` (JSON shape `algorithmId` + `records`, same load path as rads), starts nsjail with -`RECORDS_PATH` / `RESULT_PATH` set, reads the DC app's `result.json`, then streams -that result to the parent instance over vsock (CID 3, port 5000) - the enclave's -only channel out. +`RECORDS_PATH` / `RESULT_PATH` set, reads the DC app's `result.json`, then signs +the result fields with the ephemeral key it registered during attestation. + +sce-unit POSTs the signed envelope to the run's DC webhook over CA-verified TLS +through a per-run vsock-proxy. The signature, not the transport, is what keeps a +compromised host from forging a result. PDM returns a standalone `dataSubjectIds` list aligned with the records. sce-unit keeps those ids in memory, writes `records.json` without them, and after a diff --git a/secure/sce-unit/attest.go b/secure/sce-unit/attest.go index 6e6235ef..b11b123a 100644 --- a/secure/sce-unit/attest.go +++ b/secure/sce-unit/attest.go @@ -6,6 +6,7 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" + "crypto/x509" "encoding/base64" "encoding/json" "fmt" @@ -19,38 +20,41 @@ import ( const attestRequestTimeout = 30 * time.Second -func attest(cfg runConfig, runID string) (tokenPair, error) { +func attest(cfg runConfig, runID string) (tokenPair, *ecdsa.PrivateKey, error) { priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) if err != nil { - return tokenPair{}, fmt.Errorf("generate ephemeral key: %w", err) + return tokenPair{}, nil, fmt.Errorf("generate ephemeral key: %w", err) + } + pubKey, err := x509.MarshalPKIXPublicKey(&priv.PublicKey) + if err != nil { + return tokenPair{}, nil, fmt.Errorf("marshal ephemeral public key: %w", err) } - pubKey := elliptic.Marshal(elliptic.P384(), priv.PublicKey.X, priv.PublicKey.Y) // The verifier issues the nonce, so the document it receives is bound to this specific /attest request. challenge, err := fetchChallenge(cfg, runID) if err != nil { - return tokenPair{}, fmt.Errorf("request challenge: %w", err) + return tokenPair{}, nil, fmt.Errorf("request challenge: %w", err) } nonce, err := base64.RawURLEncoding.DecodeString(challenge) if err != nil { - return tokenPair{}, fmt.Errorf("decode challenge: %w", err) + return tokenPair{}, nil, fmt.Errorf("decode challenge: %w", err) } sess, err := nsm.OpenDefaultSession() if err != nil { - return tokenPair{}, fmt.Errorf("open NSM session: %w", err) + return tokenPair{}, nil, fmt.Errorf("open NSM session: %w", err) } defer sess.Close() res, err := sess.Send(&request.Attestation{Nonce: nonce, PublicKey: pubKey}) if err != nil { - return tokenPair{}, fmt.Errorf("request attestation document: %w", err) + return tokenPair{}, nil, fmt.Errorf("request attestation document: %w", err) } if res.Error != "" { - return tokenPair{}, fmt.Errorf("NSM: %s", res.Error) + return tokenPair{}, nil, fmt.Errorf("NSM: %s", res.Error) } if res.Attestation == nil || res.Attestation.Document == nil { - return tokenPair{}, fmt.Errorf("NSM returned no attestation document") + return tokenPair{}, nil, fmt.Errorf("NSM returned no attestation document") } body, err := json.Marshal(struct { @@ -65,10 +69,14 @@ func attest(cfg runConfig, runID string) (tokenPair, error) { Challenge: challenge, }) if err != nil { - return tokenPair{}, err + return tokenPair{}, nil, err } - return postForTokens(cfg, "/attest", body) + tokens, err := postForTokens(cfg, "/attest", body) + if err != nil { + return tokenPair{}, nil, err + } + return tokens, priv, nil } // fetchChallenge gets a single-use nonce from verifier-service before the NSM attestation request, so the diff --git a/secure/sce-unit/main.go b/secure/sce-unit/main.go index 1dd91e10..daa1f6b1 100644 --- a/secure/sce-unit/main.go +++ b/secure/sce-unit/main.go @@ -11,7 +11,6 @@ import ( "time" sharedlog "github.com/Secure-RADS/st-dp/packages/go-common/log" - "golang.org/x/sys/unix" ) const ( @@ -25,7 +24,6 @@ const ( // The parent EC2 instance is always CID 3 on Nitro; the host's user data listens on this port. hostCID = 3 - hostOutputPort = 5000 vsockRetryWait = 500 * time.Millisecond vsockRetryLimit = 20 ) @@ -51,14 +49,14 @@ func main() { } info, err := readRunInfo() if err != nil { - failRun(timelineLog, cfg.AlgorithmId, "", err) + failRun(timelineLog, cfg.AlgorithmId, runInfo{}, err) } runID := info.RunID timelineLog.EmitEvent(cfg.AlgorithmId, &runID, sharedlog.EventEnclaveStarted, nil) // Must run before any crypto/rand use (attestation, TLS) - see entropy.go. if err := seedEntropy(); err != nil { - failRun(timelineLog, cfg.AlgorithmId, runID, fmt.Errorf("seed entropy: %w", err)) + failRun(timelineLog, cfg.AlgorithmId, info, fmt.Errorf("seed entropy: %w", err)) } log.Printf("sce-unit: seeded kernel entropy from NSM") timelineLog.EmitEvent(cfg.AlgorithmId, &runID, sharedlog.EventUnitReady, nil) @@ -66,7 +64,7 @@ func main() { // Attest, fetch, decrypt, and write records.json before nsjail starts - same file contract as rads. subjectIDs, err := prepareRecordsFile(cfg, timelineLog, runID, info.Size) if err != nil { - failRun(timelineLog, cfg.AlgorithmId, runID, err) + failRun(timelineLog, cfg.AlgorithmId, info, err) } var jailLog bytes.Buffer @@ -74,7 +72,7 @@ func main() { cmd.Stdout = io.MultiWriter(os.Stdout, &jailLog) cmd.Stderr = io.MultiWriter(os.Stderr, &jailLog) if err := cmd.Start(); err != nil { - failRun(timelineLog, cfg.AlgorithmId, runID, fmt.Errorf("start nsjail: %w", err)) + failRun(timelineLog, cfg.AlgorithmId, info, fmt.Errorf("start nsjail: %w", err)) } log.Printf("sce-unit: nsjail started (pid %d)", cmd.Process.Pid) @@ -82,6 +80,7 @@ func main() { log.Printf("sce-unit: nsjail exited: %v", waitErr) output, readErr := os.ReadFile(resultFileHost) + status := resultStatus(waitErr, readErr, len(output)) failed := waitErr != nil || readErr != nil || len(output) == 0 if failed { @@ -111,8 +110,13 @@ func main() { } else if output[len(output)-1] != '\n' { output = append(output, '\n') } - if err := sendOutput(output); err != nil { - log.Printf("sce-unit: send output to host failed: %v", err) + if err := sendResult(info, resultPayload{ + RunID: runID, + AlgorithmID: cfg.AlgorithmId, + Status: status, + Output: string(output), + }); err != nil { + log.Printf("sce-unit: send signed result to webhook failed: %v", err) timelineLog.EmitEvent(cfg.AlgorithmId, &runID, sharedlog.EventRunFailed, map[string]any{"error": err.Error()}) os.Exit(1) } @@ -122,16 +126,35 @@ func main() { } } -func failRun(timelineLog *sharedlog.Client, algorithmID, runID string, err error) { +func resultStatus(waitErr, readErr error, outputLen int) string { + if exitErr, ok := waitErr.(*exec.ExitError); ok { + return fmt.Sprintf("exit:%d", exitErr.ExitCode()) + } + if waitErr != nil || readErr != nil || outputLen == 0 { + return "exit:1" + } + return "exit:0" +} + +func failRun(timelineLog *sharedlog.Client, algorithmID string, info runInfo, err error) { log.Printf("sce-unit: %v", err) - if runID != "" { - timelineLog.EmitEvent(algorithmID, &runID, sharedlog.EventRunFailed, map[string]any{"error": err.Error()}) + if info.RunID != "" { + timelineLog.EmitEvent(algorithmID, &info.RunID, sharedlog.EventRunFailed, map[string]any{"error": err.Error()}) + } + if info.RunID == "" || info.WebhookURL == "" { + os.Exit(1) } failure, _ := json.Marshal(struct { Error string `json:"error"` }{Error: err.Error()}) - if err := sendOutput(append(failure, '\n')); err != nil { - log.Printf("sce-unit: send error to host failed: %v", err) + payload := resultPayload{ + RunID: info.RunID, + AlgorithmID: algorithmID, + Status: "exit:1", + Output: string(append(failure, '\n')), + } + if sendErr := sendResult(info, payload); sendErr != nil { + log.Printf("sce-unit: send signed failure to webhook failed: %v", sendErr) } os.Exit(1) } @@ -140,10 +163,11 @@ func failRun(timelineLog *sharedlog.Client, algorithmID, runID string, err error // records.json the DC app loads via RECORDS_PATH. It also returns the data subjects whose records were // handed to the DC app, for the post-completion subject-access trail. func prepareRecordsFile(cfg runConfig, timelineLog *sharedlog.Client, runID string, limit int) ([]string, error) { - tp, err := attest(cfg, runID) + tp, signer, err := attest(cfg, runID) if err != nil { return nil, fmt.Errorf("attestation failed: %w", err) } + setResultSigner(signer) log.Printf("sce-unit: attested successfully, access token expires %s", tp.AccessTokenExpiresAt.Format(time.RFC3339)) setTokens(tp) go refreshLoop(cfg, runID) @@ -196,34 +220,3 @@ func prepareRecordsFile(cfg runConfig, timelineLog *sharedlog.Client, runID stri timelineLog.EmitEvent(cfg.AlgorithmId, &runID, sharedlog.EventRecordsStoredLocally, nil) return subjectIDs, nil } - -// sendOutput streams the DC app's response to the parent instance over vsock - the enclave's only channel out. -func sendOutput(output []byte) error { - fd, err := unix.Socket(unix.AF_VSOCK, unix.SOCK_STREAM, 0) - if err != nil { - return err - } - defer unix.Close(fd) - - addr := &unix.SockaddrVM{CID: hostCID, Port: hostOutputPort} - for i := 0; ; i++ { - err = unix.Connect(fd, addr) - if err == nil { - break - } - if i >= vsockRetryLimit { - return err - } - time.Sleep(vsockRetryWait) - } - log.Printf("sce-unit: connected to host vsock %d:%d, sending %d bytes", hostCID, hostOutputPort, len(output)) - - for len(output) > 0 { - n, err := unix.Write(fd, output) - if err != nil { - return err - } - output = output[n:] - } - return nil -} diff --git a/secure/sce-unit/result.go b/secure/sce-unit/result.go new file mode 100644 index 00000000..ea9b59b2 --- /dev/null +++ b/secure/sce-unit/result.go @@ -0,0 +1,72 @@ +package main + +import ( + "crypto/ecdsa" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "sync" +) + +const resultSignatureContext = "sce-result-v1\n" + +type resultPayload struct { + RunID string `json:"runId"` + AlgorithmID string `json:"algorithmId"` + Status string `json:"status"` + Output string `json:"output"` +} + +type signedResult struct { + RunID string `json:"runId"` + AlgorithmID string `json:"algorithmId"` + Payload string `json:"payload"` + Signature string `json:"signature"` +} + +var resultSigner struct { + mu sync.RWMutex + key *ecdsa.PrivateKey +} + +func setResultSigner(key *ecdsa.PrivateKey) { + resultSigner.mu.Lock() + defer resultSigner.mu.Unlock() + resultSigner.key = key +} + +func getResultSigner() *ecdsa.PrivateKey { + resultSigner.mu.RLock() + defer resultSigner.mu.RUnlock() + return resultSigner.key +} + +func sendResult(info runInfo, p resultPayload) error { + key := getResultSigner() + if key == nil { + return fmt.Errorf("no result signing key: enclave has not attested") + } + + payload, err := json.Marshal(p) + if err != nil { + return fmt.Errorf("marshal result payload: %w", err) + } + digest := sha256.Sum256(append([]byte(resultSignatureContext), payload...)) + signature, err := ecdsa.SignASN1(rand.Reader, key, digest[:]) + if err != nil { + return fmt.Errorf("sign result payload: %w", err) + } + + envelope, err := json.Marshal(signedResult{ + RunID: p.RunID, + AlgorithmID: p.AlgorithmID, + Payload: base64.StdEncoding.EncodeToString(payload), + Signature: base64.StdEncoding.EncodeToString(signature), + }) + if err != nil { + return fmt.Errorf("marshal signed result: %w", err) + } + return sendWebhookResult(info, envelope) +} diff --git a/secure/sce-unit/runinfo.go b/secure/sce-unit/runinfo.go index 5013b7df..45942d94 100644 --- a/secure/sce-unit/runinfo.go +++ b/secure/sce-unit/runinfo.go @@ -14,11 +14,11 @@ import ( // no other way to learn the per-run id it was launched for (the EIF only carries the per-algorithm config). const hostRunIDPort = 5001 -// runInfo is the per-run data the host serves on hostRunIDPort: the run id and how many records to read -// (0 = the whole dataset). The enclave takes no user-data, so this is its only source for both. +// The enclave takes no user-data, so the host serves these on hostRunIDPort; Size 0 means the whole dataset. type runInfo struct { - RunID string `json:"runId"` - Size int `json:"size"` + RunID string `json:"runId"` + Size int `json:"size"` + WebhookURL string `json:"webhookUrl"` } func readRunInfo() (runInfo, error) { @@ -66,5 +66,8 @@ func readRunInfo() (runInfo, error) { if info.RunID == "" || info.Size < 0 { return runInfo{}, fmt.Errorf("invalid run-info: runId must be nonempty and size must be nonnegative") } + if info.WebhookURL == "" { + return runInfo{}, fmt.Errorf("invalid run-info: webhookUrl must be nonempty") + } return info, nil } diff --git a/secure/sce-unit/webhook.go b/secure/sce-unit/webhook.go new file mode 100644 index 00000000..685097ed --- /dev/null +++ b/secure/sce-unit/webhook.go @@ -0,0 +1,116 @@ +package main + +import ( + "bytes" + "context" + "crypto/tls" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "time" +) + +// Forwarded by the host to the webhook (see userdata.sh.tmpl); any public host, so CA-verified, not pinned. +const webhookProxyPort = 8006 + +const ( + webhookRequestTimeout = 30 * time.Second + webhookAttempts = 3 +) + +type webhookRejectedError struct { + status string + body []byte +} + +func (e *webhookRejectedError) Error() string { + return fmt.Sprintf("webhook rejected result with %s: %s", e.status, e.body) +} + +func retryableStatus(code int) bool { + return code == http.StatusTooManyRequests || code >= 500 +} + +func sendWebhookResult(info runInfo, envelope []byte) error { + target, err := url.Parse(info.WebhookURL) + if err != nil || target.Scheme != "https" || target.Hostname() == "" { + return fmt.Errorf("invalid webhook URL") + } + + body := bytes.NewReader(envelope) + for attempt := 1; ; attempt++ { + err := postWebhook(target, body) + if err == nil { + return nil + } + var permanent *webhookRejectedError + if attempt >= webhookAttempts || errors.As(err, &permanent) { + return err + } + time.Sleep(time.Duration(attempt) * time.Second) + body = bytes.NewReader(envelope) + } +} + +func postWebhook(target *url.URL, body *bytes.Reader) error { + ctx, cancel := context.WithTimeout(context.Background(), webhookRequestTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, target.String(), body) + if err != nil { + return fmt.Errorf("build webhook request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + + resp, err := vsockWebhookHTTPClient(target.Hostname()).Do(req) + if err != nil { + return fmt.Errorf("POST webhook: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) + if !retryableStatus(resp.StatusCode) { + return &webhookRejectedError{status: resp.Status, body: respBody} + } + return fmt.Errorf("webhook returned %s: %s", resp.Status, respBody) + } + return nil +} + +func vsockWebhookHTTPClient(host string) *http.Client { + return &http.Client{ + Timeout: webhookRequestTimeout, + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + Transport: &http.Transport{ + DisableKeepAlives: true, + DialTLSContext: func(ctx context.Context, _ string, _ string) (net.Conn, error) { + conn, err := dialVsock(ctx, hostCID, webhookProxyPort) + if err != nil { + return nil, err + } + if err := conn.SetDeadline(time.Now().Add(tlsHandshakeTimeout)); err != nil { + conn.Close() + return nil, err + } + tlsConn := tls.Client(conn, &tls.Config{ + ServerName: host, + MinVersion: tls.VersionTLS12, + }) + if err := tlsConn.Handshake(); err != nil { + conn.Close() + return nil, err + } + if err := conn.SetDeadline(time.Time{}); err != nil { + tlsConn.Close() + return nil, err + } + return tlsConn, nil + }, + }, + } +} diff --git a/secure/sce/Makefile b/secure/sce/Makefile index 3c747af3..6aa1d341 100644 --- a/secure/sce/Makefile +++ b/secure/sce/Makefile @@ -12,12 +12,8 @@ ALGORITHM_TABLE = $(shell aws cloudformation describe-stacks --stack-name secure --query "Stacks[0].Outputs[?OutputKey=='AlgorithmTableName'].OutputValue" --output text) PDM_MTLS_HOST = $(shell aws cloudformation describe-stacks --stack-name secure-rads-pdm-service-dev --region $(REGION) \ --query "Stacks[0].Outputs[?OutputKey=='PdmMtlsHost'].OutputValue" --output text) -RUN_RESULTS_QUEUE_ARN = $(shell aws cloudformation describe-stacks --stack-name secure-rads-result-consumer-dev --region $(REGION) \ - --query "Stacks[0].Outputs[?OutputKey=='RunResultsQueueArn'].OutputValue" --output text) RUN_RESULTS_TABLE = $(shell aws cloudformation describe-stacks --stack-name secure-rads-result-consumer-dev --region $(REGION) \ --query "Stacks[0].Outputs[?OutputKey=='RunResultsTableName'].OutputValue" --output text) -RUN_RESULTS_QUEUE_URL = $(shell aws cloudformation describe-stacks --stack-name secure-rads-result-consumer-dev --region $(REGION) \ - --query "Stacks[0].Outputs[?OutputKey=='RunResultsQueueUrl'].OutputValue" --output text) API_URL = $(shell aws cloudformation describe-stacks --stack-name $(STACK_NAME) --region $(REGION) \ --query "Stacks[0].Outputs[?OutputKey=='ExecutionApiUrl'].OutputValue" --output text) @@ -30,8 +26,6 @@ deploy: env-check --param="artifactBucket=$(ARTIFACT_BUCKET)" \ --param="algorithmTable=$(ALGORITHM_TABLE)" \ --param="pdmMtlsHost=$(PDM_MTLS_HOST)" \ - --param="runResultsQueueArn=$(RUN_RESULTS_QUEUE_ARN)" \ - --param="runResultsQueueUrl=$(RUN_RESULTS_QUEUE_URL)" \ --param="runResultsTable=$(RUN_RESULTS_TABLE)" \ --param="enclaveInstanceType=c6g.large" diff --git a/secure/sce/execution-service/README.md b/secure/sce/execution-service/README.md index 8d323283..4118f258 100644 --- a/secure/sce/execution-service/README.md +++ b/secure/sce/execution-service/README.md @@ -2,16 +2,26 @@ Part of the SCE. API Gateway invokes the TypeScript Lambda control plane. Given an `AlgorithmId`, it looks up the EIF in S3 (via registry-service's `AlgorithmTable`), starts a Nitro-Enclave-capable EC2 instance, and returns immediately. The per-run EC2 instance remains necessary as the Nitro Enclave parent; the service itself has no persistent EC2 host. -`POST /run` is fire-and-forget: it assigns a `runId`, looks up the EIF, and — when `size` is set — rejects the request if that count exceeds the rows already seeded for the algorithm in PDM. The check calls PDM's `/count` endpoint over mTLS with a client certificate fetched from SSM; this Lambda has no DynamoDB access to PDM. It then launches the enclave and returns `202 {runId, algorithmId, instanceId, status: "pending"}` immediately. The enclave host sends its result (exit status plus what the DC app returned over vsock) to the run-results SQS queue when it finishes; a consumer Lambda (result-consumer) writes it to the RunResults table. +`POST /run` is fire-and-forget: it assigns a `runId`, looks up the EIF, and — when `size` is set — rejects the request if that count exceeds the rows already seeded for the algorithm in PDM. The check calls PDM's `/count` endpoint over mTLS with a client certificate fetched from SSM; this Lambda has no DynamoDB access to PDM. It then launches the enclave and returns `202 {runId, algorithmId, instanceId, status: "pending"}` immediately. -`GET /run/{runId}?algorithmId={algorithmId}` polls for the result: `{runId, status: "pending"}` until it lands, then the stored result once the consumer has written it. `algorithmId` is required so every poll can be attributed to its run. +The request requires a `webhookUrl`: -The control plane logs `run-requested` and `executor-launched` (or `launch-failed`). The parent posts `executor-ready`, `artifact-retrieved`, `enclave-launched`, and `executor-finished` directly to telemetry-service with `origin: host`. The host holds no credential; telemetry ingest is unauthenticated. The enclave emits `run-failed` before it exits. result-consumer only emits `result-persisted`. SCE-unit and result-consumer emit the remaining events in [the execution flow](../../../docs/e2e-secure-rads.txt). +```json +{ "algorithmId": "...", "size": 1000, "webhookUrl": "https://dc.example/results" } +``` + +The URL must be `https` with a plain DNS hostname (no IP literals or credentials), because the hostname is written into the host's vsock-proxy config. The control plane makes a 5s `HEAD` reachability check with redirects disabled; any HTTP response counts, only DNS/TLS/connection failures reject the request. That probe is an accepted SSRF surface for now: the Lambda can reach VPC-internal hosts, so a production deployment should move delivery behind a public-egress-only proxy. The enclave signs the result (run id, algorithm id, status, and output) with its attested ephemeral key and POSTs the signed envelope to that webhook over CA-verified TLS. It retries transport errors, `429`, and `5xx` up to three times; any other non-2xx is final. + +If the webhook is result-consumer's `ResultWebhookUrl`, result-consumer verifies the signature and writes the RunResults table, so `GET /run/{runId}` returns the result. For any other webhook, the DC verifies the envelope with verifier-service `GET /runs/{runId}` and `GET /run/{runId}` stays `pending`. + +`GET /run/{runId}?algorithmId={algorithmId}` polls for the result: `{runId, status: "pending"}` until it lands, then the stored result for runs delivered to result-consumer. `algorithmId` is required so every poll can be attributed to its run. + +The control plane logs `run-requested` and `executor-launched` (or `launch-failed`). The parent posts `executor-ready`, `artifact-retrieved`, `enclave-launched` (or `enclave-launch-failed` with the run-enclave log tail in `detail`), and `executor-finished` directly to telemetry-service with `origin: host`. The host holds no credential; telemetry ingest is unauthenticated. The enclave emits `run-failed` before it exits. A run that fails before attestation or never launches has no signed result, so `GET /run/{runId}` stays `pending`; the cause is in the telemetry timeline. result-consumer emits `result-persisted` for internally delivered runs. SCE-unit and result-consumer emit the remaining events in [the execution flow](../../../docs/e2e-secure-rads.txt). See [../README.md](../README.md) for the full SCE context. ## Deployment -`make -C sce deploy` deploys the Lambda stack. It requires result-consumer, registry-service storage, and kms-service to exist first. +`make -C sce deploy` deploys the Lambda stack. It requires registry-service storage, verifier-service, result-consumer, and kms-service to exist first. -The enclave host pulls the EIF and publishes the result; it has no algorithm-key KMS permission. Data-key decryption runs in kms-service, so the per-algorithm key policy names the kms-service role rather than this per-deployment host role. `KMS_HOST` is passed as `KMS_SERVICE_HOST` and baked into the host user data, which proxies the enclave's `/decrypt` call. +The enclave host pulls the EIF but does not publish the result; it has no algorithm-key KMS permission. Data-key decryption runs in kms-service, so the per-algorithm key policy names the kms-service role rather than this per-deployment host role. `KMS_HOST` is passed as `KMS_SERVICE_HOST` and baked into the host user data, which proxies the enclave's `/decrypt` call. diff --git a/secure/sce/execution-service/serverless.yml b/secure/sce/execution-service/serverless.yml index e6224491..1dd64d23 100644 --- a/secure/sce/execution-service/serverless.yml +++ b/secure/sce/execution-service/serverless.yml @@ -54,7 +54,6 @@ provider: environment: ALGORITHM_TABLE: ${param:algorithmTable} RUN_RESULTS_TABLE: ${param:runResultsTable} - RUN_RESULTS_QUEUE_URL: ${param:runResultsQueueUrl} # Pinned to match rads EXECUTOR_AMI_ID so both trees boot the same AL2023 arm64 build. ENCLAVE_AMI_ID: ${env:SCE_ENCLAVE_AMI_ID} ENCLAVE_INSTANCE_TYPE: ${param:enclaveInstanceType, 'c6g.large'} @@ -127,14 +126,6 @@ resources: Condition: StringEquals: "ec2:ResourceTag/ManagedBy": secure-rads-execution-service - - PolicyName: SendRunResult - PolicyDocument: - Version: "2012-10-17" - Statement: - - Effect: Allow - Action: sqs:SendMessage - Resource: ${param:runResultsQueueArn} - EnclaveHostInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: diff --git a/secure/sce/execution-service/src/handlers/run.ts b/secure/sce/execution-service/src/handlers/run.ts index f9808746..a24b531b 100644 --- a/secure/sce/execution-service/src/handlers/run.ts +++ b/secure/sce/execution-service/src/handlers/run.ts @@ -13,7 +13,6 @@ const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})); const ec2 = new EC2Client({}); const algorithmTable = requiredEnv("ALGORITHM_TABLE"); const runResultsTable = requiredEnv("RUN_RESULTS_TABLE"); -const runResultsQueueUrl = requiredEnv("RUN_RESULTS_QUEUE_URL"); const enclaveAmiId = requiredEnv("ENCLAVE_AMI_ID"); const enclaveInstanceType = requiredEnv("ENCLAVE_INSTANCE_TYPE") as RunInstancesCommandInput["InstanceType"]; const enclaveAz = requiredEnv("ENCLAVE_AZ"); @@ -31,24 +30,54 @@ const region = requiredEnv("AWS_REGION"); interface RunRequest { algorithmId: string; size?: number; -} - -interface AlgorithmRecord { - S3Bucket?: string; - S3Key?: string; - RecordCount?: number; + webhookUrl: string; } interface RunResult { AlgorithmId?: string; - Diag?: unknown; - InstanceId?: string; Output?: string; ReceivedAt?: string; RunId?: string; Status?: string; } +const WEBHOOK_PROBE_TIMEOUT_MS = 5000; +// The hostname is spliced into host shell and vsock-proxy config, so only plain DNS names are accepted. +const DNS_HOSTNAME = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/; + +// Known SSRF surface accepted for now; see the webhook note in the README. +async function webhookReachable(url: string): Promise { + try { + await fetch(url, { + method: "HEAD", + redirect: "manual", + signal: AbortSignal.timeout(WEBHOOK_PROBE_TIMEOUT_MS), + }); + return true; + } catch { + return false; + } +} + +function parseWebhookUrl(value: unknown): string | undefined { + if (typeof value !== "string" || value.length === 0) return undefined; + try { + const url = new URL(value); + if (url.protocol !== "https:" || url.username || url.password || !DNS_HOSTNAME.test(url.hostname)) { + return undefined; + } + return url.toString(); + } catch { + return undefined; + } +} + +interface AlgorithmRecord { + S3Bucket?: string; + S3Key?: string; + RecordCount?: number; +} + function jsonResponse(statusCode: number, body: unknown) { return { statusCode, headers: { "content-type": "application/json" }, body: JSON.stringify(body) }; } @@ -57,12 +86,14 @@ function parseRunRequest(body: string | undefined): RunRequest | undefined { try { const parsed: unknown = JSON.parse(body ?? ""); if (typeof parsed !== "object" || parsed === null) return undefined; - const { algorithmId, size } = parsed as Record; + const { algorithmId, size, webhookUrl } = parsed as Record; if (typeof algorithmId !== "string" || algorithmId.length === 0) return undefined; if (size !== undefined && (typeof size !== "number" || !Number.isInteger(size) || size <= 0)) { return undefined; } - return size === undefined ? { algorithmId } : { algorithmId, size }; + const webhook = parseWebhookUrl(webhookUrl); + if (webhook === undefined) return undefined; + return { algorithmId, webhookUrl: webhook, ...(size === undefined ? {} : { size }) }; } catch { return undefined; } @@ -120,6 +151,11 @@ export const create: APIGatewayProxyHandlerV2 = async (event) => { } } + if (!(await webhookReachable(request.webhookUrl))) { + await recordRequest(request.algorithmId, runId, CostPhase.Execution, startedAt); + return jsonResponse(400, { error: "webhook unreachable" }); + } + await emitEvent(request.algorithmId, runId, "run-requested"); const launched = await ec2.send( new RunInstancesCommand({ @@ -141,12 +177,12 @@ export const create: APIGatewayProxyHandlerV2 = async (event) => { telemetryHost, pdmHost, region, - queueUrl: runResultsQueueUrl, runId, s3Bucket: record.S3Bucket, s3Key: record.S3Key, size: request.size, verifierHost, + webhookUrl: request.webhookUrl, }), ).toString("base64"), TagSpecifications: [ @@ -199,11 +235,9 @@ export const result: APIGatewayProxyHandlerV2 = async (event) => { if (!item) return jsonResponse(200, { runId, status: "pending" }); return jsonResponse(200, { runId: item.RunId, - instanceId: item.InstanceId, algorithmId: item.AlgorithmId, status: item.Status, output: item.Output, - diag: item.Diag, receivedAt: item.ReceivedAt, }); } catch (error) { diff --git a/secure/sce/execution-service/src/lib/userdata.ts b/secure/sce/execution-service/src/lib/userdata.ts index 6352602d..3ee05378 100644 --- a/secure/sce/execution-service/src/lib/userdata.ts +++ b/secure/sce/execution-service/src/lib/userdata.ts @@ -16,11 +16,14 @@ export interface UserDataValues { s3Bucket: string; s3Key: string; verifierHost: string; - queueUrl: string; size?: number; + webhookUrl: string; } export function userData(values: UserDataValues): string { + const webhook = new URL(values.webhookUrl); + const webhookPort = webhook.port || "443"; + const replacements: Record = { AlgorithmId: values.algorithmId, CostHost: values.costHost, @@ -31,13 +34,15 @@ export function userData(values: UserDataValues): string { TelemetryHost: values.telemetryHost, MemoryMiB: "2048", PdmHost: values.pdmHost, - QueueUrl: values.queueUrl, Region: values.region, RunId: values.runId, S3Bucket: values.s3Bucket, S3Key: values.s3Key, Size: (values.size ?? 0).toString(), VerifierHost: values.verifierHost, + WebhookAllowlist: ` - {address: "${webhook.hostname}", port: ${webhookPort}}`, + WebhookProxy: `vsock-proxy 8006 "${webhook.hostname}" ${webhookPort} --config /etc/nitro_enclaves/vsock-proxy.yaml &`, + WebhookURL: JSON.stringify(values.webhookUrl), }; return Object.entries(replacements).reduce( diff --git a/secure/sce/execution-service/userdata.sh.tmpl b/secure/sce/execution-service/userdata.sh.tmpl index c56b3a9f..9b31ddba 100644 --- a/secure/sce/execution-service/userdata.sh.tmpl +++ b/secure/sce/execution-service/userdata.sh.tmpl @@ -6,7 +6,7 @@ exec > >(tee /var/log/execution-service-run.log) 2>&1 # auth=none, origin=host. The enclave owns the post-attestation and terminal events. emit_event() { curl -sS --max-time 5 -X POST "https://{{.TelemetryHost}}/events" -H 'content-type: application/json' \ - -d "{\"algorithmId\":\"{{.AlgorithmId}}\",\"runId\":\"{{.RunId}}\",\"event\":\"$1\",\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%S.%NZ)\",\"origin\":\"host\"}" >/dev/null || true + -d "{\"algorithmId\":\"{{.AlgorithmId}}\",\"runId\":\"{{.RunId}}\",\"event\":\"$1\",\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%S.%NZ)\",\"origin\":\"host\",\"detail\":${2:-null}}" >/dev/null || true } # Cost metering reports selected AWS operations, keyed by (AlgorithmId, runId). Best-effort. @@ -16,31 +16,14 @@ emit_cost() { -d "{\"algorithmId\":\"{{.AlgorithmId}}\",\"runId\":\"{{.RunId}}\",\"eventId\":\"$(cat /proc/sys/kernel/random/uuid)\",\"phase\":\"execution\",\"service\":\"$1\",\"operation\":\"$2\",\"quantity\":$3,\"timestamp\":\"$(date -u +%Y-%m-%dT%H:%M:%S.%NZ)\"}" >/dev/null || true } -# Always self-terminate on exit and send the run result to SQS, where a consumer Lambda persists it for the -# caller to poll (GET /run/). The result carries the runId execution-service assigned at launch. +# Always self-terminate on exit; sce-unit delivers the signed result itself. finish() { - STATUS=$? set +e TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") INSTANCE_ID=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id) REGION=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/region) - python3 - "$STATUS" "$INSTANCE_ID" > /tmp/result.json <<'PYEOF' -import json, sys -def read(path): - try: - return open(path, "rb").read().decode("utf-8", "replace") - except FileNotFoundError: - return "" -out = read("/tmp/output.txt") -# When the DC app produced no output, surface the enclave launch log so an empty result is diagnosable -# instead of silent (the enclave console is otherwise lost when the host terminates). -diag = {"runEnclave": read("/tmp/run-enclave.log")} if not out else {} -print(json.dumps({"runId": "{{.RunId}}", "algorithmId": "{{.AlgorithmId}}", "instanceId": sys.argv[2], "status": "exit:" + sys.argv[1], "output": out, "diag": diag})) -PYEOF - aws sqs send-message --queue-url "{{.QueueUrl}}" --message-body file:///tmp/result.json --region "$REGION" || true emit_event executor-finished - emit_cost sqs send "$(wc -c < /tmp/result.json)" - # The runtime estimate is captured before this cost POST and the terminate request. + # The runtime estimate is captured before the cost POST and the terminate request. emit_cost ec2 instance "$(( $(date +%s) - {{.LaunchEpoch}} ))" aws ec2 terminate-instances --instance-ids "$INSTANCE_ID" --region "$REGION" } @@ -66,35 +49,25 @@ emit_cost s3 get 1 # Checkpoint: the algorithm artifact (EIF) is now on the host, before the enclave is launched. emit_event artifact-retrieved -# sce-unit connects back to the parent (CID 3) on port 5000 and streams the DC app's output; one connection per run. -python3 - <<'PYEOF' & -import socket -s = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) -s.settimeout(3600) -s.bind((socket.VMADDR_CID_ANY, 5000)) -s.listen(1) -conn, _ = s.accept() -conn.settimeout(3600) -with open("/tmp/output.txt", "wb") as f: - while chunk := conn.recv(65536): - f.write(chunk) -PYEOF -OUTPUT_LISTENER_PID=$! - -# Serve this run's id and record limit to the enclave on port 5001 - the enclave takes no user-data, so it -# has no other way to learn the per-run id or how many records to read (the EIF carries per-algorithm config). -python3 - <<'PYEOF' & +# The enclave takes no user-data, so per-run values (the EIF carries per-algorithm config) come from port 5001. +python3 - > /dev/null <<'PYEOF' & import json, socket s = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((socket.VMADDR_CID_ANY, 5001)) s.listen(5) -body = json.dumps({"runId": "{{.RunId}}", "size": {{.Size}}}).encode() +body = json.dumps({ + "runId": "{{.RunId}}", + "size": {{.Size}}, + "webhookUrl": {{.WebhookURL}}, +}).encode() while True: conn, _ = s.accept() conn.sendall(body) conn.close() PYEOF +RUNINFO_LISTENER_PID=$! + # Only way out of the enclave: one vsock-proxy per allowed host forwards vsock traffic over real TCP/TLS, resolving DNS here since the enclave has none. cat > /etc/nitro_enclaves/vsock-proxy.yaml </dev/null || true - wait "$OUTPUT_LISTENER_PID" 2>/dev/null || true +if [ "$launched" = false ]; then + kill "$RUNINFO_LISTENER_PID" 2>/dev/null || true + emit_event enclave-launch-failed "$(tail -c 4096 /tmp/run-enclave.log | python3 -c 'import json, sys; print(json.dumps({"runEnclave": sys.stdin.read()}))')" exit 1 fi + +emit_event enclave-launched +# A single empty describe-enclaves can be transient right after launch; require several in a row. +ENCLAVE_GONE_POLLS=5 +gone=0 +while [ "$gone" -lt "$ENCLAVE_GONE_POLLS" ]; do + ENCLAVE_COUNT=$(nitro-cli describe-enclaves | python3 -c 'import json, sys; print(sum(e.get("EnclaveCID") == 16 for e in json.load(sys.stdin)))') || exit 1 + if [ "$ENCLAVE_COUNT" -eq 0 ]; then gone=$((gone + 1)); else gone=0; fi + sleep 1 +done diff --git a/secure/telemetry-service/src/lib/events.ts b/secure/telemetry-service/src/lib/events.ts index efb13d3d..f7b147dd 100644 --- a/secure/telemetry-service/src/lib/events.ts +++ b/secure/telemetry-service/src/lib/events.ts @@ -15,7 +15,13 @@ export const ENCLAVE_EVENTS = [ // Host-reported events. The EC2 host posts them directly without a token, so they carry origin=host // instead of being presented as enclave claims. -export const HOST_EVENTS = ["executor-ready", "artifact-retrieved", "enclave-launched", "executor-finished"] as const; +export const HOST_EVENTS = [ + "executor-ready", + "artifact-retrieved", + "enclave-launched", + "enclave-launch-failed", + "executor-finished", +] as const; // Control-plane producers: registry-service, execution-service, and result-consumer. export const INTERNAL_EVENTS = [ diff --git a/secure/verifier-service/README.md b/secure/verifier-service/README.md index 51907c61..8b14e86c 100644 --- a/secure/verifier-service/README.md +++ b/secure/verifier-service/README.md @@ -6,10 +6,29 @@ Serverless Framework v4, TypeScript. Receives `AlgorithmId` + PCR values from re - `POST /algorithms` (mTLS domain) - registry-service registers `AlgorithmId` -> PCR0/1/2 at build time. - `POST /challenge` (public domain) - sce-unit asks for a single-use nonce before attesting. The row is stored hashed in `AttestationChallengeTable` with a 60 s TTL and is bound to the `algorithmId` and `runId` in the request. -- `POST /attest` (public domain) - sce-unit submits a real Nitro attestation document (base64 COSE_Sign1 bytes) + `algorithmId` + `runId` + the `challenge` it was issued. The document's `nonce` must equal the challenge, and the challenge is consumed atomically before the PCR check, so a captured document cannot be replayed. After the PCR check, the run is claimed in `RunAttestationTable` with a conditional put, so only the first attestation for a `runId` succeeds; later ones get 409. Verified against the pinned AWS Nitro root cert chain and the registered PCRs; on success, issues a signed access JWT + opaque refresh token (persisted in `AttestationSessionTable`, including `RunId`). +- `POST /attest` (public domain) - sce-unit submits a real Nitro attestation document (base64 COSE_Sign1 bytes) + `algorithmId` + `runId` + the `challenge` it was issued. The document's `nonce` must equal the challenge, and the challenge is consumed atomically before the PCR check, so a captured document cannot be replayed. After the PCR check, the run is claimed in `RunAttestationTable` with a conditional put, so only the first attestation for a `runId` succeeds; later ones get 409. The attestation document's `public_key` is stored on the `RunAttestationTable` row with `AlgorithmId`; the DC uses it to verify signed run results. Verified against the pinned AWS Nitro root cert chain and the registered PCRs; on success, issues a signed access JWT + opaque refresh token (persisted in `AttestationSessionTable`, including `RunId`). - `POST /refresh` (public domain) - exchanges a still-valid refresh token plus its `runId` for a new access JWT, without requiring a fresh attestation document. The `runId` must match the one stored on the session. +- `GET /runs/{runId}` (public domain) - returns `{runId, algorithmId, publicKey}` for a run that has attested. The DC uses it to verify the enclave's result signature. Public keys are public, so no auth. - `GET /.well-known/jwks.json` (public domain) - the ML-DSA-87 public key downstream services use to verify access JWTs locally. Public by definition, no auth. +### Verifying a webhook result + +A webhook run delivers this body to the DC: + +```json +{ "runId": "...", "algorithmId": "...", "payload": "", "signature": "" } +``` + +`payload` decodes to the signed JSON `{runId, algorithmId, status, output}`. The signature is ECDSA P-384 over SHA-256 of `sce-result-v1\n` followed by the exact payload bytes. + +To verify: + +1. `GET /runs/{runId}` on the public domain returns `{runId, algorithmId, publicKey}`; `publicKey` is base64 SPKI DER. +2. Check the signed `runId` and `algorithmId` match the values you expect. +3. Verify the signature with `publicKey`. + +The webhook is the only result delivery path for secure-rads. When the run webhook is result-consumer, it writes `RunResultsTable` and backs `GET /run/{runId}`. A DC-supplied webhook bypasses that table. + ### Access token format (ML-DSA-87 compact JWS) Downstream services (pdm-service, kms-service, log-service) verify the JWT locally against the JWKS endpoint - there is no `/validate` round-trip. Claims: diff --git a/secure/verifier-service/serverless.yml b/secure/verifier-service/serverless.yml index 8fb37967..e80ef1d3 100644 --- a/secure/verifier-service/serverless.yml +++ b/secure/verifier-service/serverless.yml @@ -38,7 +38,9 @@ provider: - dynamodb:UpdateItem Resource: !GetAtt AttestationChallengeTable.Arn - Effect: Allow - Action: dynamodb:PutItem + Action: + - dynamodb:PutItem + - dynamodb:GetItem Resource: !GetAtt RunAttestationTable.Arn - Effect: Allow Action: ssm:GetParameter @@ -74,6 +76,10 @@ functions: jwks: handler: src/handlers/jwks.handler + # No auth: it only serves the public key the DC verifies a run's signed result against. + runSigningKey: + handler: src/handlers/runSigningKey.handler + resources: Conditions: HasTruststoreVersion: @@ -281,6 +287,29 @@ resources: Principal: apigateway.amazonaws.com SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${PublicHttpApi}/*/*/*" + RunSigningKeyIntegration: + Type: AWS::ApiGatewayV2::Integration + Properties: + ApiId: !Ref PublicHttpApi + IntegrationType: AWS_PROXY + IntegrationUri: !GetAtt RunSigningKeyLambdaFunction.Arn + PayloadFormatVersion: "2.0" + + RunSigningKeyRoute: + Type: AWS::ApiGatewayV2::Route + Properties: + ApiId: !Ref PublicHttpApi + RouteKey: "GET /runs/{runId}" + Target: !Sub "integrations/${RunSigningKeyIntegration}" + + RunSigningKeyInvokePermission: + Type: AWS::Lambda::Permission + Properties: + FunctionName: !Ref RunSigningKeyLambdaFunction + Action: lambda:InvokeFunction + Principal: apigateway.amazonaws.com + SourceArn: !Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${PublicHttpApi}/*/*/*" + PublicApiCustomDomain: Type: AWS::ApiGatewayV2::DomainName Properties: @@ -302,6 +331,8 @@ resources: Value: !Ref AttestationSessionTable AttestationChallengeTableName: Value: !Ref AttestationChallengeTable + RunAttestationTableName: + Value: !Ref RunAttestationTable TruststoreBucketName: Value: !Ref TruststoreBucket ApiRegionalDomainName: diff --git a/secure/verifier-service/src/handlers/runSigningKey.ts b/secure/verifier-service/src/handlers/runSigningKey.ts new file mode 100644 index 00000000..7781b607 --- /dev/null +++ b/secure/verifier-service/src/handlers/runSigningKey.ts @@ -0,0 +1,47 @@ +import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; +import { DynamoDBDocumentClient, GetCommand } 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 tableName = requiredEnv("RUN_ATTESTATION_TABLE"); + +interface AttestedRun { + AlgorithmId?: unknown; + PublicKey?: unknown; +} + +export const handler: APIGatewayProxyHandlerV2 = async (event) => { + const startedAt = process.hrtime.bigint(); + const runId = event.pathParameters?.runId; + if (!runId) return { statusCode: 400, body: "runId is required" }; + + const response = await ddb.send( + new GetCommand({ + TableName: tableName, + Key: { RunId: runId }, + ConsistentRead: true, + ReturnConsumedCapacity: "TOTAL", + }), + ); + const item = response.Item as AttestedRun | undefined; + if (typeof item?.AlgorithmId !== "string" || typeof item.PublicKey !== "string") { + return { statusCode: 404, body: "run has not attested" }; + } + + await costEvent( + item.AlgorithmId, + runId, + CostPhase.Execution, + "dynamodb", + "read-capacity", + response.ConsumedCapacity?.CapacityUnits ?? 0, + ); + await recordRequest(item.AlgorithmId, runId, CostPhase.Execution, startedAt); + return { + statusCode: 200, + headers: { "content-type": "application/json" }, + body: JSON.stringify({ runId, algorithmId: item.AlgorithmId, publicKey: item.PublicKey }), + }; +}; diff --git a/secure/verifier-service/src/lib/attestFlow.ts b/secure/verifier-service/src/lib/attestFlow.ts index bbb97d9f..ef8ff095 100644 --- a/secure/verifier-service/src/lib/attestFlow.ts +++ b/secure/verifier-service/src/lib/attestFlow.ts @@ -18,7 +18,7 @@ export interface AttestDeps { registered: RegisteredPcrs; verifyDocument(raw: Buffer): AttestationDocument; consumeChallenge(challenge: string, algorithmId: string, runId: string): Promise; - claimRunAttestation(algorithmId: string, runId: string): Promise; + claimRunAttestation(algorithmId: string, runId: string, publicKey: Buffer): Promise; issueTokens(algorithmId: string, runId: string): Promise; } @@ -44,6 +44,11 @@ export async function attestRequest(body: AttestBody, deps: AttestDeps): Promise return { statusCode: 401, body: `attestation verification failed: ${(err as Error).message}` }; } + // The public key is what the DC later verifies signed webhook results against. + if (!doc.publicKey || doc.publicKey.length === 0) { + return { statusCode: 401, body: "attestation document is missing a public key" }; + } + const challenge = decodeChallenge(body.challenge); if (!challenge || !doc.nonce || doc.nonce.length !== challenge.length || !timingSafeEqual(doc.nonce, challenge)) { return { @@ -64,7 +69,7 @@ export async function attestRequest(body: AttestBody, deps: AttestDeps): Promise } // A run attests once. Claiming after the measurement check keeps a wrong-image request from burning a run. - if (!(await deps.claimRunAttestation(body.algorithmId, body.runId))) { + if (!(await deps.claimRunAttestation(body.algorithmId, body.runId, doc.publicKey))) { return { statusCode: 409, body: "run already attested" }; } diff --git a/secure/verifier-service/src/lib/runAttestation.ts b/secure/verifier-service/src/lib/runAttestation.ts index bd3a8324..be033185 100644 --- a/secure/verifier-service/src/lib/runAttestation.ts +++ b/secure/verifier-service/src/lib/runAttestation.ts @@ -6,7 +6,7 @@ import { requiredEnv } from "@srads/common/env"; const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})); const tableName = requiredEnv("RUN_ATTESTATION_TABLE"); -export async function claimRunAttestation(algorithmId: string, runId: string): Promise { +export async function claimRunAttestation(algorithmId: string, runId: string, publicKey: Buffer): Promise { try { const write = await ddb.send( new PutCommand({ @@ -15,6 +15,7 @@ export async function claimRunAttestation(algorithmId: string, runId: string): P RunId: runId, AlgorithmId: algorithmId, AttestedAt: new Date().toISOString(), + PublicKey: publicKey.toString("base64"), }, ConditionExpression: "attribute_not_exists(RunId)", ReturnConsumedCapacity: "TOTAL",