Encryption, secrets and abuse
What encryption in transit, at rest and in the application each stops, envelope encryption with a key service built in C#, secrets and rotation, signed webhooks, the attacks to close, abuse and DoS, and audit and privacy.
ConceptApplied25 min readUpdated
- 4 code samples
- 6 interviewer follow-ups
- 5 self-checks
On this page13 sectionsHLDLLDSenior depth
Read first: Authentication and authorization
- Say what encryption in transit, at rest and in the application each protects against, and what each leaves open.
- Explain envelope encryption, why a key service wraps data keys, and how rotation avoids re-encrypting the data.
- Manage secrets with short-lived credentials, rotation that overlaps, and workload identity.
- Sign and verify webhooks with a timestamp and replay protection.
- Name the attacks a design must close and the layers that defend against abuse and denial of service.
4 code samples (158 lines), collapsed so the explanation stays in focus.
Authentication and authorization decide who gets in. This lesson is about what is left when someone gets in anyway, or watches the wire, or steals a disk, or finds a key in a repository, or simply hammers the front door. The recurring answer is layers, and the recurring mistake is saying "encrypted" as if it were one property. Encryption in transit, at rest and in the application protect against different attackers, and a key that anyone can read protects against none of them. The mechanisms that interviews probe, envelope encryption and signed webhooks, are built and attacked in C# below.
| Layer | Protects against | Does not protect against |
|---|---|---|
| In transit (TLS between client and edge, and between services) | Reading or changing traffic on the network, impersonating a server | Anything after the data arrives, a compromised endpoint |
| At rest, disk or volume | A stolen or discarded disk, a leaked snapshot | A running system: the operating system and the database see plaintext, so a stolen credential reads everything |
| At rest, in the database or object store (transparent data encryption, server-side encryption) | The same media threats, with keys you can manage and audit | A query by anyone who is allowed to query |
| In the application (field-level or envelope encryption) | A database administrator, a stolen backup, a leaked database credential, a cross-tenant query bug | A compromised application, which holds the keys it needs to decrypt |
In transit. TLS (version 1.3 today) gives confidentiality, integrity and server authentication, and with mutual TLS it authenticates the client too. Terminate it at the edge for performance, then re-encrypt to the services behind it: an attacker already inside the network is exactly the case that "internal traffic is trusted" fails. Certificates expire, so automate renewal and alert on days to expiry, because an expired certificate is an outage. A TLS 1.3 handshake costs one round trip, which is part of why terminating it near the user helps (see network performance).
At rest. Encrypting the disk is cheap and should be on everywhere, and it is the weakest of the layers, since the system decrypts for every authorized reader. Whoever holds the database password holds the data. Application-level encryption is the layer that changes the threat model: the application encrypts the sensitive fields before they reach the database, so a database dump, a backup thief or a bug that runs the wrong query returns ciphertext. It costs you the ability to filter, sort or index plaintext: an equality search needs a blind index (a keyed hash of the normalized value, stored beside the ciphertext), and range queries are out of reach.
The words are often confused, and an interview notices.
| Tool | Gives you | Reversible | Use it for |
|---|---|---|---|
| Hash (SHA-256) | A fingerprint of the data | No | Integrity checks, content addressing. For passwords use the slow salted hashes of the previous lesson |
| MAC, HMAC | Integrity and authenticity with a shared secret | No | Signed cookies and webhooks, where both sides hold the secret |
| Digital signature | Integrity, authenticity and non-repudiation with a private key, checked with a public key | No | Tokens verified by many services, software updates, certificates |
| Encryption | Confidentiality, reversible with the key | Yes, with the key | Data that must be read later. Use authenticated encryption (AES-GCM, ChaCha20-Poly1305), which also detects tampering |
| Encoding (base64, hex) | A different representation | Yes, by anyone | Nothing secret. It is not security |
Do not invent cryptography. Use a vetted library, standard algorithms and standard modes, and spend your effort on the key management around them, because that is where real systems fail.
Encrypting everything with one master key has two problems: the key is used everywhere, so its exposure is total and rotating it means re-encrypting all the data, and the key has to live where the data is processed. Envelope encryption splits the work. Each object is encrypted with its own random data key (DEK). The data key is then encrypted ("wrapped") by a key-encryption key (KEK) that lives in a key management service (KMS), usually backed by hardware security modules, and never leaves it. The stored object is the ciphertext plus the wrapped data key. To read it, the application asks the KMS to unwrap the data key, which the KMS allows only to callers it authorizes and logs every time.
Three properties fall out of it. Rotation is cheap: rotating the KEK means unwrapping each small data key and wrapping it again under the new version, while the (large) ciphertext is untouched. Access is auditable and revocable: the KMS logs who decrypted what, and removing a caller's permission cuts access without touching the data. And one compromised data key exposes one object. The sample builds a KMS stand-in and the envelope on AES-GCM, and then tests tampering, context binding and rotation. The context (here the tenant and object id) is bound into the ciphertext as associated data, so a ciphertext copied into another tenant's record does not decrypt.
C# · A stand-in for a key management service: it holds key-encryption keys (KEKs) by version…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
// A stand-in for a key management service: it holds key-encryption keys (KEKs) by version and wraps and unwraps small data keys.
// The KEKs never leave it. Callers hold only wrapped data keys.
public sealed class Kms
{
private readonly Dictionary<int, byte[]> keks = new Dictionary<int, byte[]>();
public int CurrentVersion { get; private set; }
public long WrapCalls, UnwrapCalls;
public Kms() { Rotate(); }
public void Rotate()
{
CurrentVersion++;
keks[CurrentVersion] = RandomNumberGenerator.GetBytes(32); // new data keys use the new version, old ones still unwrap
}
public byte[] Wrap(byte[] dataKey)
{
WrapCalls++;
return Seal(keks[CurrentVersion], dataKey, Array.Empty<byte>(), CurrentVersion);
}
public byte[] Unwrap(byte[] wrapped)
{
UnwrapCalls++;
int version = wrapped[0];
return Open(keks[version], wrapped, Array.Empty<byte>());
}
// version (1 byte) + nonce (12) + tag (16) + ciphertext
public static byte[] Seal(byte[] key, byte[] plaintext, byte[] associatedData, int version)
{
var nonce = RandomNumberGenerator.GetBytes(12); // a fresh random nonce for every encryption
var tag = new byte[16];
var ciphertext = new byte[plaintext.Length];
using var aes = new AesGcm(key, 16);
aes.Encrypt(nonce, plaintext, ciphertext, tag, associatedData);
return new[] { (byte)version }.Concat(nonce).Concat(tag).Concat(ciphertext).ToArray();
}
public static byte[] Open(byte[] key, byte[] sealedBytes, byte[] associatedData)
{
var nonce = sealedBytes.Skip(1).Take(12).ToArray();
var tag = sealedBytes.Skip(13).Take(16).ToArray();
var ciphertext = sealedBytes.Skip(29).ToArray();
var plaintext = new byte[ciphertext.Length];
using var aes = new AesGcm(key, 16);
aes.Decrypt(nonce, ciphertext, tag, plaintext, associatedData); // throws if the data or the context was changed
return plaintext;
}
}
// An encrypted object: the data is encrypted with its own random data key, and the data key is stored wrapped by the KMS.
public sealed record Stored(byte[] WrappedKey, byte[] Ciphertext);
public static class Envelope
{
// `context` (for example the tenant and object id) is bound into the ciphertext: it must be the same to decrypt.
public static Stored Encrypt(byte[] plaintext, byte[] context, Kms kms)
{
var dataKey = RandomNumberGenerator.GetBytes(32);
return new Stored(kms.Wrap(dataKey), Kms.Seal(dataKey, plaintext, context, 0));
}
public static byte[] Decrypt(Stored stored, byte[] context, Kms kms) => Kms.Open(kms.Unwrap(stored.WrappedKey), stored.Ciphertext, context);
// Rotating the master key: unwrap each data key and wrap it again under the current version. The ciphertext is not touched.
public static Stored Rewrap(Stored stored, Kms kms) => new Stored(kms.Wrap(kms.Unwrap(stored.WrappedKey)), stored.Ciphertext);
}C#
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
var kms = new Kms();
byte[] context = Encoding.UTF8.GetBytes("tenant-9/object-42");
var stored = Envelope.Encrypt(Encoding.UTF8.GetBytes("the quarterly numbers"), context, kms);
Debug.Assert(Encoding.UTF8.GetString(Envelope.Decrypt(stored, context, kms)) == "the quarterly numbers");
bool Fails(Action action) { try { action(); return false; } catch (CryptographicException) { return true; } }
var flipped = new Stored(stored.WrappedKey, (byte[])stored.Ciphertext.Clone());
flipped.Ciphertext[40] ^= 1; // one bit of the ciphertext changed
Debug.Assert(Fails(() => Envelope.Decrypt(flipped, context, kms))); // authenticated encryption detects it
Debug.Assert(Fails(() => Envelope.Decrypt(stored, Encoding.UTF8.GetBytes("tenant-3/object-42"), kms))); // the same bytes under another tenant's context
// Rotation: 10,000 objects are encrypted, the master key rotates, and each object's data key is wrapped again.
var objects = Enumerable.Range(0, 10_000).Select(i => Envelope.Encrypt(new byte[64], Encoding.UTF8.GetBytes("o" + i), kms)).ToArray();
kms.Rotate();
long wrapsBefore = kms.WrapCalls, unwrapsBefore = kms.UnwrapCalls;
var rewrapped = objects.Select(o => Envelope.Rewrap(o, kms)).ToArray();
Debug.Assert(kms.WrapCalls - wrapsBefore == 10_000 && kms.UnwrapCalls - unwrapsBefore == 10_000); // one unwrap and one wrap per object
Debug.Assert(objects.All(o => o.WrappedKey[0] == 1) && rewrapped.All(o => o.WrappedKey[0] == 2)); // key version 1 to 2
Debug.Assert(Enumerable.Range(0, 10_000).All(i => ReferenceEquals(objects[i].Ciphertext, rewrapped[i].Ciphertext))); // the data was not touched
Debug.Assert(rewrapped.Sum(o => (long)o.WrappedKey.Length) == 610_000); // 10,000 wrapped keys of 61 bytes
Debug.Assert(Envelope.Decrypt(rewrapped[5], Encoding.UTF8.GetBytes("o5"), kms).Length == 64); // and every object still decrypts
Debug.Assert(Encoding.UTF8.GetString(Envelope.Decrypt(stored, context, kms)) == "the quarterly numbers"); // including one from before the rotationA flipped bit and a ciphertext moved to another tenant both failed to decrypt, because GCM authenticates the data and the context together. Rotating the master key for 10,000 objects touched 610,000 bytes of wrapped keys (10,000 small unwrap and wrap calls). Had the data itself been encrypted under the master key, rotation would have meant reading, re-encrypting and rewriting every object: with 1 MB objects that is 10 GB of I/O and a window in which two keys are live. Notes for real use:
- Never reuse a nonce with the same key. With AES-GCM it is catastrophic: it leaks the XOR of plaintexts and lets an attacker forge messages. Random 96-bit nonces are safe only for a limited number of messages per key (NIST allows at most 2^32), which is one more reason for a data key per object.
- The KMS is a dependency with latency, quotas and an availability of its own. Callers cache unwrapped data keys briefly, in memory, and a KMS outage must degrade reads of cold data, not everything.
- Separate duties. The people who administer keys should not be the ones who can use them to read data, and every use is logged.
- Crypto-shredding. If each tenant or user has its own key, deleting the key makes all of their data unreadable everywhere, including backups, replicas and derived copies that you cannot find one by one. That makes "delete my data" tractable, and it is the reason to design key hierarchy with deletion in mind.
A secret is anything that grants access: passwords, API keys, tokens, private keys, signing keys, database credentials. They leak through repositories (including history), container images, build logs, environment dumps in error reports, chat messages and support tickets. The design questions are where they live, how long they are valid and how they are replaced.
- A secrets manager, not files and not environment variables in the image. Applications fetch secrets at start-up or on demand from a service with access control and an audit trail.
- Prefer identity to secrets. A workload that proves who it is (a cloud role, a Kubernetes service account, a SPIFFE identity) receives short-lived credentials automatically, and then there is no long-lived key to steal. The last remaining secret is the bootstrap one, so make it an identity and not a password.
- Short-lived and dynamic. Credentials issued per instance with a time to live (a database user created for an hour) limit what a leak is worth.
- Rotation must overlap. A secret that changes at one instant breaks every client that has not caught up. Accept both the old and the new value during a window, then retire the old one: the webhook verifier below takes a list of secrets for exactly this.
- Scope and least privilege. A key that can only read one bucket is a small incident. A key that can do anything is a large one.
- Detect and plan. Scan repositories and logs for secrets, and have a runbook for "this key leaked": revoke it, rotate it, find where it was used (the audit log), and assume it was used.
A webhook is your system calling someone else's endpoint, or theirs calling yours, so the receiver must answer two questions: did this really come from the sender, and is it a fresh message and not a replay of an old one? The standard answer is an HMAC signature over a timestamp and the body, with a shared secret, sent in a header. The receiver recomputes it and compares in constant time, rejects timestamps outside a small tolerance (so a captured request cannot be replayed later), and remembers event ids (so it cannot be replayed within the window). During secret rotation the header carries several signatures and the receiver accepts any that match. For many receivers, an asymmetric signature (the sender signs with a private key and publishes the public key) avoids distributing a shared secret at all.
C# · HookResult, WebhookVerifier
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
public enum HookResult { Accepted, BadSignature, TooOld, Replay, Malformed }
// Verifying a signed webhook. The sender sends "Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of 't.body'>", possibly with several
// v1 values while a secret is being rotated.
public sealed class WebhookVerifier
{
private readonly byte[][] secrets;
private readonly int toleranceSeconds;
private readonly HashSet<string> seenEvents = new HashSet<string>();
public WebhookVerifier(int toleranceSeconds, params string[] secrets)
{
this.toleranceSeconds = toleranceSeconds;
this.secrets = secrets.Select(Encoding.UTF8.GetBytes).ToArray();
}
public static string Sign(string secret, long timestamp, string body) =>
Convert.ToHexString(HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes(timestamp + "." + body))).ToLowerInvariant();
public HookResult Verify(string header, string body, string eventId, long now)
{
var fields = header.Split(',').Select(p => p.Split('=', 2)).Where(p => p.Length == 2).ToList();
var timestamp = fields.FirstOrDefault(p => p[0] == "t");
if (timestamp == null || !long.TryParse(timestamp[1], out long sentAt)) return HookResult.Malformed;
var signatures = fields.Where(p => p[0] == "v1").Select(p => p[1]).ToList();
byte[] signed = Encoding.UTF8.GetBytes(sentAt + "." + body);
bool genuine = secrets.Any(secret => signatures.Any(sig =>
sig.Length == 64 && CryptographicOperations.FixedTimeEquals(HMACSHA256.HashData(secret, signed), Convert.FromHexString(sig)))); // constant-time comparison
if (!genuine) return HookResult.BadSignature;
if (Math.Abs(now - sentAt) > toleranceSeconds) return HookResult.TooOld; // a captured request cannot be replayed later
if (!seenEvents.Add(eventId)) return HookResult.Replay; // ...nor twice within the window
return HookResult.Accepted;
}
}C#
using System;
using System.Diagnostics;
long now = 1_700_000_000;
string body = "{\"id\":\"evt_1\",\"type\":\"payment.succeeded\",\"amount\":5000}";
string Header(string secret, long t, string b) => "t=" + t + ",v1=" + WebhookVerifier.Sign(secret, t, b);
var verifier = new WebhookVerifier(300, "whsec_new", "whsec_old"); // two secrets are valid during a rotation
Debug.Assert(verifier.Verify(Header("whsec_new", now, body), body, "evt_1", now) == HookResult.Accepted);
Debug.Assert(verifier.Verify(Header("whsec_new", now, body), body, "evt_1", now + 10) == HookResult.Replay); // the same event again
Debug.Assert(verifier.Verify(Header("whsec_new", now, body), body.Replace("5000", "9999"), "evt_2", now) == HookResult.BadSignature); // body changed
Debug.Assert(verifier.Verify(Header("whsec_guess", now, body), body, "evt_3", now) == HookResult.BadSignature); // wrong secret
Debug.Assert(verifier.Verify(Header("whsec_old", now, body), body, "evt_4", now) == HookResult.Accepted); // the old secret, during rotation
Debug.Assert(verifier.Verify(Header("whsec_new", now, body), body, "evt_5", now + 3_600) == HookResult.TooOld); // captured and resent an hour later
Debug.Assert(verifier.Verify("t=" + (now + 3_600) + ",v1=" + WebhookVerifier.Sign("whsec_new", now, body), body, "evt_6", now + 3_600) == HookResult.BadSignature); // timestamp rewritten
Debug.Assert(verifier.Verify("garbage", body, "evt_7", now) == HookResult.Malformed);| Request | Result | Why |
|---|---|---|
| A genuine event | Accepted | Signature, timestamp and event id all check out |
| The same event again | Replay | The event id was already seen |
| The body changed after signing | Bad signature | The HMAC covers the body |
| Signed with a guessed secret | Bad signature | The attacker does not have the secret |
| Signed with the old secret during a rotation | Accepted | Both secrets are valid for the overlap |
| A captured request resent an hour later | Too old | Outside the 300-second tolerance |
| The attacker rewrites the timestamp to look fresh | Bad signature | The timestamp is part of the signed text |
| No usable header | Malformed | Refused before any work |
Details that matter: sign the raw bytes of the body, not a re-serialized copy, and put the timestamp inside the signed text (so it cannot be edited separately). The check must be constant-time, because a comparison that stops at the first differing byte leaks the signature one byte at a time to an attacker who measures. Processing must also be idempotent (see API design), since a verified event is still delivered at least once. The same pattern, as AWS Signature Version 4 or an HMAC header, signs requests to an API.
A design review should be able to say, for each of these, where it is closed.
| Attack | What happens | Defence |
|---|---|---|
| Injection (SQL, command, NoSQL, LDAP) | Input is interpreted as code or a query | Parameterized queries and safe APIs, never string concatenation, least-privilege database accounts |
| Cross-site scripting | A script runs in another user's browser, and can read what that page can | Context-aware output encoding, a Content Security Policy, HttpOnly cookies |
| Cross-site request forgery | A page makes the user's browser send an authenticated request | SameSite cookies, anti-forgery tokens on state-changing requests |
| Server-side request forgery (SSRF) | The server fetches a URL the attacker chose: your internal services, the cloud metadata endpoint with its credentials | Allow-list destinations, resolve the name and refuse private, loopback and link-local addresses (and recheck after redirects and DNS changes), no redirects, egress filtering, a metadata service that needs a token |
| Mass assignment and over-posting | A request sets fields it should not (isAdmin) | Allow-list the fields a request may set, separate input and storage models |
| Path traversal | ../../etc/passwd escapes the intended directory | Canonicalize and check the path, or use opaque ids, not names |
| Unsafe deserialization | An object stream runs code on load | Do not deserialize untrusted data into rich types, use plain data formats |
| Open redirect | A trusted URL sends users to an attacker's site, or leaks OAuth codes | Allow-list redirect targets, exact-match registered URIs |
| Vulnerable dependencies | A library you ship has a known hole | An inventory (SBOM), scanning, pinned and verified dependencies, prompt updates |
The pattern across the rows: treat all input as hostile, keep data separate from instructions, give each component the least power, and add a second layer so that one missed check is not a breach.
Some attackers never break in. They use what is offered, at a scale that hurts. Defend in layers, cheapest first.
- Volumetric attacks (floods of packets and connections) are absorbed at the edge by a CDN or a scrubbing service on anycast, spread over a large fleet. Your servers must never see them (see DNS, CDNs and the edge).
- Application-layer attacks look like legitimate requests. Limit per identity, address and tenant (the algorithms are in the rate limiting lesson), charge expensive endpoints more tokens than cheap ones, challenge suspicious clients, and shed unauthenticated and low-priority traffic first so that paying users keep working (see tail latency and overload).
- Resource exhaustion by one request: slow connections that never finish (set timeouts), enormous bodies and decompression bombs (size limits), pathological regular expressions and algorithmic worst cases (linear-time engines, input limits), unbounded queries (page size and cost limits).
- Denial of wallet. Autoscaling and pay-per-request services turn an attack into a bill. Autoscaling absorbs a flood by spending money, so cap it, alert on cost, and limit upstream of the metered resource.
- Feature abuse: fake sign-ups, promotion abuse, scraping, spam, and fraud such as SMS pumping (see the notification lesson). Defences are friction where it is cheap for honest users (verification, quotas, delays), signals that raise the attacker's cost (device and behaviour checks), and limits tied to value, such as a cap on messages to new numbers.
Plan for graceful degradation: decide in advance what you turn off first when under attack (search, exports, anonymous traffic), because that decision is better made on a calm day.
Audit logs answer "who did what, when, to which object, from where, and did it work", for the events that matter: logins and failures, permission changes, administrator actions, exports, and reads of sensitive records. They go to a separate, append-only store that the actors being recorded cannot edit (a compromised administrator must not be able to erase their trail), with a retention period and alerts on anomalies. Application logs must not carry secrets or personal data (see observability).
Privacy by design starts by collecting less: data you never stored cannot leak. Then purpose limits (use it for what it was collected for), access controls, a retention schedule with automatic deletion, and a plan for erasure requests that reaches every copy: caches, search indexes, analytics tables, logs and backups, which is where per-user keys and crypto-shredding earn their cost. Regulations such as the GDPR add rights to access and delete data and a duty to notify the regulator of a breach within a short deadline (72 hours, where feasible); legal review decides what applies to you. For payments, do not store card numbers: use a processor's hosted fields and tokens, which keeps most of your systems out of PCI scope. SOC 2 and ISO 27001 are audits of whether your controls exist and operate, and a design that can show its access reviews, change history and key usage passes them more easily.
| Failure | What goes wrong | Defence |
|---|---|---|
| Encryption without key control | Keys sit beside the data, or one key does everything | A KMS, data keys per object, separated duties, audited use |
| Nonce reuse with AES-GCM | Plaintexts leak and messages can be forged | Random nonces with a bounded count per key, a data key per object, a vetted library |
| A KMS outage | Nothing can be decrypted, or everything fails open | Cached data keys, graceful degradation, no fallback to unencrypted |
| A leaked secret | Anyone holding it has the access, possibly for months | Short-lived credentials, scanning, a rotate-and-investigate runbook |
| Rotation without overlap | A secret that changes at one instant breaks every client | Accept old and new together for a window |
| Unsigned or unchecked webhooks | Anyone can post fake events, captured ones can be replayed | HMAC over timestamp and body, constant-time compare, event ids |
| SSRF to the metadata service | The server hands out its own cloud credentials | Destination allow-lists, private-range checks, a token-protected metadata service |
| Logging secrets and personal data | The log store becomes the breach | Redaction in the logging library, restricted access, short retention |
| Denial of wallet | An attack becomes a huge bill | Caps, cost alerts, limits upstream of metered resources |
| Erasure that misses copies | "Deleted" data lives on in backups and indexes | A data map, per-user keys and crypto-shredding, deletion pipelines |
Interviewer follow-upL5What is the difference between encryption in transit and at rest, and what does each protect against?How to answer
In transit (TLS) stops anyone on the network from reading or altering traffic and impersonating the server. At rest (disk or database encryption) protects stolen media, snapshots and discarded disks. Neither helps against a stolen application credential or a compromised service, because the system decrypts for authorized readers. Application-level encryption of sensitive fields is what protects against a database administrator, a stolen backup or a leaked database login.
Interviewer follow-upL5What is the difference between hashing, encryption and signing?How to answer
A hash is a one-way fingerprint, with no key: for integrity checks, or with salt and cost for passwords. Encryption is reversible with a key and hides the data (use authenticated encryption so tampering is detected). A signature or MAC proves who produced the data and that it was not changed: an HMAC with a shared secret, or a signature with a private key that anyone can verify with the public key. Base64 is none of these.
Interviewer follow-upL6How does envelope encryption work, and why use it?How to answer
Each object is encrypted with its own random data key, and the data key is wrapped by a key-encryption key held in a KMS, which never gives the master key out and logs every use. You store the ciphertext and the wrapped key. Rotating the master key re-wraps small data keys and leaves the data alone (610,000 bytes of keys against 10 GB of data for 10,000 objects of 1 MB in the test), one leaked data key exposes one object, and deleting a tenant's key makes its data unreadable everywhere.
Interviewer follow-upL6How do you secure the endpoint that receives webhooks?How to answer
Verify an HMAC over the timestamp and the raw body with the shared secret, compared in constant time. Reject timestamps outside a few minutes so captured requests cannot be replayed, and remember event ids to catch replays inside the window. Accept two secrets during rotation, process events idempotently, and answer quickly (queue the work). All eight cases passed in the test, including the attacker who rewrites the timestamp, which is part of the signed text.
Interviewer follow-upL6An API key was committed to a public repository. What do you do?How to answer
Treat it as compromised from the moment it was pushed: revoke or rotate it immediately, do not just delete the commit, since it is in history and in forks and scraped within minutes. Check the audit log for use of that key, assess what it could reach and what was accessed, notify affected parties as required, and fix the cause: secret scanning in CI and pre-commit, short-lived credentials and workload identity instead of long-lived keys, and least-privilege scopes so the next leak is small.
Interviewer follow-upL7An API is being scraped and attacked at a hundred times its normal traffic. How do you respond?How to answer
Absorb volumetric traffic at the CDN and edge, then tell good from bad: rate-limit per identity, address and tenant with limits that cost expensive endpoints more, challenge or block clients with automated patterns, and shed unauthenticated and low-priority traffic first so paying users keep working. Cap autoscaling and watch cost (denial of wallet), protect the database with load shedding, and cache. Afterwards, close the abuse path (a cheaper endpoint, a quota, a verification step) and keep the controls on, because the attacker will return.
Walk the layers and say what each stops. TLS on every hop with mutual TLS between services, and automated certificates. Disk and database encryption everywhere, application-level envelope encryption for the data that would hurt most, with a data key per object and a KMS that audits every use, and per-tenant keys where deletion matters. Secrets come from a secrets manager or, better, from workload identity, short-lived and rotated with overlap. Webhooks are signed with a timestamp and checked in constant time. Name the attacks you closed (injection, SSRF, request forgery) and the abuse layers (edge, per-identity limits, shedding), and finish with audit logs that the actors cannot edit.
Encryption in transit stops network attackers, disk and database encryption stop stolen media, and only application-level encryption protects against a stolen database credential or a database administrator, at the cost of querying. Use authenticated encryption and never reuse a nonce. Envelope encryption encrypts each object with its own data key wrapped by a key-encryption key in a KMS: in the test a flipped bit and a ciphertext moved to another tenant both failed to decrypt, and rotating the master key for 10,000 objects touched 610,000 bytes of wrapped keys where re-encrypting 1 MB objects would be 10 GB. Per-tenant keys make deletion tractable by crypto-shredding. Secrets come from a manager or, better, from workload identity, are short-lived, scoped and rotated with overlap, and a leak is handled by revoking, investigating and fixing the cause. Webhooks are verified by an HMAC over timestamp and raw body in constant time, with a time tolerance, event ids and two secrets during rotation, and all eight cases in the test behaved. Close the classic attacks (injection, XSS, CSRF, SSRF, mass assignment, deserialization), defend against abuse in layers from the edge to per-identity limits and load shedding, watch for denial of wallet, and keep audit logs the actors cannot edit and a privacy design that reaches every copy of the data.
Try answering out loud before you reveal each answer.
QuestionA company encrypts its database disks and says its customer data is protected. Against which attacks is that true, and which does it leave open?Reveal answer
True against a stolen disk, a discarded drive or a leaked snapshot. It does nothing against a stolen application credential, a database administrator, SQL injection or a cross-tenant bug, because the running system decrypts for every authorized reader. For those, encrypt sensitive fields in the application, with keys the database does not hold, and limit who can use them.
QuestionWhy store a wrapped data key next to each object instead of encrypting everything with the master key?Reveal answer
Rotation re-wraps small keys instead of rewriting all the data (610,000 bytes against 10 GB for 10,000 objects of 1 MB), the master key never leaves the KMS and each use is logged, a compromised data key exposes one object, and a key per tenant allows deleting that tenant's data by deleting its key. It also keeps the number of encryptions per key low, which matters for AES-GCM's nonce limit.
QuestionA webhook request is captured on the wire and sent again an hour later. What stops it, and what stops it from being sent twice within a minute?Reveal answer
The timestamp is part of the signed text, so the attacker cannot make it look fresh, and the receiver rejects timestamps outside a tolerance (300 seconds in the test: too old). Within the window the receiver remembers event ids and answers replay for a repeat. Both protections are needed, and the handler must still be idempotent because genuine deliveries repeat.
QuestionA feature fetches a URL that a user supplies, to build a preview. What is the risk, and how do you defend?Reveal answer
Server-side request forgery: the user points the server at an internal service or the cloud metadata endpoint and reads credentials or internal data. Allow-list destinations if you can, resolve the name and refuse private, loopback and link-local addresses (and recheck after redirects and DNS changes), do not follow redirects blindly, filter egress at the network, and use a metadata service that requires a token.
QuestionAn attack multiplies your traffic by 100 and your autoscaler happily follows it. What went wrong, and what do you change?Reveal answer
Autoscaling turned a denial-of-service attack into a denial of wallet, and the database behind it probably fell over anyway. Absorb floods at the edge, limit per identity and charge expensive endpoints more, shed unauthenticated and low-priority traffic first, cap scaling and alert on spend, and protect the stateful layer with load shedding.
- NIST, Special Publication 800-38D, Galois/Counter Mode (GCM) (opens in a new tab): the nonce rules and the limit on messages per key.
- OWASP, Cryptographic Storage (opens in a new tab), Secrets Management (opens in a new tab) and Server-Side Request Forgery Prevention (opens in a new tab) cheat sheets.
- Amazon Web Services, AWS KMS concepts: envelope encryption (opens in a new tab): the wrapped data key pattern, with a managed key service.
- Stripe, Check the webhook signatures (opens in a new tab): a widely copied design with a timestamp, a tolerance and multiple signatures for rotation.
- IETF, RFC 8446, TLS 1.3 (opens in a new tab): the handshake and what the protocol protects.