GetClaps
Ücretsiz DenetimFiyatlandırmaSözlükAkademi
  1. Ana sayfa
  2. /Akademi
  3. /L05 · Cryptography and secrets: hashing, HMAC, encryption and the vault

Ana sayfa / Akademi / L05 · Cryptography and secrets: hashing, HMAC, encryption and the vault

L05Bölüm B · GüvenlikOrtaKod doğrulama tarihi: 2026-12-04

Cryptography and secrets: hashing, HMAC, encryption and the vault

How hashing, HMAC, envelope encryption, vault isolation, crypto-shredding, and hash-chained audit logs protect stored tokens and prove history without exposing secrets.

20 dk·3863 kelime·7 soru·36 terim·docs/lessons/05-cryptography-and-secrets.md
Ön koşul:L03 · Data: PostgreSQL, tenants, exact money, and doing things exactly once
Tüm derslere dön
●

Ders içerikleri İngilizce yayınlanır (OD-23)

Sayfa çerçevesi Türkçe ve İngilizce olarak sunulur. Teknik ders metinleri, kod örnekleri ve kendini sına soruları doğrudan ortak kaynak dosyalarından İngilizce okunur; hukuk ve ürün terimlerinde Türkçe karşılıklar yer alır.

0%
▲Yanıtlanan sorular
0 / 7
—
○Doğruluk oranı
Henüz yanıt yok

Bu dersteki bölümler

  1. 1.Why this matters
  2. 2.The ideas
  3. 3.How this repository does it
  4. 4.What went wrong once
  5. 5.Try it yourself
  6. 6.Check yourself
  7. 7.Words to know
  8. 8.Go deeper

Why this matters

Every merchant who connects Meta, Google, Shopify, or a payment account to this product hands over live credentials that can spend advertising money or read customer orders. If a database backup leaks, a web query has a bug, or a developer prints an error object to logs, those credentials become an instant takeover of every connected shop. You cannot solve that risk with database passwords or disk encryption alone, because a running application reads an encrypted disk in plain text. During Wave 45, a review of the API server caught a real bug that illustrates how unforgiving secret management is: the server read an optional vault master key and quietly fell back to generating a brand-new random key on every restart, which meant every OAuth token stored before a restart became permanently unreadable the second the server rebooted. Cryptography only protects a business when the right primitive is picked for each job, keys stay separated from the data they guard, and failure modes fail closed instead of silently losing or leaking secrets.

The ideas

Cryptography feels complex mostly because five different tools get lumped under one word. Nearly every server-side decision in this repository comes down to picking the right primitive from this table:

ToolKey needed?Reversible?What it provesAnalogy
Hash (SHA-256)NoNoExact content fingerprintTamper-evident wax seal
HMAC (HMAC-SHA-256)Shared secretNoSender and unaltered bodyPrivate family signet
Authenticated encryption (AES-256-GCM)Shared secretYesSecrecy plus tamper detectionLocked steel box with latch
Digital signature (ES256, EdDSA)Private signs, public checksNoAuthorship without sharing secretPublicly verifiable signature
HKDFRoot secret + labelNoIsolated child keys per purposeSeparate door keys from one master

One-way hashing and why hashing is not anonymisation

A cryptographic hash turns any bytes into a fixed-length digest, 32 bytes (64 hex characters) for SHA-256. It is one-way, and changing a single bit scrambles the whole output (the avalanche effect).

Two practical traps matter immediately:

  1. Same object, different bytes. In JSON, {"b":2,"a":1} and {"a":1,"b":2} mean the same thing yet hash to unrelated digests. Whenever two programs must compute the same hash independently, they convert objects to canonical JSON first: sorted keys, fixed spacing, and non-finite numbers refused.
  2. Plain hashes of personal data are not anonymous. Because SHA-256 is fast and unkeyed, an attacker with hashed Turkish mobile numbers or e-mails can run a dictionary attack: hash all 100 million +905xxxxxxxxx numbers or a leaked e-mail list in seconds and match them. Under KVKK, hashed identifiers remain personal data.
●

In plain words

Hashing hides an e-mail address from a quick glance, not from a laptop hashing every plausible phone number or e-mail in a loop.

Keyed hashes (HMAC), raw bodies, and constant-time checks

Anyone on the internet can POST fake JSON to a public webhook URL. Plain SHA-256 cannot stop forgery because the attacker can compute SHA-256 on fake payloads too.

An HMAC mixes a shared secret into SHA-256 (RFC 2104) so only someone holding that secret can produce the valid tag. Four rules separate safe HMAC checks from broken ones:

  • Verify the raw body. Parsing JSON and calling JSON.stringify can shift whitespace or escaping by one byte and break valid webhooks.
  • Check a timestamp window. Signing <timestampSec>.<rawBody> and rejecting skew beyond 300 seconds stops attackers from replaying old captured requests.
  • Use constant-time comparison. Plain === stops at the first differing byte; crypto.timingSafeEqual checks every byte in fixed time so timing leaks nothing.
  • Support dual-key rotation. Accepting both current and previous secrets during cutover avoids dropping in-flight webhooks.

Authenticated encryption: AES-256-GCM, nonces, tags, and AAD

When the API must later recover a secret, such as an OAuth refresh token to call Meta or Google, hashing fails because it is one-way. You need reversible authenticated encryption.

AES-256-GCM hides plaintext and detects any modification in one step, producing ciphertext, a fresh 12-byte random nonce (IV), and a 16-byte authentication tag. Three rules are non-negotiable:

  • Never reuse a nonce under one key. GCM encrypts by applying XOR with a keystream derived from the key and nonce. Reusing a nonce cancels the keystream between two ciphertexts, exposing plaintext differences and enabling forged tags.
  • Bind context with additional authenticated data (AAD). Without AAD, an attacker with database write access could perform a ciphertext transplant, copying Workspace A's valid ciphertext into Workspace B's row. Folding workspaceId:connectionId:provider:kekVersion into the authentication tag makes transplanted rows fail decryption immediately.
  • Prevent delimiter injection. Joining AAD parts with colons fails if any part itself contains a colon ("a:b" + "c" collides with "a" + "b:c"). Validating every segment against a strict colon-free allowlist and prefixing versioned domain separation labels (gd-dek-v1:, oauth:) guarantees distinct contexts never collide.

Public-key signatures and HKDF in brief

Passkey sign-in (covered in L04) uses public-key signatures (ES256, EdDSA) so the user's private key never leaves their device. Stored OAuth tokens use symmetric AES-256-GCM because the server both encrypts and later reads them. Whenever one root secret must yield separate symmetric keys for distinct features, HKDF (RFC 5869) derives independent child keys bound to purpose labels.

Envelope encryption, rotation, sealing, and zeroisation

Encrypting 50,000 OAuth tokens directly with one master key makes master-key rotation slow and per-customer erasure messy. Envelope encryption uses two key layers:

text
[ Master KEK (32 bytes, process config ONLY, never in PostgreSQL) ]
       |  wraps / unwraps (AES-256-GCM + AAD "gd-dek-v1:<ws>:<kekVer>")
       v
[ Workspace DEK (32 bytes, stored as 63-byte wrapped_dek in vault.workspace_deks) ]
       |  encrypts / decrypts (AES-256-GCM + AAD "<ws>:<conn>:<provider>:<kekVer>")
       v
[ OAuth Tokens / Credentials (ciphertext + 12B IV + 16B auth_tag) ]

Each workspace has its own 256-bit data encryption key (DEK). The master key encryption key (KEK) performs only key wrapping on those small 32-byte DEKs. During key rotation, KEK rotation simply rewraps each 32-byte DEK under KEK v2 with zero token ciphertexts re-encrypted, whereas DEK rotation generates a new workspace DEK and re-encrypts only that workspace's rows.

For short-lived standalone items such as pending OAuth states or authenticator secrets, sealing generates a fresh per-item 256-bit DEK, wraps it under the KEK, and packs the wrapped DEK, IV, tag, and ciphertext with strict flow AAD. After any unwrap, zeroisation (buf.fill(0) in finally) wipes mutable key buffers, though JavaScript strings are immutable and remain until garbage collection.

Vault isolation, crypto-shredding, and hash-chained audit logs

Encryption sits behind database isolation: encrypted secrets live inside a separate vault schema reachable only through the vault executor role, while normal screens list connection metadata from a safe view (oauth_connections_safe) with zero crypto columns.

On revocation or tenant erasure, crypto-shredding destroys key material (and overwrites revoked row columns) so live ciphertext can no longer decrypt, optionally recording a PII-free erasure certificate. Meanwhile, the append-only audit log links every row into an audit chain from a 64-zero genesis hash, summarised by an audit chain checkpoint and exportable as an audit bundle for offline verification without trusting the server.

How this repository does it

Every cryptographic mechanism described above maps directly to live files in this repository. Notice the careful status distinctions: the core cryptographic primitives, database schema, triggers, scrubbers, and offline verifiers are built and verified by automated tests, while production key custody, runtime multi-version KEK rotation, and live deployment are not built yet.

CapabilityLive repository filesVerified detailStatus
Envelope encryption & AADpackages/vault/src/envelope.tsAES-256-GCM, 12B random IV, 16B tag, 63B wrapped DEK, SAFE_AAD_SEGMENT_RE, validateKey256, zeroizeBufferVerified
KEK rewrap & DEK rotation librarypackages/vault/src/rotation.tsrewrapWorkspaceDek, rotateKekBatch (ciphertextsReencrypted: 0), rotateWorkspaceDekVerified (library)
Crypto-shredding & erasure certificatespackages/vault/src/crypto-shred.tsshredTenantDek, buildErasureCertificate (domain-separated SHA-256 commitments, hashed not signed), verifyCryptoShredProofVerified
OAuth standalone sealingapps/api/src/connections/oauth/sealing.tsFresh 256-bit DEK per blob, [0x01][63B wrapped DEK][12B IV][16B tag][ciphertext], oauth:... AADVerified
Raw-body HMAC & dual-key rotationapps/api/src/hmac.ts, packages/connectors/src/hmac-verifiers.ts<timestampSec>.<rawBody>, 300s skew window, MAX_HMAC_ROTATION_SECRETS = 2, timingSafeEqualVerified
Vault schema, safe view & rolesdocs/schema.sql, docs/adr/0004-zero-password-vault-and-force-rls.mdvault.workspace_deks, vault.oauth_connections, vault.sub_merchants, vault.audit_chain_head, oauth_connections_safe, vault_executorVerified
Least-privilege vault runtime configapps/api/src/platform/runtime-config.ts, apps/api/src/dispatch-main.tsFails closed in production if VAULT_MASTER_KEK_BASE64 missing/zero; only API and dispatch hold VAULT_DATABASE_URL + KEKVerified
Hash-chained audit log & checkpointpackages/approvals/src/audit-chain.ts, packages/approvals/src/canonical-hash.ts, apps/api/src/routes/audit-log-chain-checkpoint.tsGENESIS_PREV_HASH_HEX, canonicalJsonStringify, FOR UPDATE lock on vault.audit_chain_head, 16-char checkpoint prefixVerified
Offline audit bundle verifierpackages/vault/src/audit-bundle-verifier.ts, tools/verify-audit-bundle.mjs, apps/web/src/app/trust/bundle-verify-browser.tsVerifies pg_preimage_v1 rows offline in Node.js CLI or browser Web CryptoVerified
Log redaction & secret scanningpackages/vault/src/log-scrubber.ts, tools/lib/zero-echo.mjs, .gitleaks.tomlFORBIDDEN_SECRET_KEY_SET, value-level detectSecrets, assertNoSecrets, scrubOpaque, Gitleaks rulesVerified

Inside the 63-byte wrapped DEK

Open packages/vault/src/envelope.ts and you will see an exact binary layout (WRAPPED_DEK_TOTAL_BYTES = 63) that makes key wrapping self-describing and tamper-evident:

text
Byte offset   Length   Meaning
0             1 byte   Envelope format version (0x01)
1..2          2 bytes  kekVersion (unsigned 16-bit big-endian integer)
3..14         12 bytes Random AES-256-GCM IV (nonce)
15..30        16 bytes AES-256-GCM authentication tag
31..62        32 bytes Encrypted 256-bit workspace DEK ciphertext

When unwrapDek opens that 63-byte buffer, it reads kekVersion from bytes 1–2, looks up that exact master key inside KekKeyring, rebuilds gd-dek-v1:${workspaceId}:${kekVersion} as AAD, and decrypts. If anyone edits byte 2 to claim a different key version, or copies the 63 bytes to another workspace row, the 16-byte tag check fails before a single key byte is returned. Furthermore, validateKey256 explicitly rejects an all-zero 32-byte buffer (WEAK_ZERO_KEY) so a broken configuration script cannot accidentally encrypt production data with zeros.

Process separation and secret hygiene

Notice how least privilege spans both PostgreSQL and operating-system processes:

text
Web / API process       --> holds DATABASE_URL + VAULT_DATABASE_URL + VAULT_MASTER_KEK_BASE64
Dispatch process        --> holds DATABASE_URL + VAULT_DATABASE_URL + VAULT_MASTER_KEK_BASE64
General background job  --> holds DATABASE_URL ONLY (lint refuses any VAULT_* env var)
SEO crawler worker      --> holds ZERO database or vault credentials (enforced at startup)

Even inside the API process, redaction works as a second net. packages/vault/src/log-scrubber.ts maintains both a key allowlist/denylist (FORBIDDEN_SECRET_KEY_SET alongside SAFE_SHA256_HASH_KEY_SET so legitimate audit digests do not false-positive) and value-level pattern detectors (detectSecrets) that catch OAuth tokens, JWTs (eyJ...), raw IBANs, tax IDs, and base64/hex keys even when tucked under an innocent field name. Startup configuration failures in apps/api/src/platform/runtime-config.ts throw ApiRuntimeConfigError carrying machine-readable error codes only — never echoing back the malformed secret value.

◆

Not built yet

Nothing in this repository is deployed to production, no real Meta or Google API call has been made with live customer tokens, and there are no live customers yet. Inside the vault specifically, three pieces remain unfinished before live launch: (1) runtime config currently runs only SUPPORTED_VAULT_KEK_VERSION = 1 — the multi-version KekKeyring and rotateKekBatch functions are built and unit-tested, but a production operator rotation runbook and multi-KEK environment loader are not wired yet; (2) external KMS or HSM key custody and offline KEK backup procedures are designed as open decisions rather than wired infrastructure; and (3) erasure certificates in crypto-shred.ts carry a SHA-256 self-hash (certificateSha256), not a third-party digital signature.

What went wrong once

Real cryptographic failures rarely come from breaking AES-256 mathematically; they come from wiring, lifecycle, and process-boundary mistakes around the cipher. Four real incidents from Waves 45 through 48 show how those bugs happen and how they were fixed.

1. The master key that regenerated on every boot (Wave 45, finding P-2)

During an early review, the API factory initialised the vault key with deps.vaultKek ?? generateKek(), and the production bootstrap never passed deps.vaultKek in. Everything looked green in single-process tests. The moment two API instances ran or one process restarted, however, the new process generated a brand-new ephemeral key and could not decrypt a single OAuth token stored minutes earlier.

Fix: apps/api/src/platform/runtime-config.ts now loads VAULT_MASTER_KEK_BASE64, verifies it decodes to exactly 32 non-zero bytes, and refuses to boot in production if it is missing or malformed. Outside production, an ephemeral fallback remains allowed for local convenience, but logs an explicit api.vault_kek_ephemeral warning so no developer mistakes it for durable storage.

2. Connections stored in memory, and what deleting a token really requires (Wave 47, finding P-10)

While tracing the vault key fix, a reviewer discovered that POST /connections encrypted incoming OAuth tokens properly and then saved the encrypted row inside an in-memory JavaScript Map even when PostgreSQL was configured. Restarting the server wiped every connection, and there was no real revoke path.

When Wave 47 wired persistence into vault.oauth_connections over the separate vault database pool (failing closed with 503 VAULT_STORE_NOT_CONFIGURED before spending a single-use step-up token if the vault pool or KEK is missing), the implementing engineer caught a subtle crypto-shredding trap on revoke. Because every connection inside a workspace shares that workspace's DEK, overwriting only a revoked connection row's wrapped_dek column would leave its ciphertext still decryptable with the active workspace DEK.

Fix: Revocation now calls the upstream provider and always overwrites all four cryptographic columns (wrapped_dek, ciphertext, iv, auth_tag), verified by a mutation check that confirms skipping ciphertext causes the revoke test to fail. The engineering report also states the honest database boundary: overwriting live columns destroys the live copy only; PostgreSQL MVCC retains old row versions on disk until VACUUM runs, and older database backups retain whatever ciphertext and wrapped keys were present when the backup was taken until those backups expire.

3. Sample workspaces whose placeholder DEKs refused real connections (Wave 47)

Static SQL seed files for local demo workspaces cannot wrap a workspace DEK under a master key that only exists at runtime, so the seed inserted opaque placeholder bytes into vault.workspace_deks. When developers tried connecting a real test account to a seeded workspace, the vault rejected the row as corrupted (503 VAULT_WORKSPACE_KEY_UNAVAILABLE).

Fix: First, the team locked down an unbreakable safety rule: the API must never silently overwrite an undecryptable workspace DEK, because silently generating a replacement key when a real KEK is merely misconfigured would permanently orphan every existing connection in that workspace. Only a narrow local dev-stack bootstrap path performs a strict compare-and-set matching the exact known seed placeholder bytes, guaranteeing a real workspace key is never overwritten.

4. Moving OAuth token refresh out of the general worker (Wave 48)

OAuth access tokens expire and must be refreshed in the background, which requires both VAULT_DATABASE_URL and VAULT_MASTER_KEK_BASE64. An initial draft placed token refresh inside the general background worker — and immediately collided with a deployment lint test that deliberately forbids any VAULT_* environment variable in the general worker unit.

Rather than relaxing the security rule to give a broad worker access to every customer's vault keys, Wave 48 moved token refresh into a tiny dedicated process, apps/api/src/dispatch-main.ts, running under its own dedicated operating-system user so the general worker cannot even read its environment file. The lesson is foundational: when a job needs a secret, move the job to the smallest process allowed to hold that secret; never widen the secret boundary to match a convenient process.

Try it yourself

Every step below is read-only and safe to run from the repository root in PowerShell or Git Bash. None of these commands touch ports 3000, 4000, or 5432, require PostgreSQL, or contact any external provider.

Step 1: See SHA-256 avalanche and why canonical JSON matters

Run this short Node.js one-liner to compare two objects with identical keys in different orders and watch one changed character scramble a SHA-256 digest:

bash
node -e "const c=require('node:crypto'); const h=(s)=>c.createHash('sha256').update(s).digest('hex'); console.log('a-first:', h('{\"a\":1,\"b\":2}')); console.log('b-first:', h('{\"b\":2,\"a\":1}')); console.log('1-bit:  ', h('{\"a\":1,\"b\":3}'));"

Notice that a-first and b-first produce completely unrelated 64-character hex hashes even though they mean the same thing. That is why packages/approvals/src/canonical-hash.ts sorts keys before hashing.

Step 2: Run the vault envelope, rotation, and log-scrubber test suite

Execute the self-contained vault unit tests to watch AES-256-GCM round-trips, 1-byte tamper rejection, cross-workspace AAD swap blocking, zero-reencryption KEK rotation, and secret-scrubber assertions run live:

bash
node --test packages/vault/test/vault.test.mjs

Look for suites 3, 4, and 5 in the output: suite 3 flips single bytes in ciphertext, IV, tag, and AAD; suite 4 rotates KEK v1 to v2 with zero ciphertexts re-encrypted; and suite 5 checks that tokens, base64 keys, IBANs, and tax numbers never escape into logs or oauth_connections_safe.

Step 3: Run the crypto-shredding and offline audit-bundle verifier tests

Verify that destroying a workspace DEK renders its ciphertexts unreadable, erasure certificates detect tampering, and offline audit bundle verification catches modified or missing rows:

bash
node --test packages/vault/test/crypto-shred.test.mjs packages/vault/test/audit-bundle-verifier.test.mjs

Both suites run purely in memory with zero database setup and prove the mathematical checks behind tools/verify-audit-bundle.mjs and apps/web/src/app/trust/bundle-verify-browser.ts.

Step 4: Inspect the 63-byte wrapped DEK layout and startup KEK validation

Open packages/vault/src/envelope.ts and find WRAPPED_DEK_TOTAL_BYTES, SAFE_AAD_SEGMENT_RE, and validateKey256, then open apps/api/src/platform/runtime-config.ts and find VAULT_MASTER_KEK_BASE64. Trace how the runtime refuses all-zero keys and missing production keys without ever printing the secret value in the thrown error.

Check yourself

0 / 7

Q1.Why is hashing customer e-mails with plain SHA-256 not enough to call a dataset anonymous?

Q2.Why must webhook HMAC checks run on the raw HTTP body instead of JSON.stringify(req.body)?

Q3.What attack does binding workspaceId:connectionId:provider:kekVersion as AAD in AES-256-GCM stop?

Q4.Why does rotating the master KEK under envelope encryption avoid re-encrypting stored OAuth tokens?

Q5.On per-connection revoke in Wave 47, why was wiping only wrapped_dek insufficient?

Q6.Why did Wave 48 move OAuth token refresh to apps/api/src/dispatch-main.ts instead of giving the general worker the vault key?

Q7.Why does an exported audit bundle support offline verification?

Words to know

36
additional authenticated dataAAD

Plain context bound into an encryption tag so that a ciphertext only opens in the exact place it belongs.

Kriptografi ve gizlilerSözlükte incele
AES-256-GCM

A standard symmetric cipher that uses a 256-bit key in Galois/Counter Mode to encrypt data and verify its integrity in one step.

Kriptografi ve gizlilerSözlükte incele
audit bundleTR: denetim paketi

A self-contained export of audit log rows and their hashes that an outsider can verify offline without trusting the server.

Kriptografi ve gizlilerSözlükte incele
audit chainTR: denetim zinciri

A hash-linked sequence of audit log rows where each row hashes the previous row's digest so past edits break the chain.

Kriptografi ve gizlilerSözlükte incele
audit chain checkpointTR: kontrol noktası

A read-only summary of a workspace's audit chain showing its bounds, head hash prefix, and whether every link verifies.

Kriptografi ve gizlilerSözlükte incele
audit logTR: denetim kaydı

An append-only record of who performed each sensitive action and when, protected against updates and deletions.

Kriptografi ve gizlilerSözlükte incele
authenticated encryptionAEAD

Encryption that provides both confidentiality and tamper detection in a single primitive, optionally checking unencrypted context.

Kriptografi ve gizlilerSözlükte incele
authentication tagTR: kimlik doğrulama etiketi

A fixed-length proof produced beside ciphertext by authenticated encryption to detect any change to the data or its AAD.

Kriptografi ve gizlilerSözlükte incele
canonical JSONTR: kanonik JSON

A single deterministic text representation of a JSON value, with sorted object keys, so equal data always hashes identically.

Kriptografi ve gizlilerSözlükte incele
ciphertext transplant

An attack that copies valid encrypted bytes from one row or tenant into another to trick the application into decrypting them there.

Kriptografi ve gizlilerSözlükte incele
constant-time comparisonTR: zamanlamaya dayanıklı karşılaştırma

Comparing two secret strings or byte buffers in fixed time regardless of where they first differ, preventing timing leaks.

Kriptografi ve gizlilerSözlükte incele
crypto-shreddingTR: kriptografik imha

Destroying a tenant's data encryption key so all ciphertext encrypted under it becomes permanently unreadable.

Kriptografi ve gizlilerSözlükte incele
data encryption keyDEKTR: veri şifreleme anahtarı

The 256-bit key that directly encrypts stored secrets, kept in the database only after being wrapped by the master key.

Kriptografi ve gizlilerSözlükte incele
delimiter injectionTR: ayırıcı enjeksiyonu

A bug where an input contains the separator character used to join fields, making two distinct field tuples collide into one string.

Kriptografi ve gizlilerSözlükte incele
dictionary attackTR: sözlük saldırısı

Reversing a hash by hashing a huge list of likely inputs, such as emails or phone numbers, until a digest matches.

Kriptografi ve gizlilerSözlükte incele
domain separation

Prefixing a hash, AAD, or key derivation with a fixed purpose label so outputs from one context can never validate in another.

Kriptografi ve gizlilerSözlükte incele
dual-key rotationTR: çift anahtar rotasyonu

Rotating a shared signing secret with zero downtime by temporarily verifying incoming requests against both current and previous keys.

Kriptografi ve gizlilerSözlükte incele
envelope encryptionTR: zarf şifreleme

A two-layer scheme where a data encryption key encrypts the secrets and a master key encrypts only the data keys.

Kriptografi ve gizlilerSözlükte incele
ephemeral key

A random key generated in memory at process startup and discarded on exit, making anything encrypted with it unrecoverable after restart.

Kriptografi ve gizlilerSözlükte incele
erasure certificate

A PII-free JSON record attesting that a workspace's data key was destroyed, carrying a SHA-256 hash of its own fields.

Kriptografi ve gizlilerSözlükte incele
hashTR: özet

A fixed-length one-way fingerprint of any input data that changes completely if even one bit of the input changes.

Kriptografi ve gizlilerSözlükte incele
HKDFHKDF

An HMAC-based standard for deriving one or more independent cryptographic keys from an input secret and a context label.

Kriptografi ve gizlilerSözlükte incele
HMACHMAC

A keyed hash computed from a message and a shared secret that proves both who sent the message and that it was not altered.

Kriptografi ve gizlilerSözlükte incele
key encryption keyKEKTR: anahtar şifreleme anahtarı

The top-level 256-bit master key that wraps workspace data keys and never gets written into the database.

Kriptografi ve gizlilerSözlükte incele
key rotationTR: anahtar döndürme

Replacing an active cryptographic key with a fresh version without downtime to limit blast radius and meet compliance schedules.

Kriptografi ve gizlilerSözlükte incele
key wrappingTR: anahtar sarma

Encrypting a data encryption key under a master key so the data key can be stored safely in the database.

Kriptografi ve gizlilerSözlükte incele
nonce

A unique per-encryption value, 12 random bytes in AES-256-GCM, that must never repeat under the same key.

Kriptografi ve gizlilerSözlükte incele
offline verificationTR: çevrimdışı doğrulama

Checking an exported audit bundle locally using standalone code with zero network calls to the product's servers.

Kriptografi ve gizlilerSözlükte incele
raw bodyTR: ham gövde

The exact unaltered bytes of an incoming HTTP request body before JSON parsing, required for verifying webhook signatures.

Kriptografi ve gizlilerSözlükte incele
redactionTR: maskeleme

Replacing secrets or personal data with a safe placeholder such as [REDACTED] before writing logs, responses, or exports.

Kriptografi ve gizlilerSözlükte incele
safe viewTR: arındırılmış görünüm

A restricted database view that exposes only non-secret connection metadata so application code can list connections without reading ciphertext.

Kriptografi ve gizlilerSözlükte incele
sealing

Encrypting a single short-lived secret with a fresh per-item key and strict context AAD so it opens only in its intended flow.

Kriptografi ve gizlilerSözlükte incele
SHA-256

A standardised member of the SHA-2 hash family that produces a 32-byte (64-hex-character) one-way digest from any input.

Kriptografi ve gizlilerSözlükte incele
vaultTR: kasa

The isolated database schema and encryption package that holds wrapped keys and encrypted OAuth tokens away from main app queries.

Kriptografi ve gizlilerSözlükte incele
vault executor role

The separate, least-privilege PostgreSQL role that is the only runtime identity permitted to read or write the vault schema.

Kriptografi ve gizlilerSözlükte incele
zeroisationTR: bellek temizleme

Overwriting sensitive key bytes in a memory buffer with zeros as soon as an operation finishes, shrinking the exposure window.

Kriptografi ve gizlilerSözlükte incele

Go deeper

  • ADR 0004: Zero-password vault and FORCE RLS — design decision behind the isolated vault schema, envelope encryption, and oauth_connections_safe.
  • ADR 0005: Expiring SHA-256 approval ledger — how canonical JSON hashing binds approval previews to executed actions.
  • Threat model — specifically assets A1–A2, threat T2 (vault credential theft), and gate G2.
  • Archived lesson 14: Cryptography, vault DEK/KEK and audit chains — earlier wave notes replaced by this lesson.
  • Archived lesson 26: Audit retention and assurance — earlier notes on audit retention and bundle verification.
  • Archived lesson 31: Audit chain checkpoints — earlier notes on workspace audit checkpoints.
  • NIST SP 800-38D: Recommendation for Galois/Counter Mode (GCM) — authoritative standard on AES-GCM nonces, tags, and AAD.
  • NIST FIPS 180-4: Secure Hash Standard (SHA-256) — official specification of SHA-256.
  • RFC 2104: HMAC — Keyed-Hashing for Message Authentication — why HMAC uses a two-pass keyed hash construction.
  • RFC 5869: HKDF — HMAC-based Key Derivation Function — deriving domain-separated keys safely.
  • RFC 8785: JSON Canonicalization Scheme (JCS) — deterministic JSON serialisation for cryptographic hashing.
  • Node.js node:crypto documentation — official reference for createCipheriv, createHmac, timingSafeEqual, and randomBytes.
  • MDN Web Crypto API — browser-native crypto.subtle used by the offline audit verifier.
◆

NOT LEGAL OR TAX ADVICE · Açık karar kapıları dürüstlüğü

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

Önceki ders: L04Sonraki ders: L06

L05 · Part B · intermediate · Verified 2026-12-04 · 20 min

Cryptography and secrets: hashing, HMAC, encryption and the vault

How hashing, HMAC, envelope encryption, vault isolation, crypto-shredding, and hash-chained audit logs protect stored tokens and prove history without exposing secrets.

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

Why this matters

Every merchant who connects Meta, Google, Shopify, or a payment account to this product hands over live credentials that can spend advertising money or read customer orders. If a database backup leaks, a web query has a bug, or a developer prints an error object to logs, those credentials become an instant takeover of every connected shop. You cannot solve that risk with database passwords or disk encryption alone, because a running application reads an encrypted disk in plain text. During Wave 45, a review of the API server caught a real bug that illustrates how unforgiving secret management is: the server read an optional vault master key and quietly fell back to generating a brand-new random key on every restart, which meant every OAuth token stored before a restart became permanently unreadable the second the server rebooted. Cryptography only protects a business when the right primitive is picked for each job, keys stay separated from the data they guard, and failure modes fail closed instead of silently losing or leaking secrets.

The ideas

Cryptography feels complex mostly because five different tools get lumped under one word. Nearly every server-side decision in this repository comes down to picking the right primitive from this table:

ToolKey needed?Reversible?What it provesAnalogy
Hash (SHA-256)NoNoExact content fingerprintTamper-evident wax seal
HMAC (HMAC-SHA-256)Shared secretNoSender and unaltered bodyPrivate family signet
Authenticated encryption (AES-256-GCM)Shared secretYesSecrecy plus tamper detectionLocked steel box with latch
Digital signature (ES256, EdDSA)Private signs, public checksNoAuthorship without sharing secretPublicly verifiable signature
HKDFRoot secret + labelNoIsolated child keys per purposeSeparate door keys from one master

One-way hashing and why hashing is not anonymisation

A cryptographic hash turns any bytes into a fixed-length digest, 32 bytes (64 hex characters) for SHA-256. It is one-way, and changing a single bit scrambles the whole output (the avalanche effect).

Two practical traps matter immediately:

  1. Same object, different bytes. In JSON, {"b":2,"a":1} and {"a":1,"b":2} mean the same thing yet hash to unrelated digests. Whenever two programs must compute the same hash independently, they convert objects to canonical JSON first: sorted keys, fixed spacing, and non-finite numbers refused.
  2. Plain hashes of personal data are not anonymous. Because SHA-256 is fast and unkeyed, an attacker with hashed Turkish mobile numbers or e-mails can run a dictionary attack: hash all 100 million +905xxxxxxxxx numbers or a leaked e-mail list in seconds and match them. Under KVKK, hashed identifiers remain personal data.
●

In plain words

Hashing hides an e-mail address from a quick glance, not from a laptop hashing every plausible phone number or e-mail in a loop.

Keyed hashes (HMAC), raw bodies, and constant-time checks

Anyone on the internet can POST fake JSON to a public webhook URL. Plain SHA-256 cannot stop forgery because the attacker can compute SHA-256 on fake payloads too.

An HMAC mixes a shared secret into SHA-256 (RFC 2104) so only someone holding that secret can produce the valid tag. Four rules separate safe HMAC checks from broken ones:

  • Verify the raw body. Parsing JSON and calling JSON.stringify can shift whitespace or escaping by one byte and break valid webhooks.
  • Check a timestamp window. Signing <timestampSec>.<rawBody> and rejecting skew beyond 300 seconds stops attackers from replaying old captured requests.
  • Use constant-time comparison. Plain === stops at the first differing byte; crypto.timingSafeEqual checks every byte in fixed time so timing leaks nothing.
  • Support dual-key rotation. Accepting both current and previous secrets during cutover avoids dropping in-flight webhooks.

Authenticated encryption: AES-256-GCM, nonces, tags, and AAD

When the API must later recover a secret, such as an OAuth refresh token to call Meta or Google, hashing fails because it is one-way. You need reversible authenticated encryption.

AES-256-GCM hides plaintext and detects any modification in one step, producing ciphertext, a fresh 12-byte random nonce (IV), and a 16-byte authentication tag. Three rules are non-negotiable:

  • Never reuse a nonce under one key. GCM encrypts by applying XOR with a keystream derived from the key and nonce. Reusing a nonce cancels the keystream between two ciphertexts, exposing plaintext differences and enabling forged tags.
  • Bind context with additional authenticated data (AAD). Without AAD, an attacker with database write access could perform a ciphertext transplant, copying Workspace A's valid ciphertext into Workspace B's row. Folding workspaceId:connectionId:provider:kekVersion into the authentication tag makes transplanted rows fail decryption immediately.
  • Prevent delimiter injection. Joining AAD parts with colons fails if any part itself contains a colon ("a:b" + "c" collides with "a" + "b:c"). Validating every segment against a strict colon-free allowlist and prefixing versioned domain separation labels (gd-dek-v1:, oauth:) guarantees distinct contexts never collide.

Public-key signatures and HKDF in brief

Passkey sign-in (covered in L04) uses public-key signatures (ES256, EdDSA) so the user's private key never leaves their device. Stored OAuth tokens use symmetric AES-256-GCM because the server both encrypts and later reads them. Whenever one root secret must yield separate symmetric keys for distinct features, HKDF (RFC 5869) derives independent child keys bound to purpose labels.

Envelope encryption, rotation, sealing, and zeroisation

Encrypting 50,000 OAuth tokens directly with one master key makes master-key rotation slow and per-customer erasure messy. Envelope encryption uses two key layers:

[ Master KEK (32 bytes, process config ONLY, never in PostgreSQL) ]
       |  wraps / unwraps (AES-256-GCM + AAD "gd-dek-v1:<ws>:<kekVer>")
       v
[ Workspace DEK (32 bytes, stored as 63-byte wrapped_dek in vault.workspace_deks) ]
       |  encrypts / decrypts (AES-256-GCM + AAD "<ws>:<conn>:<provider>:<kekVer>")
       v
[ OAuth Tokens / Credentials (ciphertext + 12B IV + 16B auth_tag) ]

Each workspace has its own 256-bit data encryption key (DEK). The master key encryption key (KEK) performs only key wrapping on those small 32-byte DEKs. During key rotation, KEK rotation simply rewraps each 32-byte DEK under KEK v2 with zero token ciphertexts re-encrypted, whereas DEK rotation generates a new workspace DEK and re-encrypts only that workspace's rows.

For short-lived standalone items such as pending OAuth states or authenticator secrets, sealing generates a fresh per-item 256-bit DEK, wraps it under the KEK, and packs the wrapped DEK, IV, tag, and ciphertext with strict flow AAD. After any unwrap, zeroisation (buf.fill(0) in finally) wipes mutable key buffers, though JavaScript strings are immutable and remain until garbage collection.

Vault isolation, crypto-shredding, and hash-chained audit logs

Encryption sits behind database isolation: encrypted secrets live inside a separate vault schema reachable only through the vault executor role, while normal screens list connection metadata from a safe view (oauth_connections_safe) with zero crypto columns.

On revocation or tenant erasure, crypto-shredding destroys key material (and overwrites revoked row columns) so live ciphertext can no longer decrypt, optionally recording a PII-free erasure certificate. Meanwhile, the append-only audit log links every row into an audit chain from a 64-zero genesis hash, summarised by an audit chain checkpoint and exportable as an audit bundle for offline verification without trusting the server.

How this repository does it

Every cryptographic mechanism described above maps directly to live files in this repository. Notice the careful status distinctions: the core cryptographic primitives, database schema, triggers, scrubbers, and offline verifiers are built and verified by automated tests, while production key custody, runtime multi-version KEK rotation, and live deployment are not built yet.

CapabilityLive repository filesVerified detailStatus
Envelope encryption & AADpackages/vault/src/envelope.tsAES-256-GCM, 12B random IV, 16B tag, 63B wrapped DEK, SAFE_AAD_SEGMENT_RE, validateKey256, zeroizeBufferVerified
KEK rewrap & DEK rotation librarypackages/vault/src/rotation.tsrewrapWorkspaceDek, rotateKekBatch (ciphertextsReencrypted: 0), rotateWorkspaceDekVerified (library)
Crypto-shredding & erasure certificatespackages/vault/src/crypto-shred.tsshredTenantDek, buildErasureCertificate (domain-separated SHA-256 commitments, hashed not signed), verifyCryptoShredProofVerified
OAuth standalone sealingapps/api/src/connections/oauth/sealing.tsFresh 256-bit DEK per blob, [0x01][63B wrapped DEK][12B IV][16B tag][ciphertext], oauth:... AADVerified
Raw-body HMAC & dual-key rotationapps/api/src/hmac.ts, packages/connectors/src/hmac-verifiers.ts<timestampSec>.<rawBody>, 300s skew window, MAX_HMAC_ROTATION_SECRETS = 2, timingSafeEqualVerified
Vault schema, safe view & rolesdocs/schema.sql, docs/adr/0004-zero-password-vault-and-force-rls.mdvault.workspace_deks, vault.oauth_connections, vault.sub_merchants, vault.audit_chain_head, oauth_connections_safe, vault_executorVerified
Least-privilege vault runtime configapps/api/src/platform/runtime-config.ts, apps/api/src/dispatch-main.tsFails closed in production if VAULT_MASTER_KEK_BASE64 missing/zero; only API and dispatch hold VAULT_DATABASE_URL + KEKVerified
Hash-chained audit log & checkpointpackages/approvals/src/audit-chain.ts, packages/approvals/src/canonical-hash.ts, apps/api/src/routes/audit-log-chain-checkpoint.tsGENESIS_PREV_HASH_HEX, canonicalJsonStringify, FOR UPDATE lock on vault.audit_chain_head, 16-char checkpoint prefixVerified
Offline audit bundle verifierpackages/vault/src/audit-bundle-verifier.ts, tools/verify-audit-bundle.mjs, apps/web/src/app/trust/bundle-verify-browser.tsVerifies pg_preimage_v1 rows offline in Node.js CLI or browser Web CryptoVerified
Log redaction & secret scanningpackages/vault/src/log-scrubber.ts, tools/lib/zero-echo.mjs, .gitleaks.tomlFORBIDDEN_SECRET_KEY_SET, value-level detectSecrets, assertNoSecrets, scrubOpaque, Gitleaks rulesVerified

Inside the 63-byte wrapped DEK

Open packages/vault/src/envelope.ts and you will see an exact binary layout (WRAPPED_DEK_TOTAL_BYTES = 63) that makes key wrapping self-describing and tamper-evident:

Byte offset   Length   Meaning
0             1 byte   Envelope format version (0x01)
1..2          2 bytes  kekVersion (unsigned 16-bit big-endian integer)
3..14         12 bytes Random AES-256-GCM IV (nonce)
15..30        16 bytes AES-256-GCM authentication tag
31..62        32 bytes Encrypted 256-bit workspace DEK ciphertext

When unwrapDek opens that 63-byte buffer, it reads kekVersion from bytes 1–2, looks up that exact master key inside KekKeyring, rebuilds gd-dek-v1:${workspaceId}:${kekVersion} as AAD, and decrypts. If anyone edits byte 2 to claim a different key version, or copies the 63 bytes to another workspace row, the 16-byte tag check fails before a single key byte is returned. Furthermore, validateKey256 explicitly rejects an all-zero 32-byte buffer (WEAK_ZERO_KEY) so a broken configuration script cannot accidentally encrypt production data with zeros.

Process separation and secret hygiene

Notice how least privilege spans both PostgreSQL and operating-system processes:

Web / API process       --> holds DATABASE_URL + VAULT_DATABASE_URL + VAULT_MASTER_KEK_BASE64
Dispatch process        --> holds DATABASE_URL + VAULT_DATABASE_URL + VAULT_MASTER_KEK_BASE64
General background job  --> holds DATABASE_URL ONLY (lint refuses any VAULT_* env var)
SEO crawler worker      --> holds ZERO database or vault credentials (enforced at startup)

Even inside the API process, redaction works as a second net. packages/vault/src/log-scrubber.ts maintains both a key allowlist/denylist (FORBIDDEN_SECRET_KEY_SET alongside SAFE_SHA256_HASH_KEY_SET so legitimate audit digests do not false-positive) and value-level pattern detectors (detectSecrets) that catch OAuth tokens, JWTs (eyJ...), raw IBANs, tax IDs, and base64/hex keys even when tucked under an innocent field name. Startup configuration failures in apps/api/src/platform/runtime-config.ts throw ApiRuntimeConfigError carrying machine-readable error codes only — never echoing back the malformed secret value.

◆

Not built yet

Nothing in this repository is deployed to production, no real Meta or Google API call has been made with live customer tokens, and there are no live customers yet. Inside the vault specifically, three pieces remain unfinished before live launch: (1) runtime config currently runs only SUPPORTED_VAULT_KEK_VERSION = 1 — the multi-version KekKeyring and rotateKekBatch functions are built and unit-tested, but a production operator rotation runbook and multi-KEK environment loader are not wired yet; (2) external KMS or HSM key custody and offline KEK backup procedures are designed as open decisions rather than wired infrastructure; and (3) erasure certificates in crypto-shred.ts carry a SHA-256 self-hash (certificateSha256), not a third-party digital signature.

What went wrong once

Real cryptographic failures rarely come from breaking AES-256 mathematically; they come from wiring, lifecycle, and process-boundary mistakes around the cipher. Four real incidents from Waves 45 through 48 show how those bugs happen and how they were fixed.

1. The master key that regenerated on every boot (Wave 45, finding P-2)

During an early review, the API factory initialised the vault key with deps.vaultKek ?? generateKek(), and the production bootstrap never passed deps.vaultKek in. Everything looked green in single-process tests. The moment two API instances ran or one process restarted, however, the new process generated a brand-new ephemeral key and could not decrypt a single OAuth token stored minutes earlier.

Fix: apps/api/src/platform/runtime-config.ts now loads VAULT_MASTER_KEK_BASE64, verifies it decodes to exactly 32 non-zero bytes, and refuses to boot in production if it is missing or malformed. Outside production, an ephemeral fallback remains allowed for local convenience, but logs an explicit api.vault_kek_ephemeral warning so no developer mistakes it for durable storage.

2. Connections stored in memory, and what deleting a token really requires (Wave 47, finding P-10)

While tracing the vault key fix, a reviewer discovered that POST /connections encrypted incoming OAuth tokens properly and then saved the encrypted row inside an in-memory JavaScript Map even when PostgreSQL was configured. Restarting the server wiped every connection, and there was no real revoke path.

When Wave 47 wired persistence into vault.oauth_connections over the separate vault database pool (failing closed with 503 VAULT_STORE_NOT_CONFIGURED before spending a single-use step-up token if the vault pool or KEK is missing), the implementing engineer caught a subtle crypto-shredding trap on revoke. Because every connection inside a workspace shares that workspace's DEK, overwriting only a revoked connection row's wrapped_dek column would leave its ciphertext still decryptable with the active workspace DEK.

Fix: Revocation now calls the upstream provider and always overwrites all four cryptographic columns (wrapped_dek, ciphertext, iv, auth_tag), verified by a mutation check that confirms skipping ciphertext causes the revoke test to fail. The engineering report also states the honest database boundary: overwriting live columns destroys the live copy only; PostgreSQL MVCC retains old row versions on disk until VACUUM runs, and older database backups retain whatever ciphertext and wrapped keys were present when the backup was taken until those backups expire.

3. Sample workspaces whose placeholder DEKs refused real connections (Wave 47)

Static SQL seed files for local demo workspaces cannot wrap a workspace DEK under a master key that only exists at runtime, so the seed inserted opaque placeholder bytes into vault.workspace_deks. When developers tried connecting a real test account to a seeded workspace, the vault rejected the row as corrupted (503 VAULT_WORKSPACE_KEY_UNAVAILABLE).

Fix: First, the team locked down an unbreakable safety rule: the API must never silently overwrite an undecryptable workspace DEK, because silently generating a replacement key when a real KEK is merely misconfigured would permanently orphan every existing connection in that workspace. Only a narrow local dev-stack bootstrap path performs a strict compare-and-set matching the exact known seed placeholder bytes, guaranteeing a real workspace key is never overwritten.

4. Moving OAuth token refresh out of the general worker (Wave 48)

OAuth access tokens expire and must be refreshed in the background, which requires both VAULT_DATABASE_URL and VAULT_MASTER_KEK_BASE64. An initial draft placed token refresh inside the general background worker — and immediately collided with a deployment lint test that deliberately forbids any VAULT_* environment variable in the general worker unit.

Rather than relaxing the security rule to give a broad worker access to every customer's vault keys, Wave 48 moved token refresh into a tiny dedicated process, apps/api/src/dispatch-main.ts, running under its own dedicated operating-system user so the general worker cannot even read its environment file. The lesson is foundational: when a job needs a secret, move the job to the smallest process allowed to hold that secret; never widen the secret boundary to match a convenient process.

Try it yourself

Every step below is read-only and safe to run from the repository root in PowerShell or Git Bash. None of these commands touch ports 3000, 4000, or 5432, require PostgreSQL, or contact any external provider.

Step 1: See SHA-256 avalanche and why canonical JSON matters

Run this short Node.js one-liner to compare two objects with identical keys in different orders and watch one changed character scramble a SHA-256 digest:

node -e "const c=require('node:crypto'); const h=(s)=>c.createHash('sha256').update(s).digest('hex'); console.log('a-first:', h('{\"a\":1,\"b\":2}')); console.log('b-first:', h('{\"b\":2,\"a\":1}')); console.log('1-bit:  ', h('{\"a\":1,\"b\":3}'));"

Notice that a-first and b-first produce completely unrelated 64-character hex hashes even though they mean the same thing. That is why packages/approvals/src/canonical-hash.ts sorts keys before hashing.

Step 2: Run the vault envelope, rotation, and log-scrubber test suite

Execute the self-contained vault unit tests to watch AES-256-GCM round-trips, 1-byte tamper rejection, cross-workspace AAD swap blocking, zero-reencryption KEK rotation, and secret-scrubber assertions run live:

node --test packages/vault/test/vault.test.mjs

Look for suites 3, 4, and 5 in the output: suite 3 flips single bytes in ciphertext, IV, tag, and AAD; suite 4 rotates KEK v1 to v2 with zero ciphertexts re-encrypted; and suite 5 checks that tokens, base64 keys, IBANs, and tax numbers never escape into logs or oauth_connections_safe.

Step 3: Run the crypto-shredding and offline audit-bundle verifier tests

Verify that destroying a workspace DEK renders its ciphertexts unreadable, erasure certificates detect tampering, and offline audit bundle verification catches modified or missing rows:

node --test packages/vault/test/crypto-shred.test.mjs packages/vault/test/audit-bundle-verifier.test.mjs

Both suites run purely in memory with zero database setup and prove the mathematical checks behind tools/verify-audit-bundle.mjs and apps/web/src/app/trust/bundle-verify-browser.ts.

Step 4: Inspect the 63-byte wrapped DEK layout and startup KEK validation

Open packages/vault/src/envelope.ts and find WRAPPED_DEK_TOTAL_BYTES, SAFE_AAD_SEGMENT_RE, and validateKey256, then open apps/api/src/platform/runtime-config.ts and find VAULT_MASTER_KEK_BASE64. Trace how the runtime refuses all-zero keys and missing production keys without ever printing the secret value in the thrown error.

Words to know

  • Additional authenticated data
  • AES-256-GCM
  • Audit bundle
  • Audit chain
  • Audit chain checkpoint
  • Audit log
  • Authenticated encryption
  • Authentication tag
  • Canonical JSON
  • Ciphertext transplant
  • Constant-time comparison
  • Crypto-shredding
  • Data encryption key
  • Delimiter injection
  • Dictionary attack
  • Domain separation
  • Dual-key rotation
  • Envelope encryption
  • Ephemeral key
  • Erasure certificate
  • Hash
  • HKDF
  • HMAC
  • Key encryption key
  • Key rotation
  • Key wrapping
  • Nonce
  • Offline verification
  • Raw body
  • Redaction
  • Safe view
  • Sealing
  • SHA-256
  • Vault
  • Vault executor role
  • Zeroisation

Go deeper

  • ADR 0004: Zero-password vault and FORCE RLS — design decision behind the isolated vault schema, envelope encryption, and oauth_connections_safe.
  • ADR 0005: Expiring SHA-256 approval ledger — how canonical JSON hashing binds approval previews to executed actions.
  • Threat model — specifically assets A1–A2, threat T2 (vault credential theft), and gate G2.
  • Archived lesson 14: Cryptography, vault DEK/KEK and audit chains — earlier wave notes replaced by this lesson.
  • Archived lesson 26: Audit retention and assurance — earlier notes on audit retention and bundle verification.
  • Archived lesson 31: Audit chain checkpoints — earlier notes on workspace audit checkpoints.
  • NIST SP 800-38D: Recommendation for Galois/Counter Mode (GCM) — authoritative standard on AES-GCM nonces, tags, and AAD.
  • NIST FIPS 180-4: Secure Hash Standard (SHA-256) — official specification of SHA-256.
  • RFC 2104: HMAC — Keyed-Hashing for Message Authentication — why HMAC uses a two-pass keyed hash construction.
  • RFC 5869: HKDF — HMAC-based Key Derivation Function — deriving domain-separated keys safely.
  • RFC 8785: JSON Canonicalization Scheme (JCS) — deterministic JSON serialisation for cryptographic hashing.
  • Node.js node:crypto documentation — official reference for createCipheriv, createHmac, timingSafeEqual, and randomBytes.
  • MDN Web Crypto API — browser-native crypto.subtle used by the offline audit verifier.

Kendini sına soru özeti ve yanıt anahtarı

Q1. Why is hashing customer e-mails with plain SHA-256 not enough to call a dataset anonymous?

Answer: B

SHA-256 is one-way and deterministic, so A, C, and D are false. Because it is fast and unkeyed, hashing leaked e-mail lists or all +905xxxxxxxxx mobile numbers matches digests quickly, keeping hashed identifiers as personal data under KVKK.

Q2. Why must webhook HMAC checks run on the raw HTTP body instead of JSON.stringify(req.body)?

Answer: B

One changed byte scrambles the entire HMAC digest. Checking the unaltered raw bytes guarantees you verify the exact sequence the sender signed.

Q3. What attack does binding workspaceId:connectionId:provider:kekVersion as AAD in AES-256-GCM stop?

Answer: C

Folding those segments into the 16-byte authentication tag blocks ciphertext transplant attacks: moving bytes to another workspace, connection, provider, or key version makes tag verification throw before returning plaintext.

Q4. Why does rotating the master KEK under envelope encryption avoid re-encrypting stored OAuth tokens?

Answer: A

Rewrapping unwraps each 32-byte DEK with KEK v1 and wraps the exact same DEK under KEK v2, leaving every token ciphertext untouched (ciphertextsReencrypted: 0).

Q5. On per-connection revoke in Wave 47, why was wiping only wrapped_dek insufficient?

Answer: B

Overwriting all four crypto columns (wrapped_dek, ciphertext, iv, auth_tag) destroys the live copy without harming sibling connections, while VACUUM and backup expiry govern historical copies.

Q6. Why did Wave 48 move OAuth token refresh to apps/api/src/dispatch-main.ts instead of giving the general worker the vault key?

Answer: B

Moving the secret-handling job into the smallest isolated process keeps the general worker vault-less instead of relaxing the deployment boundary.

Q7. Why does an exported audit bundle support offline verification?

Answer: B

Local verification via tools/verify-audit-bundle.mjs or browser Web Crypto detects any missing or edited row mathematically with zero network trust.

GetClaps Kurucu Akademisi · Tarayıcı açılışında ağ çağrısı yapılmaz; ilerleme yalnızca cihazındaki yerel depolamada tutulur.