Docs

Encrypt your data with a key in each customer's KMS

This example builds customer-managed keys for a hosted product: every encryption goes through a key in the customer's own AWS KMS, Google Cloud KMS, or Azure Key Vault. If Customer 1 disables the key, your backend can no longer decrypt their data.

Architecture diagram. Left: Your cloud containing Your backend, @alienplatform/bindings, Database: ciphertext only. Right: Customer 1's cloud account containing customer-keys deployment containing customer-key (KMS).

Your backend calls the customer's KMS with short-lived credentials. The key never leaves their account.

What you build:

  • A key in each customer's key service, created once during their initial setup (the one-time step their admin runs with their own credentials), plus a role that can only encrypt and decrypt with it.
  • Backend code that encrypts and decrypts through one API on all three clouds, with short-lived credentials.
  • Envelope encryption for records, and a test of the customer's kill switch.

No compute runs in the customer's cloud. Your backend keeps its database and storage. Source: examples/customer-keys-ts.

Buyers call this "bring your own key" (BYOK) or "customer-managed keys". Their security team wants a kill switch they operate themselves, with an audit log in their own cloud, without running your software. The usual ways to build it both cost you:

  • A pasted credential. The customer creates an IAM user or service account key with KMS access and pastes it into your settings. You hold a long-lived credential per customer and write a client per key service.
  • A key policy for your account. The customer grants your AWS account access to their key. That works only on AWS, only for customers who can write the policy.

The key

alien.ts
import * as alien from "@alienplatform/core"

const customerKey = new alien.Key("customer-key").build()

export default new alien.Stack("customer-keys")
  .add(customerKey, "frozen", { remoteAccess: true })
  .build()

alien.Key is a customer-managed key in the cloud's key service. It has no options to tune.

The key is "frozen" (created at initial setup, never replaced by a release) because it belongs to the customer. The customer's admin creates it at initial setup with their own credentials, and only initial setup can create or delete it.

A release from you can never replace the key, which matters: a replaced key would make every ciphertext stored under the old one unreadable. See Frozen and live.

{ remoteAccess: true } publishes the key to your backend. The initial setup creates a separate cloud identity for remote bindings in the customer's account and grants it encrypt and decrypt on this one key:

CloudKey serviceRemote role permissions
AWSAWS KMSkms:Encrypt, kms:Decrypt on the key
Google CloudCloud KMSroles/cloudkms.cryptoKeyEncrypterDecrypter on the key
AzureKey Vaultkeys/encrypt/action, keys/decrypt/action on the key

The role can't read key material, change the key policy, or schedule deletion. The key material never leaves the key service.

A remotely published Key must be the only remoteAccess resource in its stack. Every published resource shares one remote role, so a credential for one would carry the permissions of all of them. Alien refuses to deploy a stack that breaks this rule.

If you need customer storage too, put it in its own stack, as in Customer storage.

The stack doesn't call .platforms(...), so the release supports every platform the Key resource supports: AWS, Google Cloud, and Azure.

Encrypt and decrypt

src/vendor.ts is the backend side. It runs wherever your product runs, not in the customer's cloud:

src/vendor.ts
import { Bindings } from "@alienplatform/bindings"

function requiredEnvironmentVariable(name: string): string {
  const value = process.env[name]
  if (!value) throw new Error(`${name} is required`)
  return value
}

const bindings = await Bindings.forRemoteDeployment({
  deploymentId: requiredEnvironmentVariable("ALIEN_DEPLOYMENT_ID"),
  token: requiredEnvironmentVariable("ALIEN_API_TOKEN"),
})

const key = bindings.key("customer-key")
const context = { tenant: requiredEnvironmentVariable("CUSTOMER_ID") }
const plaintext = new TextEncoder().encode("customer data")
const ciphertext = await key.encrypt(plaintext, { context })
const decrypted = await key.decrypt(ciphertext, { context })

console.log({
  ciphertext: ciphertext.toString("base64"),
  decrypted: new TextDecoder().decode(decrypted),
})
  • Bindings.forRemoteDeployment finds the deployment's manager and prepares bindings for it.
  • bindings.key("customer-key") uses the resource ID from alien.ts.
  • On the first call, the binding asks Alien for credentials for the remote role, then calls the customer's key service directly. Credentials last about an hour, and the binding refreshes them five minutes before they expire.

The plaintext and ciphertext go from your backend to the key service. They don't pass through Alien.

encrypt and decrypt take a Buffer or Uint8Array and return a Buffer.

The encryption context

The context is a map of strings that must match exactly at decrypt time. This example binds each ciphertext to the customer it belongs to:

const context = { tenant: requiredEnvironmentVariable("CUSTOMER_ID") }

If a bug or an attacker copies a ciphertext from one tenant's row into another's, decrypting it with the other tenant's context fails. Add whatever identifies the purpose of the value, such as { tenant, table: "integrations", column: "refresh_token" }.

On every cloud, Alien wraps your plaintext in a small frame with a SHA-256 hash of the canonical context and checks that hash on decrypt. Some key services also enforce the context and record it in the customer's audit log:

  • AWS: sent as the KMS encryption context.
  • Google Cloud: sent as additional authenticated data.
  • Azure: Key Vault encrypts the frame with RSA-OAEP-256, and the frame hash enforces the context.

The 128-byte limit

encrypt accepts at most 128 bytes of plaintext. Larger values fail with plaintext exceeds the portable 128-byte limit. The canonical context can be up to 16 KiB.

The limit comes from Azure: Key Vault encrypts with an RSA key, which can only encrypt a small block. Alien applies the same limit on every cloud so code that works on AWS doesn't fail on Azure.

So the customer key is for wrapping other keys, not for encrypting records. For real data, use envelope encryption:

  1. Generate a random data key in your backend.
  2. Encrypt the record locally with it.
  3. Store the data key, encrypted under the customer key, next to the record.

This sketch uses Node's built-in crypto:

src/envelope.ts
import { createCipheriv, randomBytes } from "node:crypto"
import type { Key } from "@alienplatform/bindings"

export async function sealRecord(key: Key, tenant: string, record: Buffer) {
  const dataKey = randomBytes(32)
  const iv = randomBytes(12)
  const cipher = createCipheriv("aes-256-gcm", dataKey, iv)
  const body = Buffer.concat([cipher.update(record), cipher.final()])

  return {
    wrappedKey: await key.encrypt(dataKey, { context: { tenant } }),
    iv,
    tag: cipher.getAuthTag(),
    body,
  }
}

To read the record, decrypt wrappedKey with the same context and decrypt body locally. Each key-service call handles 32 bytes, no matter how large the record is.

You can cache unwrapped data keys briefly to cut latency and KMS cost. A cache delays revocation by up to its lifetime, so keep it short.

Release and onboard a customer

Scaffold the example and publish a release:

alien init customer-keys-ts customer-keys
cd customer-keys
pnpm install
alien release

You can't run this stack with alien dev. A Key exists only in a cloud key service, and remote bindings exist only on AWS, Google Cloud, and Azure deployments. Use a test cloud account as your first customer.

Create a setup link for the customer and send it to their cloud admin. A setup link is a URL that opens the deployment portal, the setup page Alien hosts for the admin. --external-id is the ID your own product uses for this customer:

alien onboard "Customer 1" --allow admin@customer-1.com --external-id customer-1

The admin runs the initial setup with their own credentials, using alien-deploy, Terraform, or on AWS a CloudFormation stack. It creates the key and the remote role.

On AWS, Terraform can use an existing KMS key in the same account and region instead of creating one. See Follow a deployment.

Once the deployment is running, note its ID from alien deployments ls.

Run the backend script

Create a token for that deployment and run the script:

alien deployments token <deployment-id>

export ALIEN_DEPLOYMENT_ID=<deployment-id>
export ALIEN_API_TOKEN=<token>
export CUSTOMER_ID=customer-1
pnpm run run:vendor

run:vendor compiles the TypeScript with tsc and runs dist/src/vendor.js. It prints the base64 ciphertext and the decrypted string:

{ ciphertext: '<base64 ciphertext>', decrypted: 'customer data' }

The token needs write access to the deployment. Alien refuses to issue cloud credentials for a read-only token, a token for another deployment, a resource that isn't running, or a resource without remoteAccess.

Test the kill switch

Ask the customer's admin to disable the key in their console, then run the script again. The key service rejects the call and encrypt throws. Ask them to enable it, and the script succeeds again.

Alien checks the key every 30 seconds. When the key service answers that the key is disabled, deleted, or no longer grants access, the deployment reports Customer key unavailable.

Alien never deletes or recreates the key to recover. When the customer restores access, the same key, and every ciphertext you stored under it, works again.

Disabling the key makes your ciphertext unreadable until the customer restores it. If the customer deletes the key, the ciphertext is gone for good: no one, including the customer, can decrypt it.

Per-cloud behavior

AWSGoogle CloudAzure
Key serviceAWS KMSCloud KMSKey Vault
Key created by TerraformSymmetric KMS key, automatic rotation, 30-day deletion windowENCRYPT_DECRYPT key, rotated every 90 daysRSA 2048 key
AlgorithmKMS symmetric encryptionCloud KMS symmetric encryptionRSA-OAEP-256
Context enforced byKMS encryption context and the frame hashAdditional authenticated data and the frame hashThe frame hash
Audit trailCloudTrail in the customer's accountCloud Audit Logs in the customer's projectKey Vault diagnostic logs in the customer's subscription

The ciphertext format differs per cloud. A ciphertext created on one customer's AWS key can only be decrypted by that key.

Before production

  • Store one deployment per customer. Save the deployment ID next to the customer in your database, or use Bindings.forRemoteCustomer({ project, externalId, token }) with a project API key created with alien api-keys create --for remote-bindings to address customers by your own ID.
  • Keep tokens on the server. Keep the Alien token in a secret manager, scoped to the deployment that owns the key. Never log it or the credentials it returns.
  • Use envelope encryption. Wrap 32-byte data keys, not records. Keep any data-key cache short.
  • Design for a revoked key. Treat encrypt and decrypt failures for a customer as an expected state. Show it in your product, stop background jobs for that customer, and don't fall back to an unencrypted copy.
  • Put the tenant in the context. Never decrypt without the context that identifies whose data it is.

Other ways to use a customer key

A remote key binding, as in this example, is one way to put data under a customer's key:

PathWhere the data livesPage
Remote key binding (this example)Your cloud, encrypted through the customer's keyRemote bindings
encryptionKey on deployed resourcesThe customer's cloud: Storage, Postgres, and volumesCustomer-managed keys
Encrypt/Decrypt APIYour cloud, encrypted over HTTPS without an alien.tsCustomer-managed keys

The keys setup item deploys a stack equivalent to this example: one frozen Key opted into remote access.

Adapt it

Prompt
Use the alien customer-keys-ts example (github.com/alienplatform/alien/tree/main/examples/customer-keys-ts) as a model. Add an alien.ts with one frozen Key added with { remoteAccess: true }, and no other remoteAccess resources. In my backend, protect the sensitive fields I store for enterprise customers with envelope encryption: generate a 32-byte data key, encrypt the field locally with AES-256-GCM, and wrap the data key with Bindings.forRemoteDeployment(...).key("customer-key") using the customer's ID as encryption context. Plaintext passed to the key is limited to 128 bytes. Handle a revoked key with a clear error. Read https://alien.dev/docs/guide/remote-bindings.md and https://alien.dev/docs/guide/customer-managed-keys/in-a-deployment.md first.

Next

On this page