Skip to content
brix.v2.15.0+b120c49

Search documentation

Loading search…

    Documentation menu
    Docs / Server configuration / Environment and secretsRead Markdown
    On this page

    Secrets and deployment snapshots

    Resolve trusted secret-provider references for CI steps or publish immutable AWS environment snapshots.

    You need a valid environment schema and access to its secret providers. CI export needs no AWS credentials. Upload additionally needs permission to write the application's stage secret in the intended AWS account and region; it writes a new version, not a local preview or part of brix build.

    Resolve 1Password references

    #

    Brix bundles its pinned Varlock 1Password plugin. Register it in the schema header:

    # @plugin(brix)
    # @initOp(token=$OP_SERVICE_ACCOUNT_TOKEN, allowAppAuth=true)
    # @currentEnv=$VARLOCK_ENV
    # @generateTsTypes(path=../src/env.generated.d.ts, auto=false, exposeEnv=none, processEnv=none, importMetaEnv=none)
    # ---
    
    # @type=opServiceAccountToken @sensitive @internal @required=false
    OP_SERVICE_ACCOUNT_TOKEN=
    
    # @type=string @sensitive @required
    CATALOG_TOKEN=op("op://Storefront/Production/token")
    

    No application plugin install is needed. Locally, authenticate the 1Password CLI with desktop app integration; allowAppAuth=true permits that fallback when no token is set. In trusted CI, provide a vault-scoped OP_SERVICE_ACCOUNT_TOKEN; it takes precedence. Declare the token @internal so it never enters application types or snapshots. Plugins and imported schemas are executable trusted configuration, so never resolve providers in untrusted fork jobs.

    Export to subsequent GitHub Actions steps

    #

    Use brix env export production --target github when later steps need configuration but no AWS snapshot. For just one command, prefer brix env run production --no-local -- run deploy to keep resolved values scoped to that command.

    Declare the keys in env/.env.schema, then select which may cross step boundaries in package.json:

    {
      "brix": {
        "project": "application",
        "env": {
          "ciExports": {
            "literals": ["PORT"],
            "secrets": ["DEPLOY_TOKEN"]
          }
        }
      }
    }
    

    PORT must be non-sensitive and DEPLOY_TOKEN sensitive. Both lists default to empty; STAGE is always exported and must not be listed. Missing, internal, duplicate, overlapping, wildcard, control-variable, and sensitivity-mismatched entries fail. No secretsPrefix is needed.

    After checkout and Brix installation, run this only in a trusted job:

    - name: Export deployment configuration
      run: brix env export production --target github
      env:
        OP_SERVICE_ACCOUNT_TOKEN: ${{ secrets.OP_SERVICE_ACCOUNT_TOKEN }}
    
    - name: Deploy
      run: brix run deploy
    

    Export validates the complete schema/base/stage environment, even values outside the allowlist. Local and personal overrides are excluded. An ambient process value for an application key fails the export unless you consent with repeatable --allow-override KEY; internal provider authentication such as OP_SERVICE_ACCOUNT_TOKEN is allowed. Types refresh automatically. All sensitive application values are masked before writing STAGE and allowlisted values to GITHUB_ENV. GitHub matches masks within single log lines, so each line of a multiline value is also masked separately; the exported value keeps its line breaks. Resolution or policy failure exports nothing and does not print provider output. Do not continue deployment after a failed export.

    Only the GitHub target is supported. Export requires GitHub Actions and an existing absolute GITHUB_ENV file; outside Actions it fails rather than printing secrets. It cannot run inside an injected brix env run. In a workspace, use brix env#booking export production --target github. It neither uploads a runtime snapshot nor sets SECRETS_ARN or SECRETS_VERSION.

    These are job environment variables, not action outputs. Every subsequent step can read them; masking protects logs, not access. Keep the allowlist narrow. Ordinary brix run and brix exec inherit the approved values without loading providers again. Do not wrap those later steps in brix env run unless you deliberately want to resolve a full environment again.

    Exported values are not a resolved Brix environment. A later script that calls loadEnv() from #brix/env/script fails with "No validated environment is available" after export alone. Such a script should read its exported keys from process.env, or run under brix env run to resolve the full environment again.

    Upload an immutable AWS snapshot

    #

    Before uploading, configure AWS authentication and region for a trusted deployment identity with permission to create or update the intended Secrets Manager secret. Provider authentication and AWS upload authentication are separate: a 1Password token does not grant AWS access. The deployed workload needs read access to its exact secret version, not the uploader's write credentials.

    Configure a stable secret prefix and the narrow CI export allowlist in package.json:

    {
      "brix": {
        "project": "application",
        "env": {
          "secretsPrefix": "booking",
          "ciExports": {
            "literals": ["PORT"],
            "secrets": ["DEPLOY_TOKEN"]
          }
        }
      }
    }
    

    secretsPrefix is required for upload. It starts with a lowercase letter or digit and contains only lowercase letters, digits, and hyphens. Each stage writes the Secrets Manager secret <secretsPrefix>-secrets-<stage>, so this example writes booking-secrets-production. The ciExports rules are the same as for CI export.

    Run upload only in a protected deployment job:

    brix env upload production --account 123456789012 --region eu-west-1 \
      --request-token "$PERSISTED_REQUEST_TOKEN" --json
    

    --account takes the 12-digit AWS account ID and --region an explicit region such as eu-west-1; both are mandatory, and ambient AWS region or endpoint settings never select the write target. Credentials are resolved once for STS and the write, the caller's account is checked before mutation, and the returned ARN and version are checked against the requested target. Regions in every AWS partition are accepted, including GovCloud, China, ISO, and European Sovereign Cloud regions such as us-gov-west-1 or eusc-de-east-1. Both are validated before any provider resolves the stage's secrets.

    To upload to a local AWS emulator such as LocalStack or Floci during development, pass its loopback address with --endpoint-url and the emulator's fixed account:

    brix env upload development --account 000000000000 --region us-east-1 \
      --endpoint-url http://127.0.0.1:4566
    

    --endpoint-url accepts only a loopback http or https origin (localhost, 127.0.0.1, or [::1]) without a path or credentials, and only with account 000000000000. The same endpoint serves the STS account check and the Secrets Manager write. Because some emulators, such as Floci, ignore the request token when creating a secret, Brix creates the secret without a value and always writes the snapshot with PutSecretValue and the token. AWS_ENDPOINT_URL and service-specific endpoint variables stay ignored, so an ambient setting cannot redirect a real upload. Runtimes that read the snapshot use the AWS SDK's standard configuration, so point a local runtime at the emulator with AWS_ENDPOINT_URL.

    Secrets Manager stores at most 65,536 bytes per secret value. Preparation measures the serialized snapshot (every non-internal literal and secret) and fails before any AWS call, reporting only the size, when it is larger. Keep large certificates or JSON documents out of the snapshot, for example by storing them in their own secret or object and referencing that location.

    The request token is the idempotency key and becomes the new secret version's ID. Persist it before mutation. A token contains 32–64 letters, digits, or hyphens; a UUID qualifies. An invalid token fails before it is printed or any AWS call is made. When omitted, Brix generates one. The token is always printed to stderr; --json prints only the receipt to stdout:

    {
      "format": "brix-env-upload-v1",
      "accountId": "123456789012",
      "region": "eu-west-1",
      "stage": "production",
      "name": "booking-secrets-production",
      "arn": "arn:aws:secretsmanager:eu-west-1:123456789012:secret:booking-secrets-production-AbCdEf",
      "versionId": "3f6c1a52-8d0e-4f7b-9a41-2c5e7d9b0a18"
    }
    

    For recoverable automation, supply your persisted token rather than capturing a generated one from stderr.

    Upload rejects injected snapshot context and ambient application keys unless explicitly consented with repeatable --allow-override KEY. Internal provider authentication is allowed. Remove accidental application values from the uploader environment rather than broadly allowing them. Local files remain excluded. Existing upload scripts must add account/region and review any ambient overrides.

    Upload selects schema, base, and stage files, excluding local and personal overrides. It validates the complete environment, checks sensitivity, masks sensitive values in GitHub Actions, and writes a new version of <prefix>-secrets-<stage> containing a complete brix-env-v1 JSON snapshot. This is replacement of the value set, not a merge: removed application keys disappear from the new snapshot. Unlisted values remain in the AWS snapshot but do not cross into later CI steps.

    Brix exports only STAGE, allowlisted values, SECRETS_ARN, and exact SECRETS_VERSION to GITHUB_ENV when running in GitHub Actions. There are no cross-step exports outside Actions. Masking is log redaction, not access control; every later step in that job can read exports. Later steps in the same job that resolve a stage (brix env run, brix dev, brix build --stage, or brix test --env) fail while the exported pair is set, because loadEnv() would read the uploaded snapshot instead of the selected stage. Unset both in those steps or run them in a separate job; see environment loading.

    Project-owned multi-application scripts should use Node-only prepareEnvUpload and uploadAwsEnvSnapshot from brix/env/upload, not sequential CLI uploads. Prepare every application before any write, retain opaque handles in-process, and persist tokens/receipts. Preparation resolves schema/base/stage once without mutating process.env; declared non-sensitive bindings supply resource identifiers, and overrides names explicitly permitted ambient application keys. The API does not export CI variables; ciExports/GITHUB_ENV export is a CLI adapter only. Both API and CLI mask sensitive snapshot values in GitHub Actions before AWS calls. See Terraform-first deployment for the two-pass example.

    Deploy the ARN/version pair and workload identity. The runtime reads the Secrets Manager region from the ARN; AWS_REGION is used only when SECRETS_ARN is a secret name rather than an ARN, and loading fails when neither supplies a region. Node and Lambda runtimes, and script loadEnv(), fetch that immutable version once per process and reuse the deeply frozen snapshot for each request's inert createEnv parser. Concurrent first requests share one fetch, and a failed fetch is retried by the next request rather than cached. Changing SECRETS_ARN or SECRETS_VERSION requires a new deployment, which starts new processes. Both identifiers are required together; malformed snapshots and provider failures do not fall back to process values. Production needs no Varlock files or provider credentials in its runtime artifact.

    Application schema constraints are enforced before upload. Runtime parsing checks the snapshot format, JSON values, and control-key safety, not the generated application type. Keep the snapshot and code/schema revision together in deployment records, and restrict who can write the secret.

    Rotate and recover deliberately

    #

    A provider change is not live until a new snapshot is uploaded and its exact version is bound to a deployment. Literal configuration changes require the same workflow as secret changes. Verify the new runtime before revoking old credentials.

    Rollback requires the previous code, assets, and ARN/version pair. Keep all required secret versions for that window: AWS can remove old unlabeled versions, so retention labels and cleanup are owned by your infrastructure. Do not switch to AWSCURRENT to work around a missing version. Restore an approved snapshot or deploy a newly validated one deliberately.

    Upload preserves AWS's default staging-label behavior: a new version can move AWSCURRENT and AWSPREVIOUS. Those labels are not Brix traffic controls or a sufficient rollback-retention policy. Workloads must use the exact returned ARN/version pair.

    If upload fails, do not continue deployment with stale exports. Brix withholds Varlock output and AWS error details because they can contain resolved values; the failure message reports only the request token and whether a write was attempted. When it says the write may have succeeded, a network failure may have left the outcome uncertain: check whether the secret has a version whose ID equals that token before retrying. To diagnose a provider failure, run a harmless command under brix env run <stage> --no-local -- … in a trusted shell; that path shows Varlock's own validation diagnostics. Brix does not activate application code or roll back cloud resources for you.

    Retry only with the same persisted token and bytes; do not blindly create another token or resolve changed provider values for an uncertain write. Upload returns an exact receipt, not health or activation evidence, and performs no mandatory readback, retention, or promotion. Retention must cover pending deployments as well as active and rollback versions.

    Cloudflare and Fastly use the same snapshot format, but brix env upload is AWS-only. Their deployment workflows must publish the snapshot and configure the bindings described in worker deployment.

    After publication, record the exact snapshot version beside the code and assets, then follow the appropriate deployment guide. Do not treat a successful upload as activation.