К содержанию
Статья ещё не опубликована на языке Russian. Показана версия на English.

Secret Management and Envelope Encryption for Third-Party OAuth Tokens at Rest

2 мин на чтение

SaaS platforms that integrate with messaging providers, ad networks, or payment gateways must store customer OAuth tokens and bot secrets to act on their behalf in background workers. Storing those credentials in plaintext database columns turns any SQL dump, backup leak, or overly broad read query into a catastrophic multi-tenant breach.

Authenticated Encryption (AES-256-GCM) and Envelope Encryption

Always use Authenticated Encryption with Associated Data (AEAD) such as AES-256-GCM:

  • Confidentiality: plaintext cannot be read without the key.
  • Integrity: any bit flipped in ciphertext fails authentication tag verification.
  • Context Binding (AAD): binding (tenantId, credentialType) as Additional Authenticated Data prevents an attacker from copying an encrypted token from Tenant A's row into Tenant B's row!
LayerRoleRotation Strategy
Key Encryption Key (KEK)Master secret stored in KMS / runtime secret manager (never in DB)Rotate periodically via keyVersion tag
Data Encryption Key (DEK)Per-secret or derived encryption keyRe-wrap DEKs on KEK rotation without decrypting payloads
Nonce / IVUnique random 96-bit value generated fresh per encryptionNever reuse an IV with the same key under GCM
ts
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";

export function encryptToken(plaintext: string, key32Bytes: Buffer, aad: string): string {
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key32Bytes, iv);
  cipher.setAAD(Buffer.from(aad, "utf8"));
  const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const authTag = cipher.getAuthTag();
  return `v1:${iv.toString("base64")}:${authTag.toString("base64")}:${ciphertext.toString("base64")}`;
}

export function decryptToken(encoded: string, key32Bytes: Buffer, aad: string): string {
  const [version, ivB64, tagB64, dataB64] = encoded.split(":");
  if (version !== "v1") throw new Error("Unsupported ciphertext version");
  const decipher = createDecipheriv("aes-256-gcm", key32Bytes, Buffer.from(ivB64, "base64"));
  decipher.setAAD(Buffer.from(aad, "utf8"));
  decipher.setAuthTag(Buffer.from(tagB64, "base64"));
  return Buffer.concat([
    decipher.update(Buffer.from(dataB64, "base64")),
    decipher.final(),
  ]).toString("utf8");
}

Never Pass Raw Secrets Through Workflow Histories or Client Bundles

Keep decrypted tokens strictly inside short-lived server activities or API handlers. Pass only an opaque credentialId through queues, workflow inputs, logs, and browser responses, and resolve the decrypted token right before making the outbound HTTPS call.

Next: track usage and enforce plan limits cleanly without race conditions in Idempotent Usage Metering and Billing Ledgers.

Было ли это полезно?