The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Create a dedicated bucket and new-object queues for the Beacon reader
shukieshah3d3384387768
diff --git a/CLAUDE.md b/CLAUDE.mdindex 403260e7..012ce4aa 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -18,7 +18,7 @@ Beacon Endpoint Agent is a local-only endpoint telemetry agent for AI runtimes.- `spec/lenses`: the Lenses format — single-file HTML views of one trace that the local dashboard runs in a sandboxed, network-less frame and feeds once through `window.beacon.getTrace()`. The contract types (`LensManifestV1`, `LensDataV1`) live in `pkg/asymptoteobserve/lens.go`, and `lens_test.go` pins the spec's examples and manifest schema to them. The dashboard builds the data in `BuildLensData` (`/api/lens-data`), lists lenses at `/api/lenses`, and serves each lens at `/lenses/frame/<id>` under the spec's CSP with `lenses/prelude.js` (which defines `window.beacon`) injected ahead of it; that route is the only one that may be framed. Built-in lenses are `cli/beacon/internal/endpoint/dashboard/lenses/*.lens.html`, and `activity` is byte-identical to the spec example (a test enforces it). The session page (`static/session.html`, `initLensTabs` in `app.js`) shows lenses as tabs fed by `/api/lens-data?session=`, which projects exactly the events that page lists; it is the host half of the protocol and closes a lens that errors, stalls, or navigates its own frame. Trust model (SPEC "Trust model"): the opaque origin, sandbox and CSP keep a lens from touching Beacon or the dashboard and block ordinary network APIs, but cannot fully prevent a lens from sending trace data out through browser features no CSP governs (WebRTC, resource hints, speculative loading), so an installed lens is code the person trusts with the trace data it is shown; never describe the sandbox as making exfiltration impossible. `prelude.js` removes the `RTC*` globals and guards the document (refuses creating, inserting or parsing in nested frames, `<link>` elements and `<script type=speculationrules>`, parsing markup in the real call's document and context and inserting exactly the checked nodes so `<noscript>`/foreign-content parser differentials cannot slip through, refuses `document.write` and `execCommand("insertHTML")`, and a mutation observer removes those from the file's own markup); that is best-effort hardening, not a boundary, and the hostile `probe` fixture in `testdata/lens-e2e` pins each covered path. Installed lenses live in the lens store (`cli/beacon/internal/endpoint/lensstore`, `<BaseDir>/lenses/<id>.lens.html`, 0600 under 0700), written only by `beacon lenses add|remove` (`cli/beacon/cmd/lenses.go`; `add` prints the trust warning and confirms on a TTY, and refuses without one or in CI unless `--yes`); the dashboard rescans it per request and never writes it, and a store lens can never shadow a built-in. `asymptoteobserve.CheckLensFile` is the one file check every installer, server and linter uses. User docs are `docs/concepts/lenses.mdx` and `docs/cli/lenses.mdx`; keep them in sync with the commands and built-in lenses. The authoring loop is `beacon lenses spec` (the spec carried in the binary as `dashboard/lenses/SPEC.md`, kept byte-identical to `spec/lenses/SPEC.md` by a test), `beacon lenses data` (the exact `LensDataV1` for a session), `beacon lenses lint` (`lensstore.Lint`; built-ins must lint clean) and `beacon lenses preview` (the dashboard with `Options.LensFiles`, re-read per reload).- `beacon-sandbox`: harness that runs a real Claude Code session in a disposable sandbox and checks what Beacon captured. See `beacon-sandbox/AGENTS.md`.- `packaging`: macOS, Linux, and Windows packaging and deployment assets.-- `terraform`: customer-run Terraform modules for the cloud side of object storage forwarding. `aws-s3` creates the bucket (hardened, skipped with `create_bucket = false`), the put-only `beacon-endpoint-writer` IAM user, and optionally `beacon-s3-reader` for Beacon Cloud's S3 data connector, which reads with an access key because ClickPipes on the GCP-hosted ClickHouse rejects IAM roles. `gcs` creates the bucket, a `beacon-endpoint-writer` service account with `objectCreator` limited to the prefix by an IAM condition, an optional reader, and an optional `objectViewer` grant for Beacon's `beacon-clickpipes-reader`. Neither creates keys unless asked (`create_access_keys`, `create_writer_key`), so no secret lands in state by default. Resource names and the `forwarder_settings` output match the packaged `install-forwarder.sh` helpers and the manual guides. The AWS module needs provider 6.0+ for the per-data-source `region` that finds an existing bucket in another region. Docs are `docs/log-forwarding/{aws-s3,gcs}-terraform.mdx`, mirrored in beacon-mdr's docs, with the module pinned to a release tag; keep both in sync with the variables.+- `terraform`: customer-run Terraform modules for the cloud side of object storage forwarding. Each module always creates a new, dedicated bucket and never manages an existing one. `aws-s3` creates the hardened bucket, the put-only `beacon-endpoint-writer` IAM user, and optionally `beacon-s3-reader` for Beacon Cloud's S3 data connector, which reads with an access key because ClickPipes on the GCP-hosted ClickHouse rejects IAM roles. The reader comes with an SQS queue per stream (runtime, inventory), each with a dead-letter queue, and the bucket notification that feeds them, so the ClickPipes run in any-order mode; without a queue a pipe reads in key order and skips objects that land behind its cursor, which many Macs uploading on their own timers cause. `gcs` creates the bucket, a `beacon-endpoint-writer` service account with `objectCreator` limited to the prefix by an IAM condition, an optional reader, and with `grant_beacon_read_access` an `objectViewer` grant for Beacon's `beacon-clickpipes-reader` plus a Pub/Sub topic, bucket notification and one subscription per stream matching the managed path's (60 s ack, 7-day retention, never expiring, `objectId` prefix filter). The queue URLs and subscription paths are outputs, ready for the provisioning script's `--queue-url`. Neither module creates keys unless asked (`create_access_keys`, `create_writer_key`), so no secret lands in state by default. Resource names and the `forwarder_settings` output match the packaged `install-forwarder.sh` helpers and the manual guides. Docs are `docs/log-forwarding/{aws-s3,gcs}-terraform.mdx` and the connector steps in `docs/manage/configure-s3-data-connector.mdx`, mirrored in beacon-mdr's docs, with the module pinned to a release tag; keep both in sync with the variables.- `docs`: the published documentation site (docs.asymptotelabs.ai).Do not recreate or depend on removed `asymptote` mirror trees. Keep new work focused on the Beacon paths above.diff --git a/docs/guides/fleet-s3-mdm.mdx b/docs/guides/fleet-s3-mdm.mdxindex b0579517..03c20d21 100644--- a/docs/guides/fleet-s3-mdm.mdx+++ b/docs/guides/fleet-s3-mdm.mdx@@ -122,7 +122,7 @@ You can leave this Mac as it is. When Fleet installs the same package on it lateaws iam create-access-key --user-name beacon-endpoint-writer --output json```- The key starts with `AKIA` and doesn't expire. To use a bucket you already have or your own KMS key, see the [module's options](/log-forwarding/aws-s3-terraform#options).+ The key starts with `AKIA` and doesn't expire. For your own KMS key, object expiry, and other settings, see the [module's options](/log-forwarding/aws-s3-terraform#options).</Tab></Tabs>diff --git a/docs/guides/jamf-gcs-mdm.mdx b/docs/guides/jamf-gcs-mdm.mdxindex 88dba57d..5005b5a6 100644--- a/docs/guides/jamf-gcs-mdm.mdx+++ b/docs/guides/jamf-gcs-mdm.mdx@@ -133,7 +133,7 @@ deployments should use the root layout.export BEACON_GCS_READER_EMAIL="$(terraform output -raw reader_email)"```- For lifecycle rules, CMEK, or an existing bucket, see the+ For lifecycle rules or CMEK, see the[module's options](/log-forwarding/gcs-terraform#options).</Tab></Tabs>diff --git a/docs/guides/rippling-gcs-mdm.mdx b/docs/guides/rippling-gcs-mdm.mdxindex 4948e727..87dd2191 100644--- a/docs/guides/rippling-gcs-mdm.mdx+++ b/docs/guides/rippling-gcs-mdm.mdx@@ -177,7 +177,7 @@ Prepare:export BEACON_GCS_READER_EMAIL="$(terraform output -raw reader_email)"```- For lifecycle rules, CMEK, or an existing bucket, see the+ For lifecycle rules or CMEK, see the[module's options](/log-forwarding/gcs-terraform#options).</Tab></Tabs>diff --git a/docs/log-forwarding/aws-s3-terraform.mdx b/docs/log-forwarding/aws-s3-terraform.mdxindex ee264465..c9df5610 100644--- a/docs/log-forwarding/aws-s3-terraform.mdx+++ b/docs/log-forwarding/aws-s3-terraform.mdx@@ -9,9 +9,9 @@ The AWS CLI steps in the rollout guides create the same resources. Follow either## What you'll set up-- **An S3 bucket** with public access blocked, ACLs disabled, HTTPS required, default encryption (SSE-S3, or SSE-KMS with your key), and versioning.+- **A new S3 bucket just for Beacon**, with public access blocked, ACLs disabled, HTTPS required, default encryption (SSE-S3, or SSE-KMS with your key), and versioning. The module always creates its own bucket and does not manage existing ones.- **`beacon-endpoint-writer`**, an IAM user that can upload objects below your Beacon prefix and can't read or delete them.-- **Optionally, `beacon-s3-reader`**, a read-only IAM user for [Beacon Cloud's S3 data connector](/manage/configure-s3-data-connector).+- **Optionally, `beacon-s3-reader`**, a read-only IAM user for [Beacon Cloud's S3 data connector](/manage/configure-s3-data-connector), with two SQS queues that tell Beacon about each new object.Every Mac's forwarder writes both of Beacon's logs to the bucket:@@ -27,7 +27,7 @@ The module is in the Beacon repository at [`terraform/aws-s3`](https://github.co| You need | Why || --- | --- || Terraform 1.5 or later | Runs the module. |-| AWS provider 6.0 or later | Terraform installs it during `terraform init`. |+| AWS provider 5.0 or later | Terraform installs it during `terraform init`. || An AWS identity that can create S3 buckets, IAM users, and IAM user policies | Used by `terraform apply`. || The AWS CLI, signed in as that identity | Creates the writer's access key in step 3. || A bucket name nobody else uses | S3 bucket names are global across all AWS accounts. |@@ -147,18 +147,6 @@ aws s3 ls "s3://${BEACON_S3_BUCKET}/${BEACON_S3_PREFIX}/runtime/" --recursive --Set any of these in the `module "beacon_s3"` block and run `terraform apply` again. Every input is described in [`variables.tf`](https://github.com/asymptote-labs/agent-beacon/blob/main/terraform/aws-s3/variables.tf).<AccordionGroup>- <Accordion title="Use a bucket you already have">- ```hcl- create_bucket = false- bucket_name = "acme-security-logs"- existing_bucket_region = "us-east-1" # only if it differs from the provider's region- ```-- The module then creates only the IAM users and changes nothing on the bucket. Two bucket settings can block uploads:-- - **Customer managed KMS key.** Set `kms_key_arn` to the bucket's key so the writer gets `kms:GenerateDataKey`.- - **A bucket policy that requires encryption headers.** The forwarder sends none and relies on the bucket's default encryption, so such a policy rejects every upload.- </Accordion><Accordion title="Encrypt with your own KMS key">```hclkms_key_arn = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"@@ -184,7 +172,9 @@ Set any of these in the `module "beacon_s3"` block and run `terraform apply` agaaws iam create-access-key --user-name beacon-s3-reader --output json```- Send Beacon the key and the `beacon_reader_source_url` output. See [Configure S3 Data Connector](/manage/configure-s3-data-connector).+ It also adds two SQS queues, `beacon-s3-reader-runtime` and `beacon-s3-reader-inventory`, each with a dead-letter queue. S3 announces every new object below the prefix on its stream's queue, and Beacon loads what the queues name. Without them Beacon would read objects in name order and could skip ones that arrive late, which happens when many Macs upload at once.++ Send Beacon the key, the `beacon_reader_source_url` output, and the two URLs in `beacon_reader_queue_urls`. See [Configure S3 Data Connector](/manage/configure-s3-data-connector).</Accordion><Accordion title="Create the access keys with Terraform">```hcl@@ -216,6 +206,7 @@ Set any of these in the `module "beacon_s3"` block and run `terraform apply` aga| `writer_user_name`, `writer_user_arn` | The IAM user every Mac uploads as || `beacon_reader_user_name`, `beacon_reader_user_arn` | The Beacon reader, when `create_beacon_reader = true` || `beacon_reader_source_url` | The location to send Beacon for the S3 data connector |+| `beacon_reader_queue_urls` | The new-object queues to send Beacon, by stream || `writer_access_key_id`, `writer_secret_access_key` | Only with `create_access_keys = true` |## Rotate the writer key@@ -241,9 +232,6 @@ Rotation happens outside Terraform. IAM allows two keys per user, so the old key## Troubleshooting<AccordionGroup>- <Accordion title="Error: reading S3 Bucket (...): empty result">- With `create_bucket = false`, the bucket is in a different region from the provider. Set `existing_bucket_region` to the bucket's region.- </Accordion><Accordion title="BucketAlreadyExists">Someone else, in any AWS account, already has a bucket with that name. Choose another `bucket_name`.</Accordion>@@ -251,7 +239,7 @@ Rotation happens outside Terraform. IAM allows two keys per user, so the old key`terraform destroy` or a rename is trying to delete an IAM user that still has a key you created with the AWS CLI. Delete the key first. See [Remove](#remove).</Accordion><Accordion title="Uploads fail with AccessDenied">- Check that the forwarder's bucket, region, and prefix match the Terraform outputs exactly. The writer can only upload below `<prefix>/`. For an existing bucket with a customer managed KMS key, set `kms_key_arn`.+ Check that the forwarder's bucket, region, and prefix match the Terraform outputs exactly. The writer can only upload below `<prefix>/`.</Accordion></AccordionGroup>diff --git a/docs/log-forwarding/gcs-terraform.mdx b/docs/log-forwarding/gcs-terraform.mdxindex 7a16c836..1d9fc5cc 100644--- a/docs/log-forwarding/gcs-terraform.mdx+++ b/docs/log-forwarding/gcs-terraform.mdx@@ -9,10 +9,10 @@ The gcloud steps in the rollout guides create the same resources. Follow either## What you'll set up-- **A Cloud Storage bucket** with uniform bucket-level access, public access prevention enforced, versioning, and optionally your Cloud KMS key.+- **A new Cloud Storage bucket just for Beacon**, with uniform bucket-level access, public access prevention enforced, versioning, and optionally your Cloud KMS key. The module always creates its own bucket and does not manage existing ones.- **`beacon-endpoint-writer`**, a service account that can create objects below your Beacon prefix and can't list, read, or delete them.- **`beacon-endpoint-reader`**, a read-only service account for checking uploads.-- **Optionally, read access for Beacon Cloud**, so Beacon can ingest the telemetry you store.+- **Optionally, read access for Beacon Cloud**, so Beacon can ingest the telemetry you store, with Pub/Sub subscriptions that tell Beacon about each new object.Every Mac's forwarder writes both of Beacon's logs to the bucket:@@ -159,14 +159,6 @@ gcloud storage ls "gs://${BEACON_GCS_BUCKET}/${BEACON_GCS_PREFIX}/runtime/**" \Set any of these in the `module "beacon_gcs"` block and run `terraform apply` again. Every input is described in [`variables.tf`](https://github.com/asymptote-labs/agent-beacon/blob/main/terraform/gcs/variables.tf).<AccordionGroup>- <Accordion title="Use a bucket you already have">- ```hcl- create_bucket = false- bucket_name = "acme-security-logs"- ```-- The module then creates only the service accounts and their bucket IAM bindings, and changes nothing else on the bucket. The writer's binding uses an IAM condition, which needs uniform bucket-level access. If the bucket still uses fine-grained ACLs, set `scope_writer_to_prefix = false`; the writer can then create objects anywhere in the bucket.- </Accordion><Accordion title="Encrypt with your own Cloud KMS key">```hclkms_key_name = "projects/acme-security/locations/us-west1/keyRings/beacon/cryptoKeys/telemetry"@@ -186,7 +178,11 @@ Set any of these in the `module "beacon_gcs"` block and run `terraform apply` aggrant_beacon_read_access = true```- This grants `roles/storage.objectViewer` on the bucket to Beacon's reader, `[email protected]`. No key is involved. Then send Beacon the bucket name and prefix.+ This grants `roles/storage.objectViewer` on the bucket to Beacon's reader, `[email protected]`. No key is involved.++ It also enables Pub/Sub and creates a topic that the bucket notifies of every new object below the prefix, with one subscription per stream that Beacon's reader can consume. Beacon loads what the subscriptions name. Without them Beacon would read objects in name order and could skip ones that arrive late, which happens when many Macs upload at once.++ Send Beacon the bucket name, the prefix, and the two subscriptions in `beacon_reader_subscriptions`.</Accordion><Accordion title="Create the writer's key with Terraform">```hcl@@ -210,6 +206,7 @@ Set any of these in the `module "beacon_gcs"` block and run `terraform apply` ag| `bucket_url` | `gs://<bucket>/<prefix>/` || `writer_email` | The service account every Mac uploads as || `reader_email` | The read-only service account, when `create_reader = true` |+| `beacon_reader_subscriptions` | The new-object subscriptions to send Beacon, by stream, when `grant_beacon_read_access = true` || `writer_private_key` | Only with `create_writer_key = true` |## Rotate the writer key@@ -224,15 +221,9 @@ Rotation happens outside Terraform. Create a new key, deliver it to every Mac, r## Troubleshooting<AccordionGroup>- <Accordion title="location is required when create_bucket = true">- Set `location` to a region such as `us-west1` or a multi-region such as `US`.- </Accordion><Accordion title="The bucket name is already taken">Someone else, in any project, already has a bucket with that name. Choose another `bucket_name`.</Accordion>- <Accordion title="Terraform can't add the writer's IAM binding to an existing bucket">- An existing bucket without uniform bucket-level access can't hold the writer's IAM condition. Turn on uniform access for the bucket, or set `scope_writer_to_prefix = false`.- </Accordion><Accordion title="Uploads fail with 403">Check that the forwarder's bucket and prefix match the Terraform outputs exactly. The writer can only create objects below `<prefix>/`.</Accordion>diff --git a/docs/manage/configure-s3-data-connector.mdx b/docs/manage/configure-s3-data-connector.mdxindex c230f20d..56e2637e 100644--- a/docs/manage/configure-s3-data-connector.mdx+++ b/docs/manage/configure-s3-data-connector.mdx@@ -5,13 +5,17 @@ description: "Configure read-only S3 access for Beacon ingestion."## Overview-Beacon can ingest customer-hosted event files from a private AWS S3 bucket or prefix. Beacon reads them with the access key of a read-only IAM user you create. That user can list the bucket and read objects below the prefix you choose, and nothing else.+Beacon can ingest customer-hosted event files from a private AWS S3 bucket or prefix. Beacon reads them with the access key of a read-only IAM user you create. That user can list the bucket, read objects below the prefix you choose, and consume two notification queues, and nothing else.Beacon can't assume an IAM role in your account for this connector, so use an IAM user's access key.Do not make the bucket public. Do not grant write or delete permissions.-## Create the read-only user+## Create the read-only user and queues++Beacon reads the bucket with the access key of a read-only IAM user. It also needs two SQS queues, one per stream, that S3 notifies of every new object. Beacon loads the objects the queues name, in any order. Without them Beacon would read objects in name order and could skip ones that arrive late, which happens when many Macs upload at once.++Use a bucket dedicated to Beacon telemetry: the notification setup below replaces any notifications already configured on the bucket.<Tabs><Tab title="Terraform">@@ -24,21 +28,81 @@ Do not make the bucket public. Do not grant write or delete permissions.}```- The module creates `beacon-s3-reader` with the policy shown in the other tab, including `kms:Decrypt` when you set `kms_key_arn`. Create its access key:+ The module creates `beacon-s3-reader` with the policy shown in the other tab, including `kms:Decrypt` when you set `kms_key_arn`, the two queues with their dead-letter queues, and the bucket notification. Create the reader's access key:```bashaws iam create-access-key --user-name beacon-s3-reader --output json```++ The `beacon_reader_queue_urls` output holds the two queue URLs.</Tab><Tab title="AWS CLI">- Set the bucket and the prefix that holds the event files:+ **Set your values.** Use the bucket's region and the prefix that holds the event files:```bash+ export AWS_REGION="<bucket region>"export BEACON_S3_BUCKET="<bucket>"export BEACON_S3_PREFIX="beacon-prod"+ export AWS_ACCOUNT_ID="$(aws sts get-caller-identity --query Account --output text)"+ ```++ **Create the queues.** Each stream gets a queue that only this bucket may send to, and a dead-letter queue that keeps a message after ten failed deliveries:++ ```bash+ for stream in runtime inventory; do+ dlq_url="$(aws sqs create-queue --region "$AWS_REGION" \+ --queue-name "beacon-s3-reader-${stream}-dlq" \+ --attributes MessageRetentionPeriod=1209600,SqsManagedSseEnabled=true \+ --query QueueUrl --output text)"+ dlq_arn="$(aws sqs get-queue-attributes --region "$AWS_REGION" --queue-url "$dlq_url" \+ --attribute-names QueueArn --query Attributes.QueueArn --output text)"+ queue_arn="arn:aws:sqs:${AWS_REGION}:${AWS_ACCOUNT_ID}:beacon-s3-reader-${stream}"+ cat > "beacon-s3-reader-${stream}.json" <<EOF+ {+ "MessageRetentionPeriod": "1209600",+ "VisibilityTimeout": "300",+ "SqsManagedSseEnabled": "true",+ "RedrivePolicy": "{\"deadLetterTargetArn\":\"${dlq_arn}\",\"maxReceiveCount\":10}",+ "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"s3.amazonaws.com\"},\"Action\":\"sqs:SendMessage\",\"Resource\":\"${queue_arn}\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"arn:aws:s3:::${BEACON_S3_BUCKET}\"},\"StringEquals\":{\"aws:SourceAccount\":\"${AWS_ACCOUNT_ID}\"}}}]}"+ }+ EOF+ aws sqs create-queue --region "$AWS_REGION" \+ --queue-name "beacon-s3-reader-${stream}" \+ --attributes "file://beacon-s3-reader-${stream}.json"+ done```- Create the user and give it read-only access to that prefix:+ The loop prints the `QueueUrl` of the `runtime` and `inventory` queues. Keep both to send to Beacon.++ **Send new-object notifications to the queues:**++ ```bash+ cat > beacon-notifications.json <<EOF+ {+ "QueueConfigurations": [+ {+ "Id": "beacon-runtime",+ "QueueArn": "arn:aws:sqs:${AWS_REGION}:${AWS_ACCOUNT_ID}:beacon-s3-reader-runtime",+ "Events": ["s3:ObjectCreated:*"],+ "Filter": {"Key": {"FilterRules": [{"Name": "prefix", "Value": "${BEACON_S3_PREFIX}/runtime/"}]}}+ },+ {+ "Id": "beacon-inventory",+ "QueueArn": "arn:aws:sqs:${AWS_REGION}:${AWS_ACCOUNT_ID}:beacon-s3-reader-inventory",+ "Events": ["s3:ObjectCreated:*"],+ "Filter": {"Key": {"FilterRules": [{"Name": "prefix", "Value": "${BEACON_S3_PREFIX}/inventory/"}]}}+ }+ ]+ }+ EOF+ aws s3api put-bucket-notification-configuration \+ --bucket "$BEACON_S3_BUCKET" \+ --notification-configuration file://beacon-notifications.json+ ```++ It prints nothing when it works.++ **Create the user** and give it read-only access to the prefix and the two queues:```bashaws iam create-user --user-name beacon-s3-reader@@ -59,6 +123,19 @@ Do not make the bucket public. Do not grant write or delete permissions."Effect": "Allow","Action": "s3:GetObject","Resource": "arn:aws:s3:::${BEACON_S3_BUCKET}/${BEACON_S3_PREFIX}/*"+ },+ {+ "Effect": "Allow",+ "Action": ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"],+ "Resource": [+ "arn:aws:sqs:${AWS_REGION}:${AWS_ACCOUNT_ID}:beacon-s3-reader-runtime",+ "arn:aws:sqs:${AWS_REGION}:${AWS_ACCOUNT_ID}:beacon-s3-reader-inventory"+ ]+ },+ {+ "Effect": "Allow",+ "Action": "sqs:ListQueues",+ "Resource": "*"}]}@@ -76,7 +153,7 @@ Do not make the bucket public. Do not grant write or delete permissions.}```- Create the access key:+ **Create the access key:**```bashaws iam create-access-key --user-name beacon-s3-reader --output json@@ -92,6 +169,7 @@ Send these through the secure channel your Beacon contact gives you. Don't send- S3 bucket name and AWS region- Prefix for the event files, such as `s3://your-bucket/beacon-prod/`+- The two queue URLs, for `runtime` and `inventory`- The access key ID and secret access key- KMS key ARN, only if SSE-KMS is enabled- For files that Beacon's forwarder didn't write: the file format (ideally JSONL), delivery cadence, approximate event volume, and a small sample file or example JSONL row@@ -100,7 +178,54 @@ To rotate the key later, create a second key for `beacon-s3-reader`, send it to## Using Google Cloud Storage-For a Cloud Storage bucket, no key is involved. Grant `roles/storage.objectViewer` on the bucket to `[email protected]`, or set `grant_beacon_read_access = true` in the [Terraform module](/log-forwarding/gcs-terraform). Then send Beacon the bucket name and prefix.+For a Cloud Storage bucket, no key is involved. Beacon reads with its own service account, `[email protected]`, and needs a Pub/Sub subscription per stream for the same reason S3 needs the queues.++<Tabs>+ <Tab title="Terraform">+ Set `grant_beacon_read_access = true` in the [Terraform module](/log-forwarding/gcs-terraform) and apply. Send Beacon the bucket name, the prefix, and the two subscriptions in `beacon_reader_subscriptions`.+ </Tab>+ <Tab title="gcloud">+ ```bash+ export GCP_PROJECT="<project-id>"+ export BEACON_GCS_BUCKET="<bucket>"+ export BEACON_GCS_PREFIX="beacon-prod"+ export BEACON_READER="serviceAccount:[email protected]"+ export BEACON_TOPIC="beacon-${BEACON_GCS_BUCKET}-objects"++ # Let Beacon read the bucket.+ gcloud storage buckets add-iam-policy-binding "gs://${BEACON_GCS_BUCKET}" \+ --member "$BEACON_READER" --role roles/storage.objectViewer++ # Publish every new object below the prefix to a topic.+ gcloud pubsub topics create "$BEACON_TOPIC" --project "$GCP_PROJECT"+ gcloud pubsub topics add-iam-policy-binding "$BEACON_TOPIC" --project "$GCP_PROJECT" \+ --member "serviceAccount:$(gcloud storage service-agent --project "$GCP_PROJECT" | tr -d '[:space:]')" \+ --role roles/pubsub.publisher+ gcloud storage buckets notifications create "gs://${BEACON_GCS_BUCKET}" \+ --topic "projects/${GCP_PROJECT}/topics/${BEACON_TOPIC}" \+ --event-types OBJECT_FINALIZE \+ --object-prefix "${BEACON_GCS_PREFIX}/" \+ --payload-format json++ # One subscription per stream that Beacon may consume. They never expire.+ for stream in runtime inventory; do+ gcloud pubsub subscriptions create "beacon-${BEACON_GCS_BUCKET}-${stream}" \+ --project "$GCP_PROJECT" \+ --topic "$BEACON_TOPIC" \+ --message-filter "attributes.eventType = \"OBJECT_FINALIZE\" AND hasPrefix(attributes.objectId, \"${BEACON_GCS_PREFIX}/${stream}/\")" \+ --ack-deadline 60 \+ --message-retention-duration 7d \+ --expiration-period never+ for role in roles/pubsub.subscriber roles/pubsub.viewer; do+ gcloud pubsub subscriptions add-iam-policy-binding "beacon-${BEACON_GCS_BUCKET}-${stream}" \+ --project "$GCP_PROJECT" --member "$BEACON_READER" --role "$role"+ done+ done+ ```++ Send Beacon the bucket name, the prefix, and the two subscriptions: `projects/<project-id>/subscriptions/beacon-<bucket>-runtime` and `-inventory`.+ </Tab>+</Tabs>## Event file requirements@@ -117,7 +242,7 @@ Beacon's own S3 forwarder already writes this format, as gzip-compressed JSONL bReview managed visibility, governance, and investigation workflows.</Card><Card title="AWS S3 with Terraform" icon="bucket" href="/log-forwarding/aws-s3-terraform">- Create the bucket, writer, and Beacon reader with Terraform.+ Create the bucket, writer, Beacon reader, and queues with Terraform.</Card><Card title="Object Storage Forwarding" icon="bucket" href="/guides/macos-object-storage-system">Configure customer-managed Beacon event forwarding into S3.diff --git a/terraform/aws-s3/README.md b/terraform/aws-s3/README.mdindex 47d2da36..6dab9139 100644--- a/terraform/aws-s3/README.md+++ b/terraform/aws-s3/README.md@@ -2,13 +2,14 @@Creates the AWS side of Beacon's S3 forwarding:-- an S3 bucket with public access blocked, ACLs disabled, TLS required, default- encryption (SSE-S3, or SSE-KMS with `kms_key_arn`), versioning, and a lifecycle rule- scoped to the Beacon prefix (skipped with `create_bucket = false`);+- a new, dedicated S3 bucket with public access blocked, ACLs disabled, TLS required,+ default encryption (SSE-S3, or SSE-KMS with `kms_key_arn`), versioning, and a+ lifecycle rule scoped to the Beacon prefix;- `beacon-endpoint-writer`, an IAM user that can only `s3:PutObject` below the prefix(plus `s3:ListBucket` for the forwarder's startup health check);- optionally `beacon-s3-reader`, a read-only IAM user for Beacon Cloud's S3 data- connector (`create_beacon_reader = true`).+ connector (`create_beacon_reader = true`), with an SQS queue per stream that S3+ notifies of every new object, so Beacon loads objects in any order.```hclprovider "aws" {@@ -37,9 +38,9 @@ aws iam create-access-key --user-name beacon-endpoint-writer`forwarder_settings` holds the non-secret values the packaged forwarder helper reads(`BEACON_S3_BUCKET`, `AWS_REGION`, `BEACON_S3_PREFIX`, `BEACON_S3_STORAGE_CLASS`).-The module needs Terraform 1.5 or later and the AWS provider 6.0 or later. A new bucket-is created in the provider's region. For an existing bucket in another region, set-`existing_bucket_region`.+The module needs Terraform 1.5 or later and the AWS provider 5.0 or later. The bucket+is created in the provider's region. The module always creates its own bucket; it does+not manage existing ones.Before `terraform destroy`, delete the access keys you created with the AWS CLI. IAMrefuses to delete a user that still has keys, which keeps a rename or replace fromdiff --git a/terraform/aws-s3/examples/basic/main.tf b/terraform/aws-s3/examples/basic/main.tfindex 189c6bc3..6bc2c3e9 100644--- a/terraform/aws-s3/examples/basic/main.tf+++ b/terraform/aws-s3/examples/basic/main.tf@@ -13,7 +13,7 @@ terraform {required_providers {aws = {source = "hashicorp/aws"- version = ">= 6.0"+ version = ">= 5.0"}}}diff --git a/terraform/aws-s3/iam.tf b/terraform/aws-s3/iam.tfindex 0a0fae47..6652bf6b 100644--- a/terraform/aws-s3/iam.tf+++ b/terraform/aws-s3/iam.tf@@ -40,6 +40,19 @@ locals {Action = "s3:GetObject"Resource = local.beacon_objects_arn},+ # The four actions ClickPipes needs to consume the new-object queues.+ {+ Sid = "ConsumeBeaconNotifications"+ Effect = "Allow"+ Action = ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"]+ Resource = [for queue in aws_sqs_queue.beacon_reader : queue.arn]+ },+ {+ Sid = "FindBeaconQueues"+ Effect = "Allow"+ Action = "sqs:ListQueues"+ Resource = "*"+ },],var.kms_key_arn == null ? [] : [{diff --git a/terraform/aws-s3/main.tf b/terraform/aws-s3/main.tfindex d0dcec74..aff4c1f9 100644--- a/terraform/aws-s3/main.tf+++ b/terraform/aws-s3/main.tf@@ -1,13 +1,6 @@data "aws_partition" "current" {}-# Only read for an existing bucket: it confirms the bucket exists and reports its region. The lookup-# runs in the provider's region unless existing_bucket_region names another.-data "aws_s3_bucket" "existing" {- count = var.create_bucket ? 0 : 1-- bucket = var.bucket_name- region = var.existing_bucket_region-}+data "aws_caller_identity" "current" {}locals {bucket_arn = "arn:${data.aws_partition.current.partition}:s3:::${var.bucket_name}"@@ -15,10 +8,8 @@ locals {# Beacon writes <prefix>/runtime/date=YYYY-MM-DD/... and <prefix>/inventory/date=YYYY-MM-DD/...beacon_objects_arn = "${local.bucket_arn}/${var.prefix}/*"- bucket_region = var.create_bucket ? aws_s3_bucket.this[0].region : data.aws_s3_bucket.existing[0].region-# S3's certificate for virtual-hosted URLs covers one label, so a dotted bucket name needs path style.- s3_host = "s3.${local.bucket_region}.${data.aws_partition.current.dns_suffix}"+ s3_host = "s3.${aws_s3_bucket.this.region}.${data.aws_partition.current.dns_suffix}"beacon_reader_source_url = (strcontains(var.bucket_name, ".")? "https://${local.s3_host}/${var.bucket_name}/${var.prefix}"@@ -26,25 +17,15 @@ locals {)}+# A dedicated bucket for Beacon telemetry, always created by the module.resource "aws_s3_bucket" "this" {- count = var.create_bucket ? 1 : 0-bucket = var.bucket_nameforce_destroy = var.force_destroytags = var.tags-- lifecycle {- precondition {- condition = var.existing_bucket_region == null- error_message = "existing_bucket_region applies only with create_bucket = false. A new bucket is created in the provider's region."- }- }}resource "aws_s3_bucket_public_access_block" "this" {- count = var.create_bucket ? 1 : 0-- bucket = aws_s3_bucket.this[0].id+ bucket = aws_s3_bucket.this.idblock_public_acls = trueblock_public_policy = trueignore_public_acls = true@@ -53,9 +34,7 @@ resource "aws_s3_bucket_public_access_block" "this" {# ACLs off: every object belongs to the bucket owner. The forwarder sends no ACL.resource "aws_s3_bucket_ownership_controls" "this" {- count = var.create_bucket ? 1 : 0-- bucket = aws_s3_bucket.this[0].id+ bucket = aws_s3_bucket.this.idrule {object_ownership = "BucketOwnerEnforced"@@ -64,9 +43,7 @@ resource "aws_s3_bucket_ownership_controls" "this" {# The forwarder sends no encryption headers, so the bucket default decides how objects are encrypted.resource "aws_s3_bucket_server_side_encryption_configuration" "this" {- count = var.create_bucket ? 1 : 0-- bucket = aws_s3_bucket.this[0].id+ bucket = aws_s3_bucket.this.idrule {apply_server_side_encryption_by_default {@@ -78,9 +55,9 @@ resource "aws_s3_bucket_server_side_encryption_configuration" "this" {}resource "aws_s3_bucket_versioning" "this" {- count = var.create_bucket && var.versioning_enabled ? 1 : 0+ count = var.versioning_enabled ? 1 : 0- bucket = aws_s3_bucket.this[0].id+ bucket = aws_s3_bucket.this.idversioning_configuration {status = "Enabled"@@ -88,9 +65,7 @@ resource "aws_s3_bucket_versioning" "this" {}resource "aws_s3_bucket_lifecycle_configuration" "this" {- count = var.create_bucket ? 1 : 0-- bucket = aws_s3_bucket.this[0].id+ bucket = aws_s3_bucket.this.idrule {id = "beacon-telemetry"@@ -123,9 +98,7 @@ resource "aws_s3_bucket_lifecycle_configuration" "this" {}resource "aws_s3_bucket_policy" "this" {- count = var.create_bucket ? 1 : 0-- bucket = aws_s3_bucket.this[0].id+ bucket = aws_s3_bucket.this.idpolicy = jsonencode({Version = "2012-10-17"Statement = [diff --git a/terraform/aws-s3/notifications.tf b/terraform/aws-s3/notifications.tfnew file mode 100644index 00000000..d9c0b529--- /dev/null+++ b/terraform/aws-s3/notifications.tf@@ -0,0 +1,78 @@+# Beacon Cloud's ClickPipes read the bucket in "any order" mode: S3 announces every new object on+# an SQS queue, and the pipe loads what the queue names. Without the queues a pipe lists objects in+# key order and skips any that sort before ones it has already loaded, which happens whenever Macs+# upload out of step.++locals {+ reader_streams = var.create_beacon_reader ? toset(["runtime", "inventory"]) : toset([])++ # SQS names allow letters, digits, hyphens and underscores; IAM user names allow a few more.+ reader_queue_base = replace(var.beacon_reader_user_name, "/[^A-Za-z0-9_-]/", "-")+}++# A message that fails ten deliveries moves here instead of being dropped, so it can be redriven.+resource "aws_sqs_queue" "beacon_reader_dead_letter" {+ for_each = local.reader_streams++ name = "${local.reader_queue_base}-${each.key}-dlq"+ message_retention_seconds = 1209600+ sqs_managed_sse_enabled = true+ tags = var.tags+}++resource "aws_sqs_queue" "beacon_reader" {+ for_each = local.reader_streams++ name = "${local.reader_queue_base}-${each.key}"+ message_retention_seconds = 1209600+ visibility_timeout_seconds = 300+ sqs_managed_sse_enabled = true+ tags = var.tags++ redrive_policy = jsonencode({+ deadLetterTargetArn = aws_sqs_queue.beacon_reader_dead_letter[each.key].arn+ maxReceiveCount = 10+ })+}++resource "aws_sqs_queue_policy" "beacon_reader" {+ for_each = local.reader_streams++ queue_url = aws_sqs_queue.beacon_reader[each.key].id+ policy = jsonencode({+ Version = "2012-10-17"+ Statement = [+ {+ Sid = "AllowBucketNotifications"+ Effect = "Allow"+ Principal = { Service = "s3.amazonaws.com" }+ Action = "sqs:SendMessage"+ Resource = aws_sqs_queue.beacon_reader[each.key].arn+ Condition = {+ ArnEquals = { "aws:SourceArn" = local.bucket_arn }+ StringEquals = { "aws:SourceAccount" = data.aws_caller_identity.current.account_id }+ }+ },+ ]+ })+}++# S3 keeps one notification configuration per bucket. The module owns this bucket, so it owns that too.+resource "aws_s3_bucket_notification" "this" {+ count = var.create_beacon_reader ? 1 : 0++ bucket = aws_s3_bucket.this.id++ dynamic "queue" {+ for_each = local.reader_streams+ content {+ id = "beacon-${queue.key}"+ queue_arn = aws_sqs_queue.beacon_reader[queue.key].arn+ events = ["s3:ObjectCreated:*"]+ filter_prefix = "${var.prefix}/${queue.key}/"+ }+ }++ # S3 checks that it may send to each queue when the configuration is written.+ depends_on = [aws_sqs_queue_policy.beacon_reader]+}diff --git a/terraform/aws-s3/outputs.tf b/terraform/aws-s3/outputs.tfindex 8e7580fa..6c8b856d 100644--- a/terraform/aws-s3/outputs.tf+++ b/terraform/aws-s3/outputs.tf@@ -1,6 +1,6 @@output "bucket_name" {description = "Bucket Beacon writes to."- value = var.create_bucket ? aws_s3_bucket.this[0].bucket : data.aws_s3_bucket.existing[0].bucket+ value = aws_s3_bucket.this.bucket}output "bucket_arn" {@@ -10,7 +10,7 @@ output "bucket_arn" {output "region" {description = "Region of the bucket (AWS_REGION for the forwarder)."- value = local.bucket_region+ value = aws_s3_bucket.this.region}output "prefix" {@@ -26,8 +26,8 @@ output "storage_class" {output "forwarder_settings" {description = "The non-secret settings Beacon's S3 forwarder helper reads, keyed by environment variable name."value = {- BEACON_S3_BUCKET = var.create_bucket ? aws_s3_bucket.this[0].bucket : data.aws_s3_bucket.existing[0].bucket- AWS_REGION = local.bucket_region+ BEACON_S3_BUCKET = aws_s3_bucket.this.bucket+ AWS_REGION = aws_s3_bucket.this.regionBEACON_S3_PREFIX = var.prefixBEACON_S3_STORAGE_CLASS = var.storage_class}@@ -79,3 +79,8 @@ output "beacon_reader_source_url" {description = "The location to give Beacon for the S3 data connector."value = local.beacon_reader_source_url}++output "beacon_reader_queue_urls" {+ description = "The new-object queues to give Beacon for the S3 data connector, by stream, when create_beacon_reader = true."+ value = var.create_beacon_reader ? { for stream, queue in aws_sqs_queue.beacon_reader : stream => queue.url } : null+}diff --git a/terraform/aws-s3/tests/module.tftest.hcl b/terraform/aws-s3/tests/module.tftest.hclindex 70370385..6c4852e5 100644--- a/terraform/aws-s3/tests/module.tftest.hcl+++ b/terraform/aws-s3/tests/module.tftest.hcl@@ -8,10 +8,9 @@ mock_provider "aws" {}}- mock_data "aws_s3_bucket" {+ mock_data "aws_caller_identity" {defaults = {- bucket = "acme-security-logs"- region = "eu-west-1"+ account_id = "111122223333"}}@@ -74,21 +73,21 @@ run "new_bucket_is_hardened" {assert {condition = (- aws_s3_bucket_public_access_block.this[0].block_public_acls- && aws_s3_bucket_public_access_block.this[0].block_public_policy- && aws_s3_bucket_public_access_block.this[0].ignore_public_acls- && aws_s3_bucket_public_access_block.this[0].restrict_public_buckets+ aws_s3_bucket_public_access_block.this.block_public_acls+ && aws_s3_bucket_public_access_block.this.block_public_policy+ && aws_s3_bucket_public_access_block.this.ignore_public_acls+ && aws_s3_bucket_public_access_block.this.restrict_public_buckets)error_message = "A new bucket must block all public access."}assert {- condition = one(aws_s3_bucket_ownership_controls.this[0].rule).object_ownership == "BucketOwnerEnforced"+ condition = one(aws_s3_bucket_ownership_controls.this.rule).object_ownership == "BucketOwnerEnforced"error_message = "A new bucket must disable ACLs."}assert {- condition = one(one(aws_s3_bucket_server_side_encryption_configuration.this[0].rule).apply_server_side_encryption_by_default).sse_algorithm == "AES256"+ condition = one(one(aws_s3_bucket_server_side_encryption_configuration.this.rule).apply_server_side_encryption_by_default).sse_algorithm == "AES256"error_message = "Without a KMS key the bucket defaults to SSE-S3."}@@ -98,12 +97,12 @@ run "new_bucket_is_hardened" {}assert {- condition = aws_s3_bucket.this[0].force_destroy == false+ condition = aws_s3_bucket.this.force_destroy == falseerror_message = "A bucket holding telemetry must not be force-destroyed by default."}assert {- condition = jsondecode(aws_s3_bucket_policy.this[0].policy).Statement == [+ condition = jsondecode(aws_s3_bucket_policy.this.policy).Statement == [{Sid = "DenyInsecureTransport"Effect = "Deny"@@ -117,17 +116,17 @@ run "new_bucket_is_hardened" {}assert {- condition = one(aws_s3_bucket_lifecycle_configuration.this[0].rule[0].filter).prefix == "beacon-prod/"+ condition = one(aws_s3_bucket_lifecycle_configuration.this.rule[0].filter).prefix == "beacon-prod/"error_message = "The lifecycle rule applies only to the Beacon prefix."}assert {- condition = length(aws_s3_bucket_lifecycle_configuration.this[0].rule[0].expiration) == 0+ condition = length(aws_s3_bucket_lifecycle_configuration.this.rule[0].expiration) == 0error_message = "Objects are kept forever unless expiration_days is set."}assert {- condition = one(aws_s3_bucket_lifecycle_configuration.this[0].rule[0].noncurrent_version_expiration).noncurrent_days == 30+ condition = one(aws_s3_bucket_lifecycle_configuration.this.rule[0].noncurrent_version_expiration).noncurrent_days == 30error_message = "Noncurrent versions expire after 30 days by default."}}@@ -164,36 +163,8 @@ run "source_url_uses_path_style_for_dotted_bucket_names" {}}-run "source_url_follows_the_partition" {- command = apply-- override_data {- target = data.aws_partition.current- values = {- partition = "aws-cn"- dns_suffix = "amazonaws.com.cn"- }- }-- variables {- create_bucket = false- bucket_name = "acme-security-logs"- existing_bucket_region = "cn-north-1"- }-- assert {- condition = output.beacon_reader_source_url == "https://acme-security-logs.s3.cn-north-1.amazonaws.com.cn/beacon-prod"- error_message = "The URL uses the partition's DNS suffix."- }-- assert {- condition = output.bucket_arn == "arn:aws-cn:s3:::acme-security-logs"- error_message = "The bucket ARN uses the partition."- }-}-run "kms_key_encrypts_and_is_granted" {- command = plan+ command = applyvariables {kms_key_arn = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"@@ -202,9 +173,9 @@ run "kms_key_encrypts_and_is_granted" {assert {condition = (- one(one(aws_s3_bucket_server_side_encryption_configuration.this[0].rule).apply_server_side_encryption_by_default).sse_algorithm == "aws:kms"- && one(one(aws_s3_bucket_server_side_encryption_configuration.this[0].rule).apply_server_side_encryption_by_default).kms_master_key_id == var.kms_key_arn- && one(aws_s3_bucket_server_side_encryption_configuration.this[0].rule).bucket_key_enabled+ one(one(aws_s3_bucket_server_side_encryption_configuration.this.rule).apply_server_side_encryption_by_default).sse_algorithm == "aws:kms"+ && one(one(aws_s3_bucket_server_side_encryption_configuration.this.rule).apply_server_side_encryption_by_default).kms_master_key_id == var.kms_key_arn+ && one(aws_s3_bucket_server_side_encryption_configuration.this.rule).bucket_key_enabled)error_message = "A KMS key becomes the bucket default, with an S3 Bucket Key."}@@ -244,7 +215,7 @@ run "healthcheck_permission_can_be_dropped" {}run "beacon_reader_reads_only_the_prefix" {- command = plan+ command = applyvariables {create_beacon_reader = true@@ -264,8 +235,20 @@ run "beacon_reader_reads_only_the_prefix" {Action = "s3:GetObject"Resource = "arn:aws:s3:::acme-beacon-telemetry/beacon-prod/*"},+ {+ Sid = "ConsumeBeaconNotifications"+ Effect = "Allow"+ Action = ["sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"]+ Resource = [aws_sqs_queue.beacon_reader["inventory"].arn, aws_sqs_queue.beacon_reader["runtime"].arn]+ },+ {+ Sid = "FindBeaconQueues"+ Effect = "Allow"+ Action = "sqs:ListQueues"+ Resource = "*"+ },]- error_message = "The Beacon reader may list the bucket and read only the Beacon prefix."+ error_message = "The Beacon reader may list the bucket, read only the Beacon prefix, and consume its two queues."}assert {@@ -274,80 +257,119 @@ run "beacon_reader_reads_only_the_prefix" {}}-run "access_keys_when_asked" {- command = plan-- variables {- create_beacon_reader = true- create_access_keys = true- }-- assert {- condition = length(aws_iam_access_key.writer) == 1 && length(aws_iam_access_key.beacon_reader) == 1- error_message = "create_access_keys creates one key per user."- }-}--run "existing_bucket_is_left_alone" {+run "beacon_reader_gets_new_object_queues" {command = applyvariables {- create_bucket = false- bucket_name = "acme-security-logs"+ create_beacon_reader = true}assert {condition = (- length(aws_s3_bucket.this) == 0- && length(aws_s3_bucket_policy.this) == 0- && length(aws_s3_bucket_public_access_block.this) == 0- && length(aws_s3_bucket_server_side_encryption_configuration.this) == 0- && length(aws_s3_bucket_versioning.this) == 0- && length(aws_s3_bucket_lifecycle_configuration.this) == 0- && length(aws_s3_bucket_ownership_controls.this) == 0+ aws_sqs_queue.beacon_reader["runtime"].name == "beacon-s3-reader-runtime"+ && aws_sqs_queue.beacon_reader["inventory"].name == "beacon-s3-reader-inventory"+ && aws_sqs_queue.beacon_reader_dead_letter["runtime"].name == "beacon-s3-reader-runtime-dlq"+ && aws_sqs_queue.beacon_reader_dead_letter["inventory"].name == "beacon-s3-reader-inventory-dlq")- error_message = "With create_bucket = false the module must not manage any bucket setting."+ error_message = "Each stream gets a queue and a dead-letter queue named after the reader."+ }++ assert {+ condition = alltrue([+ for stream in ["runtime", "inventory"] :+ aws_sqs_queue.beacon_reader[stream].sqs_managed_sse_enabled+ && aws_sqs_queue.beacon_reader[stream].message_retention_seconds == 1209600+ && aws_sqs_queue.beacon_reader[stream].visibility_timeout_seconds == 300+ && jsondecode(aws_sqs_queue.beacon_reader[stream].redrive_policy) == {+ deadLetterTargetArn = aws_sqs_queue.beacon_reader_dead_letter[stream].arn+ maxReceiveCount = 10+ }+ ])+ error_message = "Queues are encrypted, keep messages 14 days, and move a message to the dead-letter queue after ten failed deliveries."+ }++ assert {+ condition = alltrue([+ for stream in ["runtime", "inventory"] :+ jsondecode(aws_sqs_queue_policy.beacon_reader[stream].policy).Statement == [+ {+ Sid = "AllowBucketNotifications"+ Effect = "Allow"+ Principal = { Service = "s3.amazonaws.com" }+ Action = "sqs:SendMessage"+ Resource = aws_sqs_queue.beacon_reader[stream].arn+ Condition = {+ ArnEquals = { "aws:SourceArn" = "arn:aws:s3:::acme-beacon-telemetry" }+ StringEquals = { "aws:SourceAccount" = "111122223333" }+ }+ },+ ]+ ])+ error_message = "Only this bucket, in this account, may send to the queues."+ }++ assert {+ condition = {+ for queue in aws_s3_bucket_notification.this[0].queue : queue.filter_prefix => {+ arn = queue.queue_arn+ events = queue.events+ }+ } == {+ "beacon-prod/runtime/" = { arn = aws_sqs_queue.beacon_reader["runtime"].arn, events = toset(["s3:ObjectCreated:*"]) }+ "beacon-prod/inventory/" = { arn = aws_sqs_queue.beacon_reader["inventory"].arn, events = toset(["s3:ObjectCreated:*"]) }+ }+ error_message = "Every new object below each stream's prefix is announced on that stream's queue."}assert {- condition = output.forwarder_settings.AWS_REGION == "eu-west-1" && output.forwarder_settings.BEACON_S3_BUCKET == "acme-security-logs"- error_message = "An existing bucket's name and region come from the bucket itself."+ condition = output.beacon_reader_queue_urls == {+ runtime = aws_sqs_queue.beacon_reader["runtime"].url+ inventory = aws_sqs_queue.beacon_reader["inventory"].url+ }+ error_message = "beacon_reader_queue_urls gives the provisioning script's --queue-url values."}+}- assert {- condition = jsondecode(aws_iam_user_policy.writer.policy).Statement[0].Resource == "arn:aws:s3:::acme-security-logs/beacon-prod/*"- error_message = "The writer is scoped to the existing bucket's Beacon prefix."+run "queue_names_drop_characters_sqs_refuses" {+ command = plan++ variables {+ create_beacon_reader = true+ beacon_reader_user_name = "beacon.reader@acme"}assert {- condition = data.aws_s3_bucket.existing[0].region == "eu-west-1"- error_message = "Without existing_bucket_region the bucket is looked up in the provider's region."+ condition = aws_sqs_queue.beacon_reader["runtime"].name == "beacon-reader-acme-runtime"+ error_message = "IAM user names allow . and @, which SQS names do not."}}-run "existing_bucket_in_another_region" {- command = plan-- variables {- create_bucket = false- bucket_name = "acme-security-logs"- existing_bucket_region = "ap-southeast-2"- }+run "no_queues_without_the_reader" {+ command = applyassert {- condition = data.aws_s3_bucket.existing[0].region == "ap-southeast-2"- error_message = "existing_bucket_region is where the bucket is looked up, so the lookup works across regions."+ condition = (+ length(aws_sqs_queue.beacon_reader) == 0+ && length(aws_sqs_queue.beacon_reader_dead_letter) == 0+ && length(aws_s3_bucket_notification.this) == 0+ && output.beacon_reader_queue_urls == null+ )+ error_message = "Queues and the bucket notification exist only with the Beacon reader."}}-run "rejects_existing_bucket_region_for_a_new_bucket" {+run "access_keys_when_asked" {command = planvariables {- existing_bucket_region = "ap-southeast-2"+ create_beacon_reader = true+ create_access_keys = true}- expect_failures = [aws_s3_bucket.this]+ assert {+ condition = length(aws_iam_access_key.writer) == 1 && length(aws_iam_access_key.beacon_reader) == 1+ error_message = "create_access_keys creates one key per user."+ }}run "expiration_when_asked" {@@ -359,12 +381,12 @@ run "expiration_when_asked" {}assert {- condition = one(aws_s3_bucket_lifecycle_configuration.this[0].rule[0].expiration).days == 365+ condition = one(aws_s3_bucket_lifecycle_configuration.this.rule[0].expiration).days == 365error_message = "expiration_days expires current objects."}assert {- condition = length(aws_s3_bucket_versioning.this) == 0 && length(aws_s3_bucket_lifecycle_configuration.this[0].rule[0].noncurrent_version_expiration) == 0+ condition = length(aws_s3_bucket_versioning.this) == 0 && length(aws_s3_bucket_lifecycle_configuration.this.rule[0].noncurrent_version_expiration) == 0error_message = "Without versioning there is no versioning resource and no noncurrent rule."}}diff --git a/terraform/aws-s3/tests/partition.tftest.hcl b/terraform/aws-s3/tests/partition.tftest.hclnew file mode 100644index 00000000..ae90c39b--- /dev/null+++ b/terraform/aws-s3/tests/partition.tftest.hcl@@ -0,0 +1,41 @@+# The module builds ARNs and URLs from the partition, so it also works in AWS China and GovCloud.++mock_provider "aws" {+ mock_data "aws_partition" {+ defaults = {+ partition = "aws-cn"+ dns_suffix = "amazonaws.com.cn"+ }+ }++ mock_resource "aws_s3_bucket" {+ defaults = {+ bucket = "acme-beacon-telemetry"+ region = "cn-north-1"+ }+ }+}++variables {+ bucket_name = "acme-beacon-telemetry"+ prefix = "beacon-prod"+}++run "urls_and_arns_follow_the_partition" {+ command = apply++ assert {+ condition = output.beacon_reader_source_url == "https://acme-beacon-telemetry.s3.cn-north-1.amazonaws.com.cn/beacon-prod"+ error_message = "The data connector URL uses the partition's DNS suffix."+ }++ assert {+ condition = output.bucket_arn == "arn:aws-cn:s3:::acme-beacon-telemetry"+ error_message = "The bucket ARN uses the partition."+ }++ assert {+ condition = jsondecode(aws_iam_user_policy.writer.policy).Statement[0].Resource == "arn:aws-cn:s3:::acme-beacon-telemetry/beacon-prod/*"+ error_message = "The writer policy uses the partition."+ }+}diff --git a/terraform/aws-s3/variables.tf b/terraform/aws-s3/variables.tfindex 71a7b529..6691f57c 100644--- a/terraform/aws-s3/variables.tf+++ b/terraform/aws-s3/variables.tf@@ -1,5 +1,5 @@variable "bucket_name" {- description = "Name of the S3 bucket Beacon writes to. With create_bucket = true it must be globally unique."+ description = "Name of the dedicated S3 bucket the module creates for Beacon telemetry. Bucket names are global across AWS, so it must be unused."type = stringvalidation {@@ -8,23 +8,6 @@ variable "bucket_name" {}}-variable "create_bucket" {- description = "Create and harden the bucket. Set to false to use a bucket you already manage: the module then only creates the IAM users and changes nothing on the bucket."- type = bool- default = true-}--variable "existing_bucket_region" {- description = "Region of an existing bucket (create_bucket = false) when it is not the provider's region. Terraform cannot find a bucket in another region without it. A bucket the module creates is always in the provider's region, so leave this null then."- type = string- default = null-- validation {- condition = var.existing_bucket_region == null || can(regex("^[a-z]{2}(-[a-z]+)+-[0-9]+$", var.existing_bucket_region))- error_message = "existing_bucket_region must be an AWS region name such as us-west-2."- }-}-variable "prefix" {description = "Root prefix for Beacon objects, such as beacon-prod. Beacon adds runtime/ and inventory/ below it."type = string@@ -59,7 +42,7 @@ variable "storage_class" {}variable "kms_key_arn" {- description = "ARN of a customer managed KMS key. With create_bucket = true it becomes the bucket's default encryption (SSE-KMS with an S3 Bucket Key); with an existing bucket, set it to the key that bucket already uses. Either way the writer gets kms:GenerateDataKey and the Beacon reader gets kms:Decrypt on it. Leave null for SSE-S3."+ description = "ARN of a customer managed KMS key to make the bucket's default encryption (SSE-KMS with an S3 Bucket Key). The writer gets kms:GenerateDataKey and the Beacon reader gets kms:Decrypt on it. Leave null for SSE-S3."type = stringdefault = null@@ -70,13 +53,13 @@ variable "kms_key_arn" {}variable "versioning_enabled" {- description = "Turn on bucket versioning, so objects deleted or overwritten by an administrator can be recovered. Applies only when the module creates the bucket."+ description = "Turn on bucket versioning, so objects deleted or overwritten by an administrator can be recovered."type = booldefault = true}variable "expiration_days" {- description = "Delete Beacon objects this many days after upload. Leave null to keep them until you delete them. Applies only when the module creates the bucket."+ description = "Delete Beacon objects this many days after upload. Leave null to keep them until you delete them."type = numberdefault = null@@ -87,7 +70,7 @@ variable "expiration_days" {}variable "noncurrent_version_expiration_days" {- description = "With versioning on, delete replaced or deleted object versions this many days after they stop being current. Applies only when the module creates the bucket."+ description = "With versioning on, delete replaced or deleted object versions this many days after they stop being current."type = numberdefault = 30@@ -116,13 +99,13 @@ variable "allow_writer_healthcheck" {}variable "create_beacon_reader" {- description = "Create a read-only IAM user for Beacon Cloud's S3 data connector, which reads your bucket with an access key. It can read only the Beacon prefix."+ description = "Create a read-only IAM user for Beacon Cloud's S3 data connector, which reads your bucket with an access key. It can read only the Beacon prefix. The module also creates an SQS queue per stream, with a dead-letter queue, that S3 notifies of every new object, so the connector loads objects in any order."type = booldefault = false}variable "beacon_reader_user_name" {- description = "Name of the read-only IAM user created when create_beacon_reader = true."+ description = "Name of the read-only IAM user created when create_beacon_reader = true. Its queues are named after it: <name>-runtime and <name>-inventory, each with a -dlq."type = stringdefault = "beacon-s3-reader"}diff --git a/terraform/aws-s3/versions.tf b/terraform/aws-s3/versions.tfindex 70998f0a..b088b0f1 100644--- a/terraform/aws-s3/versions.tf+++ b/terraform/aws-s3/versions.tf@@ -4,7 +4,7 @@ terraform {required_providers {aws = {source = "hashicorp/aws"- version = ">= 6.0"+ version = ">= 5.0"}}}diff --git a/terraform/gcs/README.md b/terraform/gcs/README.mdindex 8e2c7fa6..b7ad66af 100644--- a/terraform/gcs/README.md+++ b/terraform/gcs/README.md@@ -2,13 +2,15 @@Creates the Google Cloud side of Beacon's GCS forwarding:-- a Cloud Storage bucket with uniform bucket-level access, public access prevention- enforced, versioning, optional CMEK (`kms_key_name`), and lifecycle rules scoped to- the Beacon prefix (skipped with `create_bucket = false`);+- a new, dedicated Cloud Storage bucket with uniform bucket-level access, public access+ prevention enforced, versioning, optional CMEK (`kms_key_name`), and lifecycle rules+ scoped to the Beacon prefix;- `beacon-endpoint-writer`, a service account with `roles/storage.objectCreator` onthe bucket, limited by an IAM condition to objects below the prefix;- optionally a read-only `beacon-endpoint-reader` (`create_reader = true`) and read- access for Beacon Cloud (`grant_beacon_read_access = true`).+ access for Beacon Cloud (`grant_beacon_read_access = true`), which also publishes+ every new object to Pub/Sub with a subscription per stream, so Beacon loads objects in+ any order.```hclprovider "google" {diff --git a/terraform/gcs/main.tf b/terraform/gcs/main.tfindex d62767f6..c2f5e845 100644--- a/terraform/gcs/main.tf+++ b/terraform/gcs/main.tf@@ -1,11 +1,15 @@locals {- apis = var.enable_apis ? toset(["storage.googleapis.com", "iam.googleapis.com"]) : toset([])-- bucket_name = var.create_bucket ? google_storage_bucket.this[0].name : var.bucket_name+ apis = var.enable_apis ? toset(concat(+ ["storage.googleapis.com", "iam.googleapis.com"],+ var.grant_beacon_read_access ? ["pubsub.googleapis.com"] : [],+ )) : toset([])# Beacon writes <prefix>/runtime/date=YYYY-MM-DD/... and <prefix>/inventory/date=YYYY-MM-DD/...# The condition is built from the variable, not the bucket resource, so it is known at plan time.writer_condition = "resource.name.startsWith(\"projects/_/buckets/${var.bucket_name}/objects/${var.prefix}/\")"++ # Cloud Storage's service agent encrypts with a customer-managed key and publishes notifications.+ needs_storage_agent = var.kms_key_name != null && var.grant_kms_to_storage_agent || var.grant_beacon_read_access}resource "google_project_service" "this" {@@ -17,25 +21,23 @@ resource "google_project_service" "this" {}data "google_storage_project_service_account" "this" {- count = var.create_bucket && var.kms_key_name != null && var.grant_kms_to_storage_agent ? 1 : 0+ count = local.needs_storage_agent ? 1 : 0project = var.projectdepends_on = [google_project_service.this]}-# Cloud Storage encrypts with a customer-managed key as its own service agent, not as the writer.resource "google_kms_crypto_key_iam_member" "storage_agent" {- count = length(data.google_storage_project_service_account.this)+ count = var.kms_key_name != null && var.grant_kms_to_storage_agent ? 1 : 0crypto_key_id = var.kms_key_namerole = "roles/cloudkms.cryptoKeyEncrypterDecrypter"member = "serviceAccount:${data.google_storage_project_service_account.this[0].email_address}"}+# A dedicated bucket for Beacon telemetry, always created by the module.resource "google_storage_bucket" "this" {- count = var.create_bucket ? 1 : 0-project = var.projectname = var.bucket_namelocation = var.location@@ -82,18 +84,11 @@ resource "google_storage_bucket" "this" {}}- lifecycle {- precondition {- condition = var.location != null- error_message = "location is required when create_bucket = true."- }- }-depends_on = [google_project_service.this, google_kms_crypto_key_iam_member.storage_agent]}# The identity every Mac's forwarder uses. roles/storage.objectCreator can create objects but not-# list, read, replace or delete them.+# list, read, replace or delete them, and the condition keeps it below the Beacon prefix.resource "google_service_account" "writer" {project = var.projectaccount_id = var.writer_account_id@@ -104,17 +99,14 @@ resource "google_service_account" "writer" {}resource "google_storage_bucket_iam_member" "writer" {- bucket = local.bucket_name+ bucket = google_storage_bucket.this.namerole = "roles/storage.objectCreator"member = "serviceAccount:${google_service_account.writer.email}"- dynamic "condition" {- for_each = var.scope_writer_to_prefix ? [local.writer_condition] : []- content {- title = "beacon-prefix-only"- description = "Create objects only below the Beacon prefix."- expression = condition.value- }+ condition {+ title = "beacon-prefix-only"+ description = "Create objects only below the Beacon prefix."+ expression = local.writer_condition}}@@ -138,7 +130,7 @@ resource "google_service_account" "reader" {resource "google_storage_bucket_iam_member" "reader" {count = var.create_reader ? 1 : 0- bucket = local.bucket_name+ bucket = google_storage_bucket.this.namerole = "roles/storage.objectViewer"member = "serviceAccount:${google_service_account.reader[0].email}"}@@ -146,7 +138,7 @@ resource "google_storage_bucket_iam_member" "reader" {resource "google_storage_bucket_iam_member" "beacon_reader" {count = var.grant_beacon_read_access ? 1 : 0- bucket = local.bucket_name+ bucket = google_storage_bucket.this.namerole = "roles/storage.objectViewer"member = var.beacon_reader_member}diff --git a/terraform/gcs/notifications.tf b/terraform/gcs/notifications.tfnew file mode 100644index 00000000..acad267d--- /dev/null+++ b/terraform/gcs/notifications.tf@@ -0,0 +1,70 @@+# Beacon Cloud's ClickPipes read the bucket in "any order" mode: Cloud Storage announces every new+# object on Pub/Sub, and the pipe loads what its subscription names. Without them a pipe lists+# objects in name order and skips any that sort before ones it has already loaded, which happens+# whenever Macs upload out of step. The subscriptions match the ones Beacon's managed ingest uses.++locals {+ reader_streams = var.grant_beacon_read_access ? toset(["runtime", "inventory"]) : toset([])+}++resource "google_pubsub_topic" "beacon_reader" {+ count = var.grant_beacon_read_access ? 1 : 0++ project = var.project+ name = "beacon-${var.bucket_name}-objects"+ labels = var.labels++ depends_on = [google_project_service.this]+}++resource "google_pubsub_topic_iam_member" "storage_agent" {+ count = var.grant_beacon_read_access ? 1 : 0++ project = var.project+ topic = google_pubsub_topic.beacon_reader[0].name+ role = "roles/pubsub.publisher"+ member = "serviceAccount:${data.google_storage_project_service_account.this[0].email_address}"+}++resource "google_storage_notification" "beacon_reader" {+ count = var.grant_beacon_read_access ? 1 : 0++ bucket = google_storage_bucket.this.name+ topic = google_pubsub_topic.beacon_reader[0].id+ payload_format = "JSON_API_V1"+ event_types = ["OBJECT_FINALIZE"]+ object_name_prefix = "${var.prefix}/"++ # Cloud Storage checks that it may publish to the topic when the notification is created.+ depends_on = [google_pubsub_topic_iam_member.storage_agent]+}++resource "google_pubsub_subscription" "beacon_reader" {+ for_each = local.reader_streams++ project = var.project+ name = "beacon-${var.bucket_name}-${each.key}"+ topic = google_pubsub_topic.beacon_reader[0].id+ filter = "attributes.eventType = \"OBJECT_FINALIZE\" AND hasPrefix(attributes.objectId, \"${var.prefix}/${each.key}/\")"+ ack_deadline_seconds = 60+ message_retention_duration = "604800s"+ labels = var.labels++ # An empty TTL never expires the subscription. The default expires it after 31 quiet days,+ # which would silently stop ingestion from a fleet that was offline for a month.+ expiration_policy {+ ttl = ""+ }+}++resource "google_pubsub_subscription_iam_member" "beacon_reader" {+ for_each = {+ for pair in setproduct(local.reader_streams, ["roles/pubsub.subscriber", "roles/pubsub.viewer"]) :+ "${pair[0]}:${pair[1]}" => { stream = pair[0], role = pair[1] }+ }++ project = var.project+ subscription = google_pubsub_subscription.beacon_reader[each.value.stream].name+ role = each.value.role+ member = var.beacon_reader_member+}diff --git a/terraform/gcs/outputs.tf b/terraform/gcs/outputs.tfindex ead15f6b..948f345c 100644--- a/terraform/gcs/outputs.tf+++ b/terraform/gcs/outputs.tf@@ -1,11 +1,11 @@output "bucket_name" {description = "Bucket Beacon writes to."- value = local.bucket_name+ value = google_storage_bucket.this.name}output "bucket_url" {description = "gs:// URL of the Beacon prefix."- value = "gs://${local.bucket_name}/${var.prefix}/"+ value = "gs://${google_storage_bucket.this.name}/${var.prefix}/"}output "prefix" {@@ -21,7 +21,7 @@ output "storage_class" {output "forwarder_settings" {description = "The non-secret settings Beacon's GCS forwarder helper reads, keyed by environment variable name. The helper also needs GOOGLE_APPLICATION_CREDENTIALS, the path of the writer's key file on the Mac."value = {- BEACON_GCS_BUCKET = local.bucket_name+ BEACON_GCS_BUCKET = google_storage_bucket.this.nameBEACON_GCS_PREFIX = var.prefixBEACON_GCS_STORAGE_CLASS = var.storage_class}@@ -42,3 +42,8 @@ output "reader_email" {description = "Read-only service account, when create_reader = true."value = try(google_service_account.reader[0].email, null)}++output "beacon_reader_subscriptions" {+ description = "The new-object subscriptions to give Beacon, by stream, when grant_beacon_read_access = true."+ value = var.grant_beacon_read_access ? { for stream, sub in google_pubsub_subscription.beacon_reader : stream => sub.id } : null+}diff --git a/terraform/gcs/tests/module.tftest.hcl b/terraform/gcs/tests/module.tftest.hclindex 5e284049..eaa448ce 100644--- a/terraform/gcs/tests/module.tftest.hcl+++ b/terraform/gcs/tests/module.tftest.hcl@@ -14,6 +14,12 @@ mock_provider "google" {}}+ mock_resource "google_pubsub_topic" {+ defaults = {+ id = "projects/acme-security/topics/beacon-acme-beacon-telemetry-objects"+ }+ }+mock_data "google_storage_project_service_account" {defaults = {email_address = "[email protected]"@@ -66,26 +72,26 @@ run "new_bucket_is_hardened" {assert {condition = (- google_storage_bucket.this[0].uniform_bucket_level_access- && google_storage_bucket.this[0].public_access_prevention == "enforced"- && google_storage_bucket.this[0].force_destroy == false- && one(google_storage_bucket.this[0].versioning).enabled- && google_storage_bucket.this[0].location == "us-west1"- && google_storage_bucket.this[0].storage_class == "STANDARD"+ google_storage_bucket.this.uniform_bucket_level_access+ && google_storage_bucket.this.public_access_prevention == "enforced"+ && google_storage_bucket.this.force_destroy == false+ && one(google_storage_bucket.this.versioning).enabled+ && google_storage_bucket.this.location == "us-west1"+ && google_storage_bucket.this.storage_class == "STANDARD")error_message = "A new bucket uses uniform access, enforced public access prevention and versioning."}assert {- condition = length(google_storage_bucket.this[0].encryption) == 0+ condition = length(google_storage_bucket.this.encryption) == 0error_message = "Without a KMS key the bucket uses Google-managed encryption."}assert {condition = (- length(google_storage_bucket.this[0].lifecycle_rule) == 1- && one(google_storage_bucket.this[0].lifecycle_rule[0].condition).days_since_noncurrent_time == 30- && one(google_storage_bucket.this[0].lifecycle_rule[0].condition).matches_prefix == tolist(["beacon-prod/"])+ length(google_storage_bucket.this.lifecycle_rule) == 1+ && one(google_storage_bucket.this.lifecycle_rule[0].condition).days_since_noncurrent_time == 30+ && one(google_storage_bucket.this.lifecycle_rule[0].condition).matches_prefix == tolist(["beacon-prod/"]))error_message = "By default only noncurrent versions below the prefix expire, after 30 days."}@@ -137,58 +143,103 @@ run "beacon_read_access_when_asked" {}}-run "kms_key_encrypts_and_is_granted_to_the_storage_agent" {- command = plan+run "beacon_read_access_brings_new_object_subscriptions" {+ command = applyvariables {- kms_key_name = "projects/acme-security/locations/us-west1/keyRings/beacon/cryptoKeys/telemetry"+ grant_beacon_read_access = true}assert {- condition = one(google_storage_bucket.this[0].encryption).default_kms_key_name == var.kms_key_name- error_message = "The key becomes the bucket's default encryption."+ condition = (+ google_pubsub_topic.beacon_reader[0].name == "beacon-acme-beacon-telemetry-objects"+ && google_pubsub_topic_iam_member.storage_agent[0].role == "roles/pubsub.publisher"+ && google_pubsub_topic_iam_member.storage_agent[0].member == "serviceAccount:[email protected]"+ )+ error_message = "Cloud Storage's service agent publishes new-object notifications to a topic for this bucket."}assert {condition = (- google_kms_crypto_key_iam_member.storage_agent[0].crypto_key_id == var.kms_key_name- && google_kms_crypto_key_iam_member.storage_agent[0].role == "roles/cloudkms.cryptoKeyEncrypterDecrypter"- && google_kms_crypto_key_iam_member.storage_agent[0].member == "serviceAccount:[email protected]"+ google_storage_notification.beacon_reader[0].event_types == toset(["OBJECT_FINALIZE"])+ && google_storage_notification.beacon_reader[0].object_name_prefix == "beacon-prod/"+ && google_storage_notification.beacon_reader[0].payload_format == "JSON_API_V1")- error_message = "Cloud Storage's service agent must be able to use the key."+ error_message = "Every new object below the prefix is announced."}-}-run "existing_bucket_is_left_alone" {- command = apply+ assert {+ condition = alltrue([+ for stream in ["runtime", "inventory"] :+ google_pubsub_subscription.beacon_reader[stream].name == "beacon-acme-beacon-telemetry-${stream}"+ && google_pubsub_subscription.beacon_reader[stream].filter == "attributes.eventType = \"OBJECT_FINALIZE\" AND hasPrefix(attributes.objectId, \"beacon-prod/${stream}/\")"+ && google_pubsub_subscription.beacon_reader[stream].ack_deadline_seconds == 60+ && google_pubsub_subscription.beacon_reader[stream].message_retention_duration == "604800s"+ && one(google_pubsub_subscription.beacon_reader[stream].expiration_policy).ttl == ""+ ])+ error_message = "Each stream has a never-expiring subscription filtered to its prefix, with the managed path's settings."+ }- variables {- create_bucket = false- bucket_name = "acme-security-logs"- location = null+ assert {+ condition = toset([+ for binding in google_pubsub_subscription_iam_member.beacon_reader : "${binding.subscription}|${binding.role}|${binding.member}"+ ]) == toset(flatten([+ for stream in ["runtime", "inventory"] : [+ for role in ["roles/pubsub.subscriber", "roles/pubsub.viewer"] :+ "${google_pubsub_subscription.beacon_reader[stream].name}|${role}|serviceAccount:[email protected]"+ ]+ ]))+ error_message = "Beacon's reader may consume and view both subscriptions, and nothing else gets access."+ }++ assert {+ condition = output.beacon_reader_subscriptions == {+ runtime = google_pubsub_subscription.beacon_reader["runtime"].id+ inventory = google_pubsub_subscription.beacon_reader["inventory"].id+ }+ error_message = "beacon_reader_subscriptions gives the provisioning script's --queue-url values."}assert {- condition = length(google_storage_bucket.this) == 0 && length(google_kms_crypto_key_iam_member.storage_agent) == 0- error_message = "With create_bucket = false the module must not manage the bucket."+ condition = contains(keys(google_project_service.this), "pubsub.googleapis.com")+ error_message = "Pub/Sub is enabled when Beacon reads the bucket."}+}++run "no_pubsub_without_beacon_read_access" {+ command = applyassert {- condition = google_storage_bucket_iam_member.writer.bucket == "acme-security-logs" && output.forwarder_settings.BEACON_GCS_BUCKET == "acme-security-logs"- error_message = "The writer is bound on the existing bucket."+ condition = (+ length(google_pubsub_topic.beacon_reader) == 0+ && length(google_storage_notification.beacon_reader) == 0+ && length(google_pubsub_subscription.beacon_reader) == 0+ && output.beacon_reader_subscriptions == null+ && !contains(keys(google_project_service.this), "pubsub.googleapis.com")+ )+ error_message = "The topic, notification and subscriptions exist only with Beacon read access."}}-run "unscoped_writer_when_asked" {+run "kms_key_encrypts_and_is_granted_to_the_storage_agent" {command = planvariables {- scope_writer_to_prefix = false+ kms_key_name = "projects/acme-security/locations/us-west1/keyRings/beacon/cryptoKeys/telemetry"}assert {- condition = length(google_storage_bucket_iam_member.writer.condition) == 0- error_message = "scope_writer_to_prefix = false drops the IAM condition."+ condition = one(google_storage_bucket.this.encryption).default_kms_key_name == var.kms_key_name+ error_message = "The key becomes the bucket's default encryption."+ }++ assert {+ condition = (+ google_kms_crypto_key_iam_member.storage_agent[0].crypto_key_id == var.kms_key_name+ && google_kms_crypto_key_iam_member.storage_agent[0].role == "roles/cloudkms.cryptoKeyEncrypterDecrypter"+ && google_kms_crypto_key_iam_member.storage_agent[0].member == "serviceAccount:[email protected]"+ )+ error_message = "Cloud Storage's service agent must be able to use the key."}}@@ -202,9 +253,9 @@ run "expiration_when_asked" {assert {condition = (- length(google_storage_bucket.this[0].lifecycle_rule) == 1- && one(google_storage_bucket.this[0].lifecycle_rule[0].condition).age == 365- && one(google_storage_bucket.this[0].lifecycle_rule[0].condition).matches_prefix == tolist(["beacon-prod/"])+ length(google_storage_bucket.this.lifecycle_rule) == 1+ && one(google_storage_bucket.this.lifecycle_rule[0].condition).age == 365+ && one(google_storage_bucket.this.lifecycle_rule[0].condition).matches_prefix == tolist(["beacon-prod/"]))error_message = "expiration_days deletes objects below the prefix, and no noncurrent rule exists without versioning."}@@ -223,16 +274,6 @@ run "key_when_asked" {}}-run "location_required_for_a_new_bucket" {- command = plan-- variables {- location = null- }-- expect_failures = [google_storage_bucket.this]-}-run "rejects_stream_suffix_prefix" {command = plandiff --git a/terraform/gcs/variables.tf b/terraform/gcs/variables.tfindex 235a80bb..119a226f 100644--- a/terraform/gcs/variables.tf+++ b/terraform/gcs/variables.tf@@ -4,7 +4,7 @@ variable "project" {}variable "bucket_name" {- description = "Name of the Cloud Storage bucket Beacon writes to. With create_bucket = true it must be globally unique."+ description = "Name of the dedicated Cloud Storage bucket the module creates for Beacon telemetry. Bucket names are global across Google Cloud, so it must be unused."type = stringvalidation {@@ -13,16 +13,9 @@ variable "bucket_name" {}}-variable "create_bucket" {- description = "Create and harden the bucket. Set to false to use a bucket you already manage: the module then only creates the service account and its bucket IAM bindings."- type = bool- default = true-}-variable "location" {- description = "Bucket location, such as us-west1 or US. Required when create_bucket = true."+ description = "Bucket location, such as us-west1 or US."type = string- default = null}variable "prefix" {@@ -40,7 +33,7 @@ variable "prefix" {}variable "storage_class" {- description = "Storage class the forwarder writes objects with (BEACON_GCS_STORAGE_CLASS), and the default class of a bucket the module creates."+ description = "Storage class the forwarder writes objects with (BEACON_GCS_STORAGE_CLASS), and the bucket's default class."type = stringdefault = "STANDARD"@@ -51,7 +44,7 @@ variable "storage_class" {}variable "kms_key_name" {- description = "Cloud KMS key (projects/<p>/locations/<l>/keyRings/<r>/cryptoKeys/<k>) to use as the default encryption of a bucket the module creates. Leave null for Google-managed encryption."+ description = "Cloud KMS key (projects/<p>/locations/<l>/keyRings/<r>/cryptoKeys/<k>) to use as the bucket's default encryption. Leave null for Google-managed encryption."type = stringdefault = null@@ -68,13 +61,13 @@ variable "grant_kms_to_storage_agent" {}variable "versioning_enabled" {- description = "Turn on object versioning, so objects deleted or replaced by an administrator can be recovered. Applies only when the module creates the bucket."+ description = "Turn on object versioning, so objects deleted or replaced by an administrator can be recovered."type = booldefault = true}variable "expiration_days" {- description = "Delete Beacon objects this many days after upload. Leave null to keep them until you delete them. Applies only when the module creates the bucket."+ description = "Delete Beacon objects this many days after upload. Leave null to keep them until you delete them."type = numberdefault = null@@ -85,7 +78,7 @@ variable "expiration_days" {}variable "noncurrent_version_expiration_days" {- description = "With versioning on, delete replaced or deleted object versions this many days after they stop being current. Applies only when the module creates the bucket."+ description = "With versioning on, delete replaced or deleted object versions this many days after they stop being current."type = numberdefault = 30@@ -102,7 +95,7 @@ variable "force_destroy" {}variable "enable_apis" {- description = "Enable the Cloud Storage and IAM APIs on the project. They are left enabled when the module is destroyed."+ description = "Enable the Cloud Storage and IAM APIs on the project, and Pub/Sub when grant_beacon_read_access = true. They are left enabled when the module is destroyed."type = booldefault = true}@@ -113,12 +106,6 @@ variable "writer_account_id" {default = "beacon-endpoint-writer"}-variable "scope_writer_to_prefix" {- description = "Limit the writer to creating objects below the Beacon prefix with an IAM condition. Conditions need uniform bucket-level access, which a bucket the module creates always has; set to false only for an existing bucket that still uses fine-grained ACLs."- type = bool- default = true-}-variable "create_writer_key" {description = "Also create a JSON key for the writer. The private key is then stored in Terraform state, so leave this false unless your state is encrypted and access-controlled, and create the key with gcloud instead."type = bool@@ -138,7 +125,7 @@ variable "reader_account_id" {}variable "grant_beacon_read_access" {- description = "Grant Beacon Cloud read access to the bucket (roles/storage.objectViewer for beacon_reader_member), so Beacon can ingest the telemetry you store there. No key is involved."+ description = "Grant Beacon Cloud read access to the bucket (roles/storage.objectViewer for beacon_reader_member), so Beacon can ingest the telemetry you store there. No key is involved. The module also publishes every new object to a Pub/Sub topic with one subscription per stream that Beacon's reader may consume, so Beacon loads objects in any order."type = booldefault = false}@@ -150,7 +137,7 @@ variable "beacon_reader_member" {}variable "labels" {- description = "Labels to apply to a bucket the module creates."+ description = "Labels to apply to the bucket, and to the Pub/Sub topic and subscriptions when they exist."type = map(string)default = {}}