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).
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
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:
| Cloud | Key service | Remote role permissions |
|---|---|---|
| AWS | AWS KMS | kms:Encrypt, kms:Decrypt on the key |
| Google Cloud | Cloud KMS | roles/cloudkms.cryptoKeyEncrypterDecrypter on the key |
| Azure | Key Vault | keys/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:
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.forRemoteDeploymentfinds the deployment's manager and prepares bindings for it.bindings.key("customer-key")uses the resource ID fromalien.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:
- Generate a random data key in your backend.
- Encrypt the record locally with it.
- Store the data key, encrypted under the customer key, next to the record.
This sketch uses Node's built-in crypto:
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 releaseYou 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-1The 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:vendorrun: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
| AWS | Google Cloud | Azure | |
|---|---|---|---|
| Key service | AWS KMS | Cloud KMS | Key Vault |
| Key created by Terraform | Symmetric KMS key, automatic rotation, 30-day deletion window | ENCRYPT_DECRYPT key, rotated every 90 days | RSA 2048 key |
| Algorithm | KMS symmetric encryption | Cloud KMS symmetric encryption | RSA-OAEP-256 |
| Context enforced by | KMS encryption context and the frame hash | Additional authenticated data and the frame hash | The frame hash |
| Audit trail | CloudTrail in the customer's account | Cloud Audit Logs in the customer's project | Key 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 withalien api-keys create --for remote-bindingsto 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
encryptanddecryptfailures 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:
| Path | Where the data lives | Page |
|---|---|---|
| Remote key binding (this example) | Your cloud, encrypted through the customer's key | Remote bindings |
encryptionKey on deployed resources | The customer's cloud: Storage, Postgres, and volumes | Customer-managed keys |
| Encrypt/Decrypt API | Your cloud, encrypted over HTTPS without an alien.ts | Customer-managed keys |
The keys setup item deploys a stack equivalent to this example: one frozen Key opted into remote access.
Adapt it
Next
A complete application
Deploy a gateway, dashboard, API, worker, scheduler, Postgres, Redis, and object storage as one release into each customer's cluster.
Use the customer's models
Release a stack with one AI resource, let each customer connect Bedrock or Vertex AI, and call their models from your hosted backend through the AI Gateway.