Study guide · System design

Study guide: security and privacy

Map threats and trust boundaries, control access, protect data across its life cycle, and verify security and privacy decisions.

Contents
  1. ·Learning objectives
  2. §1Core concepts
  3. §2Map assets, flows, and trust boundaries
  4. §3Establish identity and enforce authorization
  5. §4Protect data through its life cycle
  6. §5Validate input and limit abuse
  7. §6Make sensitive actions explainable
  8. §7Verify controls and revisit trade-offs
  9. ·Common mistakes
  10. ·Practice questions
  11. ·Review checklist

· · Start here

Learning objectives

  1. Explain how security and privacy requirements differ and where they affect a system design.
  2. Map sensitive assets, data flows, trust boundaries, and likely threats before choosing controls.
  3. Distinguish authentication from authorization and design access checks for users, services, and individual resources.
  4. Protect personal and confidential data across collection, processing, storage, sharing, backup, and deletion.
  5. Choose defenses against malformed input, injection, automated abuse, and overloaded shared resources.
  6. Design audit records and incident signals that support investigation without exposing secrets or unnecessary personal data.
  7. Trace each important risk to a design control and a test that can show whether the control works.

§1 · Definitions

Core concepts

This section defines security, privacy, and the boundaries that make their requirements concrete in a distributed system.

Security asks whether an actor can do something harmful; privacy also asks whether a permitted use of personal data is appropriate and limited. Encryption can protect a database from disclosure, but it does not justify collecting an unnecessary field or keeping it indefinitely. Conversely, collecting little data reduces exposure but does not stop someone with a stolen session from reading what remains. Both concerns must be expressed as requirements for named journeys, stores, and operators.

The same data can create several different risks. An order address can be stolen by an outside attacker, seen by an employee whose role does not require it, sent to an analytics provider without a suitable purpose, or retained in a backup longer than intended. Encryption addresses some routes to disclosure; access policy, collecting only needed data, recipient limits, and retention address others. A design should name the actor, action, asset, and boundary for each risk before selecting a control. Otherwise a familiar control can be applied to the wrong failure mode.

Security covers confidentiality, integrity, and availability. A read of another person's record breaches confidentiality. A changed refund amount breaches integrity. A flood of expensive requests can make checkout unavailable. Privacy can be harmed without an attacker or broken system: a team may collect precise location when a coarse region would serve the purpose, or reuse purchase history for an unexpected analysis. This is why privacy review includes ordinary authorized processing, not only unauthorized access.

Controls do not remove all risk. A service that encrypts records at rest still decrypts them for legitimate requests. A person or process with that authority may misuse it, and a bug in the access check may expose the plaintext. Record the residual risk and decide whether a second measure, such as narrower privileges, a separate approval, or a limited retention period, is justified. The cost of a control matters too: a remote policy check can improve consistency but add latency and a failure dependency. The choice should be tied to the harm it reduces and the behavior it changes.

The common confusion is to treat security and privacy as a checklist appended after the architecture. Component boundaries, identity propagation, data copies, and retention choices determine what can be protected later. A design review therefore starts with the assets and flows, then tests each proposed control against a specific risk.

§2 · Threat modeling

Map assets, flows, and trust boundaries

Start with a user journey and draw the data it moves. A customer viewing an order may cross a browser-to-edge boundary, an edge-to-service boundary, and a service-to-database boundary. A background worker and a support console create additional paths to the same record. Mark where identity is established, where permission to read or change an order is checked, where sensitive fields are copied, and which outside services receive them. The diagram should include logs, queues, backups, exports, and administrative tools when they carry the same data.

The diagram shows a simplified order-read path and its secondary copies.

System flow
Customer browser ──encrypted channel──→ Edge/API ──authenticated call──→ Order service ──→ Order store
                           │                 │                     │
                           │                 ├──→ Audit events     └──→ Backup
                           └──→ Request logs └──→ Support console access

Read each arrow as a point where a request or data copy needs an explicit owner and policy. The browser is outside the service's trust boundary; a support console is another entry point, not automatically a trusted exception. OWASP's Threat Modeling Cheat Sheet uses data flows and trust boundaries to find risks that a component diagram alone can miss.

For each asset, ask how a caller could impersonate an owner, change a record, read another customer's record, exhaust a shared resource, or bypass a workflow. Rank risks by likely impact and exposure, then record the control and evidence needed for each. A threat model is revised when a new integration, data copy, or privilege changes the boundary; it is not a one-time drawing.

Follow the data, not only the request

A diagram of servers alone does not show where information goes. The order service may write an event to a queue, a worker may copy part of it into an email, and a support export may create a downloadable file. Each copy gains its own access path, retention period, and possible disclosure route. Trace the forward path from collection to recipient and the reverse path from a deletion or correction request to every stored copy. Include caches, diagnostic logs, backups, and test environments when they contain real data. A boundary can sit inside one organization if two teams or services have different authority.

For each crossing, record the format of the data, the identity of the caller, the policy enforced by the receiver, and the result if the call fails. An encrypted channel protects a network hop but does not prove that the receiving service is permitted to retain or republish the data. An internal service name does not prove the user's authority to read a particular record. The receiver should validate the claims it relies on and limit what it returns. This inventory also reveals forgotten paths such as support dashboards that query production data directly.

Turn a plausible misuse into a testable claim

An abuse case is more useful than a vague label such as “data leak.” Consider a signed-in customer who changes an order ID in a URL, or a support agent who requests a bulk export outside their assigned scope. The sequence identifies the entry point, the resource, the authority claimed, and the result that must be denied or constrained. A corresponding test can submit the request and inspect both the response and any side effect. A denied response is insufficient if a background job still created an export file.

Prioritization should consider harm, exposure, and the feasibility of misuse without pretending that a single numeric score is exact. A public endpoint accepting arbitrary order IDs is easier to probe than a tool restricted to a small operations group, but the operations tool may expose more records per use. Rank the risks that would change the architecture or data policy first. Record why a risk is accepted, reduced, or deferred, and revisit that choice when a new feature changes the number of users, the data fields, or the trust boundary.

A threat model should record assumptions that could invalidate its conclusions. A design may assume that only the export service can write a file, that a provider deletes data on request, or that a cache key includes tenant identity. Turn each important assumption into a configuration check, contract check, or test. If the assumption cannot be verified, treat it as a residual risk rather than quietly relying on it. This is particularly useful for shared infrastructure: two services in the same network may still need distinct identities and permissions because a compromise of one should not grant the other's authority.

Worked exampletrace a new export path

Consider an online shop that adds a support export of order records. Assume support agents may view orders assigned to their queue, but the new export endpoint initially accepts any customer ID. The asset is order history; the added flow is agent → support console → export API → order store → file store → download link. The first missing decision is whether the agent may export that customer's orders; a successful console login does not establish it. The second is whether the export contains only fields needed for support. The third is who may open the file and when it expires. Test with an assigned and an unassigned customer, then inspect the file store to confirm that the denied attempt left no downloadable artifact. Finally, use an authorized export and verify that a record of the export captures the actor, scope, result, and expiry without copying the exported orders into that record.

Worked examplefind the missing access path

Consider an order API where the customer endpoint checks ownership before returning an order. Assume a support console reads the same order store through a separate endpoint. The asset is the customer's order history. The first path is customer → API → ownership check → store; the second is support agent → console → support API → store. Protecting only the first path leaves the second path able to bypass customer checks. The design needs a support-specific permission, a reason for access where appropriate, and an audit event for the read. Check by testing both paths with an authorized user and an unauthorized user; the result must depend on the requested order and the caller's authority, not merely on a successful login.

§3 · Identity and access

Establish identity and enforce authorization

An authenticated customer is not thereby authorized to read every order. The access decision must combine principal, action, and resource: “customer 12 may read order 86 because order 86 belongs to customer 12.” Checking only a role or trusting an order identifier supplied by the client leaves object-level access unprotected. Enforce the decision at a consistent server-side boundary on every relevant request, including administrative endpoints, background jobs, and alternate API paths. OWASP's Authorization Cheat Sheet recommends deny-by-default behavior and permission checks on each request.

Evaluate the action on the actual resource

An access rule needs enough context to decide the requested action. “Customer” and “support agent” are useful broad roles, but neither alone determines whether a particular order can be read, edited, refunded, or exported. The server should load the target's owner, tenant, status, and any assignment needed by the rule, then decide before returning data or starting a side effect. A list endpoint needs the same policy: filtering a page of results after an unrestricted database query may expose counts, metadata, or data in logs before the filter runs. Enforce the constraint in the query or at a boundary that cannot return unauthorized rows.

Tenant isolation can be enforced with separate stores, database policy, application checks, or a combination. In every design, the tenant identity used for authorization must come from trusted server-side context rather than a freely editable request field. A caller can supply an order ID, but it cannot supply proof that the order belongs to its tenant by placing a tenant ID in the same URL. Test direct reads, list queries, bulk jobs, exports, search indexes, and cache keys with cross-tenant identifiers. A cache key that omits tenant scope can return a correct response for the wrong tenant even when the database query was protected.

Keep service authority distinct from user authority

A receipt worker may read customer contact details to send a receipt, but that does not let any caller ask it to send arbitrary records. The worker should receive a narrowly scoped job tied to an authorized order and verify the order's current state before acting. Similarly, an API that calls a powerful reporting service must not turn an untrusted report ID into an unrestricted database export. Carry the end user's identity only when the downstream decision needs it, authenticate the calling service separately, and state which authority each step exercises. This prevents the service's broad access from silently becoming the user's access.

Permission changes have timing consequences. If a support agent loses export permission, a queued export started before revocation may still run unless the worker rechecks authority or the job is canceled. For short operations, checking at admission may be sufficient under a stated policy; for long or sensitive work, recheck before producing or releasing the artifact. Record the principal and policy context used for the decision so an audit can explain why the action was allowed. If a remote policy service is unavailable, use an explicit failure rule that preserves the required security guarantee rather than treating a timeout as approval.

For service-to-service calls, propagate identity only when a downstream service needs it and distinguish the calling service's authority from the end user's authority. Give a worker that sends receipts permission to read the fields it needs, not broad access to all customer records. If a permission decision depends on a remote policy service, define what happens when that service is unavailable; a timeout must not silently become permission to proceed.

Session design affects revocation and exposure. An opaque server-side session can be invalidated centrally; a signed self-contained token can be checked locally but may remain usable until expiry unless a revocation mechanism is added. Protect session credentials in transit and storage, set appropriate lifetimes, and rotate or revoke them after account compromise. A signed token is evidence of claims, not evidence that the request is authorized for every resource. Sensitive actions may require fresh authentication or an additional factor, according to their risk.

Protect the session after login

A session token is a bearer credential: anyone who obtains a usable copy may be able to act as the session until it expires or is revoked. Generate unpredictable identifiers, send them only over encrypted connections, and avoid placing them in URLs where browser history, logs, or referrer information can expose them. For a browser session carried by a cookie, the Secure attribute restricts sending it to encrypted connections, HttpOnly blocks ordinary page script from reading it, and an explicit SameSite policy limits some cross-site sending. These attributes address different risks and do not replace server-side authorization or protection against injected script. OWASP's Session Management Cheat Sheet describes these controls and their limits.

Rotate the session identifier when authentication or privilege level changes so an identifier chosen or observed before login does not become a high-privilege credential. Enforce idle and absolute lifetimes on the server, and invalidate the server-side session on logout or compromise. Deleting a browser cookie alone does not invalidate a stolen copy already in another client's hands. A self-contained signed token needs a different revocation plan, such as short expiry or a server-checked status for sensitive operations. The plan should state how quickly a disabled account or withdrawn privilege stops working across every service.

Protect account recovery as an access path

Resetting a password, changing a contact address, or recovering an account can grant control as surely as a normal login. The recovery path needs its own threat model: who can start it, what evidence is required, how often attempts are allowed, and which existing sessions or credentials remain valid afterward. An email link should be short-lived, bound to the intended account and action, and unusable after completion. Avoid revealing whether an account exists through response wording or timing where that disclosure matters. A successful recovery should create an audit event and notify the account through an appropriate independent channel so misuse can be noticed.

Additional authentication factors help only if the fallback path is not easier to abuse than the normal path. A strong sign-in flow followed by a weak support override leaves the support tool as the practical entry point. Support staff should not be able to bypass the account holder's protections without a narrow, recorded process. Test recovery with an expired link, a reused link, a link for another account, and an account whose privileges changed during the flow. The checks should cover the final state and any surviving sessions, not just the reset form's response.

Worked examplean authorized list and a forbidden item

Consider customer A, whose authenticated session belongs to tenant T1. Assume order 101 belongs to T1 and order 202 belongs to tenant T2. A request for GET /orders/101 can pass when the policy permits A to read that order; GET /orders/202 must be denied even though the identifier is well formed and A is signed in. Now consider GET /orders?status=open. The query must constrain results to T1 before returning the page; filtering only the two visible rows after a global count would still reveal information about T2. Check the policy with three cases: A's own item is returned, T2's item is not returned, and the list's rows and count describe only T1. Repeat through export and search endpoints because those paths may use different queries.

The diagram shows the decision sequence for one protected operation.

System flow
Request → authenticate principal → load target resource → authorize action on target
                                                           │
                                               allow → perform action
                                               deny  → return safe error

The target resource must be considered before the authorization decision. A policy that checks only whether the caller has an “order reader” role cannot distinguish the caller's order from another customer's order. The result should be tested for both permitted and forbidden resource identifiers.

§4 · Data protection

Protect data through its life cycle

For each data field, identify its purpose, the services that need it, every copy, and its deletion rule. A hosted payment flow, for example, can keep card details out of the shop's system altogether. A shipping address may be needed to fulfil an order but not in request logs or analytics events. Pseudonymous identifiers can support correlation without copying a full address, though they may still be personal data if re-identification remains possible. The ICO's data minimisation guidance expresses the principle as collecting data adequate and relevant to a purpose, and limited to what is necessary.

Specify a purpose for each field and copy

Data minimization begins before an input form is built. State what decision or service each field supports, whether a less precise value would suffice, and whether the system can avoid collecting it altogether. A delivery service may need a full address until fulfillment; a regional sales chart may need only a region. Keeping the full address in analytics because it is already available creates a new exposure without improving the chart. When a field has several purposes, distinguish the copies and lifetimes needed for each. A purpose statement also helps decide whether a later feature is a compatible use or needs a new design decision.

Data lineage makes deletion and correction possible to reason about. An account name may appear in a primary table, a search index, an email provider, a support export, and a backup. Changing the primary row does not necessarily update the other copies. Trace each derived field to its source and record whether it is rebuilt, updated, or retired when the source changes. A test record with a unique marker can reveal unexpected copies in a controlled environment, but production data should not be copied into test systems merely to make that search easier.

Pseudonymization changes how readily a record identifies a person; it does not automatically make the record anonymous. A stable identifier can be linked with other records, and the mapping may be held by another service. If the system can re-identify the person, treat the record according to the relevant personal-data policy. Aggregation can reduce the need for individual records, but small groups or detailed dimensions may still reveal an individual. Choose the least detailed representation that supports the decision, then test the access and retention rules on the derived output as well as the original.

Include recipients outside the service

A third-party processor, email provider, analytics service, or support vendor becomes another recipient in the data map. Specify which fields it receives, why it needs them, whether it can retain or combine them, and how corrections or deletion requests reach it. A contract or configuration may restrict use, but the system still needs a technical path that sends only the intended fields. Test the outbound payload, not merely the internal object from which it was built; serialization or default logging can add fields unexpectedly. If a provider is replaced, account for data already held by the old provider and the keys or credentials that allowed access.

Sharing can be reduced by moving computation. A service may send a short-lived reference that lets a recipient fetch only the record it needs, or it may aggregate results before transfer. Each alternative has its own trust boundary: a reference can be forwarded, a fetch endpoint needs authorization, and an aggregate can still reveal information when groups are small. Choose based on the recipient's actual task and test the result for overbroad fields and unintended reuse. A privacy claim should describe the recipient's view, not only the sender's intention.

The data-life-cycle diagram makes secondary copies visible.

System flow
Collect → process → primary store → derived views / exports
                       │                    │
                       ├──→ backups         └──→ downstream recipients
                       └──→ logs and traces
                    retention or deletion decision for every branch

Read the branches as separate retention and access obligations. Deleting a row from the primary store does not automatically delete an export, a cache, a backup, or a log line. Some copies may need a different deletion method or a documented expiry; a requirement to erase data must name the systems in scope and the expected completion window. Legal and contractual retention requirements vary, so choose periods for the actual context rather than copying a generic number.

Design deletion as a distributed operation

A deletion request needs an owner and a completion rule. The primary store may delete synchronously while a search index, cache, and analytics export update later. The system should record the request, identify copies in scope, dispatch the removal or expiry work, and report whether each branch completed. A retryable worker needs an identifier so repeating a deletion does not accidentally recreate or expose data. Downstream recipients need a defined way to receive and acknowledge deletion or correction requests. If a copy cannot be removed immediately, state its expiry path and restrict access during the waiting period where feasible.

Backups are different from live copies because changing one record inside an immutable backup can undermine recovery integrity. A practical plan may let a backup expire on a bounded schedule while ensuring that restored data is reprocessed through outstanding deletion records before it serves users. That plan must be checked against the applicable obligation; it is not a universal exception. The restoration procedure should preserve the deletion ledger and prevent an old backup from reintroducing records that were already removed from live systems.

Worked examplean erasure completion window

Consider a service whose primary store deletes a record immediately. Assume its search index refreshes every 15 minutes, its cache entries expire within 10 minutes, and its export store deletes files within 24 hours after a removal request. If these processes all start at the same time and complete within their stated bounds, the last live copy disappears within max(0, 15 minutes, 10 minutes, 24 hours) = 24 hours. The check is that the export bound is longer than either index or cache bound. A system-wide completion claim of 15 minutes would therefore be false. This estimate says nothing about backups or third-party recipients; their separate expiry or removal rules must be included before claiming end-to-end completion.

Encryption in transit protects network hops, and encryption at rest protects stored copies in its threat model. Neither helps if an overprivileged service can ask for the plaintext or if the key is kept beside an accessible data export. Restrict key use, separate keys from data where feasible, and plan rotation and recovery before an incident. Passwords need password hashing rather than reversible encryption. OWASP's Cryptographic Storage Cheat Sheet describes these architectural distinctions.

Protect keys and recoverability together

Encryption at rest addresses a particular path to disclosure, such as theft of a storage copy. Application code that legitimately decrypts data remains a separate access path. Limit which service identities may request decryption, log key use without recording key material, and keep keys out of source code and ordinary application logs. Key rotation should be tested before compromise: new writes can use a new key while older records remain readable until they are re-encrypted or expire. A backup cannot be restored if its required historical key has already been destroyed, so key retention and backup retention must be planned together.

Password verification needs a deliberately costly, salted password-hashing scheme rather than ordinary fast hashing or reversible encryption. A unique salt means identical passwords need not produce identical stored values; the work factor slows large-scale guessing after a database theft. Parameters should be selected from current guidance and measured on the actual authentication service so verification remains usable without making guesses cheap. OWASP's Password Storage Cheat Sheet describes suitable schemes and migration considerations. Password resets should invalidate or review relevant sessions according to the account-compromise policy, rather than assuming the stored hash is the only credential at risk.

Worked examplemake retention measurable

Consider a service that creates 10 million activity events each day. Assume each stored event occupies 250 bytes before indexes and replication, and assume the agreed retention period is 30 days. Daily logical growth is 10,000,000 × 250 = 2,500,000,000 bytes, or 2.5 GB using decimal units. A steady 30-day window holds 2.5 × 30 = 75 GB of logical event data. Keeping a full year instead would hold 2.5 × 365 = 912.5 GB; that is 912.5 ÷ 75 ≈ 12.17 times the 30-day window. Check: both figures use the same daily input and differ only in retained days. Indexes, replicas, and backups add storage, while the privacy requirement still needs a rule for each copy. The arithmetic makes an indefinite default visible as both a storage and exposure decision.

§5 · Abuse defenses

Validate input and limit abuse

Validate at the server boundary even when a client already validates. Types, lengths, ranges, and relationships between fields should match the operation. Validation does not replace context-specific defenses: use parameterized queries when untrusted values enter a database query, and encode output for the context in which it is rendered. A valid order identifier still requires an authorization check. OWASP's Input Validation Cheat Sheet separates these controls.

Keep untrusted data in the data role

Validation asks whether an input is acceptable for an operation. Parameterization and output encoding ask how the input is used after acceptance. A product title may legitimately contain an apostrophe or angle bracket; stripping characters until a query seems safe can corrupt the title and still miss another interpretation context. Pass values to a database driver separately from the query structure so a title cannot become a clause. When displaying the same title in HTML, encode it for that HTML context so it is text rather than markup. A value inserted into a URL, JavaScript string, or CSS context needs the corresponding context rule; one generic “sanitize” function cannot safely cover all destinations.

Server validation should bound resource use as well as shape. An array of a million well-formed IDs can exhaust memory or trigger an expensive query. Limit payload size, collection length, nesting depth, and the amount of work one request may schedule according to the service contract. Reject impossible combinations before performing costly work, but keep the final authorization and state-transition checks at the authoritative boundary. A client-side form can improve usability; it is not a security boundary because a caller can send the request without using that form.

A browser may attach a session cookie to a request even when another site caused the request. For state-changing actions, use a suitable request-forgery defense such as an unguessable token or a well-designed origin check, with an explicit cookie policy as another layer. A session cookie's HttpOnly attribute stops ordinary scripts from reading the cookie, but does not stop the browser from sending it. A forged request must still pass server-side authorization, yet authorization alone may not distinguish the user's intended action from one induced by another page. OWASP's Cross-Site Request Forgery Prevention Cheat Sheet explains the choices.

A feature that fetches a user-supplied image URL creates a new network path from the server's position. Validating that the value looks like a URL does not establish that its destination is safe. Restrict allowed destinations or network routes according to the feature, validate redirects, and limit response size and time. A URL that appears public may resolve to an internal address or redirect there, so the protection must cover the actual connection as well as the initial string. A rate limit on callers reduces volume but does not remove the server's ability to reach a forbidden destination.

Handle uploads as untrusted processing

An uploaded file is not safe because its name ends in an expected extension or its browser reported a familiar content type. Limit size and accepted formats, inspect content as appropriate, store it outside executable application paths, and serve it with a safe content type and download policy. Image and document processors themselves parse untrusted bytes, so isolate them and bound CPU, memory, and time. Authorize who may upload and who may later retrieve the result. A generated thumbnail, preview, or extracted text is another derived copy that needs retention and access rules. OWASP's File Upload Cheat Sheet describes these layers.

The diagram shows that an input can move through several interpretation contexts before reaching a user.

System flow
Client input → server validation → authorization → parameterized query → stored value
                                                           │
                                           later read → context-aware output encoding → browser

Read left to right for a write, then follow the lower branch for a later display. Validation rejects unacceptable values, authorization decides who may perform the action, parameterization keeps accepted values out of query syntax, and output encoding keeps stored text out of browser markup or script syntax. A missing control cannot be replaced by a different box in the flow.

Abuse controls protect both users and shared capacity. Set limits around sign-in, password recovery, search, file upload, expensive exports, and external callbacks according to their different risks. Choose the key for each limit carefully: an IP address may group unrelated users, while an account-only limit may be bypassed before login. Apply limits at the relevant shared boundary and decide how clients learn that they have been limited. A limit based only on each server instance changes when the instance count changes.

Set limits for the resource being protected

A rate limit controls arrivals over a time window; a quota caps longer-term use; a concurrency limit bounds work currently in progress. A search endpoint may need both a requests-per-second limit and a cap on concurrent expensive queries. A file service may need a daily byte quota as well as a per-file size limit. State whether each rule applies per account, tenant, source address, API key, or whole service. Before authentication, an account key may be unknown; after authentication, a source address may group unrelated users. Combining identifiers can improve fairness, but the behavior for shared networks and attackers who rotate identities must be tested.

A token bucket permits a bounded burst while controlling average admission. It is useful when normal traffic arrives unevenly, but the bucket size must reflect what the downstream system can absorb. A per-instance bucket can multiply the intended allowance across replicas, as the existing worked example shows. A shared store, consistent ownership of callers, or an explicitly approximate distributed scheme is needed when the promise is fleet-wide. Rate-limit responses should be clear enough that well-behaved clients can back off, while revealing no unnecessary information about another caller's account.

Worked examplea burst budget

Consider an API that admits one operation per token. Assume a bucket holds at most 200 tokens and refills at 100 tokens per second, starting full. A caller can send 200 requests immediately, leaving 200 − 200 = 0 tokens. If it then sends 150 requests during the next second and no other traffic uses the bucket, only 100 new tokens arrive in that second, so at most 100 of those requests can be admitted and at least 150 − 100 = 50 must wait or be rejected under this model. Check the balance: total potential admission over the initial burst and next second is 200 + 100 = 300, whereas demand is 200 + 150 = 350. The bucket controls average admission after the initial allowance; it does not guarantee that a downstream resource can survive 200 simultaneous operations.

Worked examplea per-instance limit that scales accidentally

Consider an API with four instances behind a load balancer and a stated per-caller limit of 100 requests per second. Assume each instance maintains its own independent counter and the caller's requests are spread evenly. Each instance can admit 100 requests per second, so the caller may get 4 × 100 = 400 requests/s accepted in total. Check: at 400 requests/s spread evenly, each instance sees 400 ÷ 4 = 100 requests/s and none exceeds its local limit. If the intended global allowance is 100 requests/s, the system needs a shared decision, consistent routing for that caller, or another design whose approximation is explicitly accepted. This example assumes even distribution; the exact observed maximum depends on routing and burst rules.

§6 · Audit and response

Make sensitive actions explainable

An audit event for a refund, permission change, or sensitive export should identify the actor, action, target, outcome, and a correlation identifier. The log should be written on the path where the action is decided so that a successful privileged change is not invisible. Protect it with restricted write and read permissions, monitor whether event collection stops, and check for alteration. An audit log does not have to contain a copy of the affected personal record; storing a stable reference and the minimum needed context often provides accountability with less exposure.

Record decisions and effects without copying secrets

An audit record should distinguish an attempted action from an applied one. For a refund, record that a principal requested it, which order or payment was targeted, the authorization decision, and the durable result. A single generic “refund called” event cannot tell an investigator whether the change was denied, failed, or completed. Use a consistent event schema and stable identifiers so events across services can be joined. Record server time and the relevant operation identifier, but avoid assuming clocks are perfectly synchronized; ordering within one durable log or state transition can be more reliable than comparing timestamps from different hosts.

Data in the log should be the minimum needed to explain the action. A resource identifier, amount category, and outcome may be sufficient for routine investigation; the full address, token, or exported file contents usually are not. A correlation identifier helps connect a request to downstream events without repeating the sensitive payload in each record. Its scope matters: a globally stable identifier used across unrelated contexts can itself become a tracking key. Apply access controls and retention to the audit store because it can reveal behavior patterns even when obvious secrets are removed.

Audit delivery has a failure policy. For a highly sensitive state change, the service may require a durable audit record in the same transactional boundary as the change or refuse the change if that cannot be guaranteed. A separate remote log service can be unavailable, so simply writing to it after committing the action can leave a gap. An outbox record committed with the state change can preserve the event for later delivery, provided the event is protected and the consumer tolerates duplicate delivery. A routine diagnostic trace may instead be best-effort. State these policies by event class; silently treating every missing audit event as harmless undermines the control.

Make alteration and silence observable

Restrict who can write, read, and delete audit records, and avoid giving the actor being audited unilateral power to rewrite the record of their action. Tamper evidence may use append-only storage, integrity checks, independent replication, or controlled exports. It does not mean that alteration is impossible; it means a later check can detect it under the stated threat model. Monitor the flow of expected events as well as suspicious events. If a service normally emits authorization decisions and suddenly emits none, a quiet alert stream could indicate a broken collector rather than a safe system.

Worked exampletrace a sensitive export

Consider a support agent exporting orders assigned to a case. Assume the request receives operation ID E7. The service records an attempted export with actor, case, requested scope, and E7, then checks the agent's permission on that scope. If denied, it records a denial and creates no file. If allowed, it creates a file with a limited lifetime, records the file identifier and completion state, and links those records through E7. Check the trail by asking four questions: who requested it, what scope was approved, whether a file was actually created, and when it became inaccessible. The answer should come from protected records without storing the full order contents in the audit log.

The diagram shows the separation between a business action and its investigation record.

System flow
Privileged request → authorization → state change
                         │                │
                         └──→ audit event ←┘ → protected store → alert / investigation

Read the two inputs to the audit event as the decision and the resulting action. The design must define what happens if audit recording fails for a sensitive change; silently succeeding can leave the system unable to explain that change. Ordinary diagnostic logs may have a different failure policy, but both kinds of log need sensitive-data filtering. Tokens, passwords, keys, and unnecessary personal data do not belong in logs. OWASP's Logging Cheat Sheet covers event selection, data exclusion, tamper detection, and log retention.

Security signals should lead to a response. Repeated denied access to many resources, sudden privilege changes, unusual exports, and failed key use can justify alerts, but thresholds need a known owner and an investigation path. Response planning should include revoking credentials, limiting an affected path, preserving evidence, and assessing which data copies may have been exposed.

Connect a signal to a bounded response

An alert should name the suspected behavior and the action an operator can take. Many denied reads across different customer IDs may indicate enumeration; a burst of exports by one account may require temporary suspension of that capability; unexpected decryption requests may require key-use review. Thresholds need to consider ordinary behavior so a large legitimate support case does not produce endless noise. A short window can catch rapid misuse, while a longer window can reveal slower probing. Investigate with the protected audit trail, not by enabling raw request-body logging that creates a new privacy exposure.

Response starts with containment and evidence preservation, then assesses scope. Revoking one session may be enough for a stolen browser token, while a compromised service credential may require rotation across several dependencies. Record which accounts, records, exports, backups, or downstream recipients could have been affected, and which facts remain uncertain. A response plan should identify who can disable an export path, rotate a key, or stop an integration without erasing the evidence needed to understand the event. Test those actions in a controlled environment before an incident makes time scarce.

§7 · Verification

Verify controls and revisit trade-offs

Trace each material threat to a control and a test. For object-level authorization, try another user's identifier, an administrative path, and a background job. For retention, trace a test record through primary storage, caches, exports, logs, and backup expiry. For a lost secret, exercise rotation and revocation. For a payment integration or a callback from another service, verify the sender and reject replay or unexpected state transitions. The tests should use the same boundaries shown in the threat model, including failure paths.

Test the boundary that makes the promise

A control should have a positive test and a negative test. For an order-read rule, verify that the rightful customer can read the order and that another authenticated customer cannot. For an export, verify that an authorized agent obtains only the permitted fields and that a denied request leaves no file or queued job. For a deletion, verify that the record disappears from the primary store and that secondary copies follow their stated expiry path. Testing only the denial case can hide an overrestrictive policy; testing only the success case can hide an exposure.

Security regression tests should cover alternate entry paths, not just the most visible endpoint. A list query, direct item lookup, bulk export, background worker, cache, and administrative tool may read the same asset through different code. Choose test identities that differ in ownership, tenant, role, and account state. A known denied ID should be tested against each path; a random nonexistent ID alone proves little because the service might return “not found” before it reaches authorization. Inspect state and artifacts after the request so a denied response is not mistaken for a denied side effect.

Verify external messages and replay behavior

A webhook endpoint is a public or partner-facing entry point even when its messages usually come from a trusted provider. Verify the sender using the provider's supported signing or authentication mechanism, validate the event's shape, and bind the event to the expected account or resource. A valid signature proves who signed the message under the key's security assumptions; it does not prove that the event is new or that its requested state transition is still valid. Track stable event identifiers or another replay control, and let repeated delivery converge on one intended effect. An old “payment succeeded” event must not recreate an order that was canceled under a later authoritative decision.

Tests should include a valid event, an altered payload, an event signed with the wrong key, a duplicate event, and a valid event arriving after the resource has changed state. The response and stored state both matter. A service might return a rejection while a worker already processed the duplicate, or return success while silently discarding an event that should have been applied. Key rotation adds another case: during transition, the service may need to accept a bounded set of valid keys and reject an expired one without losing legitimate messages.

Worked examplea revocation window

Consider a signed session token that remains valid for 20 minutes after issue. Assume an account is disabled 4 minutes after the token was issued and resource servers check only the token signature and expiry. The remaining exposure window is 20 − 4 = 16 minutes. Check the timeline: issued at minute 0, account disabled at minute 4, token expires at minute 20. If the requirement is that disabling an account stops sensitive exports within 2 minutes, this design misses it by up to 16 − 2 = 14 minutes under the stated case. A server-checked revocation status, shorter token lifetime, or a required fresh check for exports can close the gap, each with a latency and availability cost. Test the chosen method at minute 4, after the allowed 2-minute window, and again after token expiry.

Review privacy risk in ordinary use

Security tests ask whether a forbidden actor can cross a boundary. Privacy review also asks what happens when every component works as designed. A recommendation service may lawfully receive a customer identifier under its contract, yet the product might not need to send a full purchase history to generate recommendations. Compare the proposed fields, precision, recipient, and retention with the purpose. Consider whether an aggregate, a short-lived token, or local computation provides the same function with less exposure. The answer should be documented as a design choice that can be revisited when the feature changes.

Privacy risk can arise from combining datasets that looked harmless separately. A pseudonymous activity stream may become identifying when joined with rare location or time patterns. Assess who can perform the join and whether derived outputs can be linked back to a person. A recipient's ability to store or combine data is part of the flow, even if the sender never sees the re-identification. The review should include the user-facing purpose, the service's actual data needs, and a deletion or expiry path for the derived result.

Security and privacy can pull in different directions. More detailed logs aid investigation but retain more information about people. Longer session lifetimes reduce login friction but extend the usefulness of a stolen credential. A remote authorization check can centralize policy but add a new availability dependency. State the affected user journey, the failure or misuse being prevented, and the cost of each option, then choose a rule that can be observed and revisited. NIST's Privacy Framework treats privacy risk across collection, use, storage, sharing, and disposition rather than as a property of storage alone.

Keep the model current as the system changes

A security review is useful only while its description matches the deployed system. A new support role, data export, third-party integration, cache, or authentication method can create a boundary that earlier tests never covered. Make the change review identify affected assets and flows, then add a test for the new path before release. When an incident exposes a missed route, update the model and regression tests rather than only patching the one observed request. This turns the model into a record of the system's actual promises.

Release changes should include the components that carry the control, not only the application endpoint. If a dependency update changes how sessions are parsed, a proxy changes which headers are trusted, or a queue consumer changes its retry behavior, the same authorization and replay tests need to run at the new boundary. Keep an inventory of the libraries and services used by sensitive flows, review reported vulnerabilities in the context of actual exposure, and assign an owner and deadline for each consequential fix. A version number alone does not establish risk: the vulnerable feature may be unreachable, or a modest-looking change may sit directly on an export path. Record the reasoning and retest after remediation.

Test environments also need a privacy rule. Copying production records into a development database creates another recipient, storage location, access group, and deletion path. Prefer synthetic records for ordinary tests. Where realistic data is necessary, remove fields that the test does not need, restrict access and lifetime, and check that snapshots, logs, and debugging exports follow the same rules. A dataset called “anonymized” should be examined for rare combinations and stable identifiers that could still identify someone. Seed tests with deliberately distinct tenants and roles so a cross-tenant failure is visible without exposing real customers.

Before release, ask four concrete questions about each changed flow: who may invoke it, which personal data it reads or emits, which failure leaves an effect behind, and which event would reveal misuse. Link the answers to a test, a retention or deletion rule, and a response owner. For example, adding a scheduled report requires a check when the job is created and again when it executes, because access may be revoked between those times. It also requires a rule for the generated file and its download link. This small review catches paths that an endpoint-only test would miss and gives the next maintainer a reason for the control.

Emergency access deserves its own rehearsal. A responder may need to inspect or contain a failing service when the normal identity provider is unavailable, but permanent broad access creates an attractive target. Define who may activate a temporary elevated role, how the reason and scope are recorded, when it expires, and who reviews its use afterward. Exercise the process with a realistic incident scenario, including the case where the approver is unavailable. Verify that emergency access can perform the intended containment and cannot silently read unrelated customer records. Retire temporary credentials and check for copied data after the exercise. A procedure that cannot be used under the expected outage is not an effective fallback.

Evidence should distinguish a control that exists from one that works under the relevant failure. A policy document stating “least privilege” does not show that a background worker lacks access to unrelated records. A successful encryption setting does not show that keys are separated from exports. A dashboard showing no suspicious events does not show that event collection is healthy. Use configuration review, representative requests, denied side-effect checks, restore or rotation exercises, and audit-event inspection to prove the specific claim. Record the limits of each test so a passing result is not extended to an untested boundary.

· · Review

Common mistakes

Each mistake below is set out the same way: what goes wrong, why the design falls into it, the fix, and the section of this guide that covers the underlying control.

  1. M1Treating login as permission

    What goes wrong
    An authenticated caller can still request another person's record or invoke an operation outside their role.
    Why it happens
    The API checks identity once at the edge and assumes downstream paths are safe.
    Fix
    Authorize the requested action on the specific resource at every relevant entry path, with deny-by-default behavior.
    Covered in
    §3 Establish identity and enforce authorization
  2. M2Encrypting everything while collecting too much

    What goes wrong
    A service with legitimate decryption access can still misuse fields it never needed.
    Why it happens
    Encryption reduces some disclosure risks, so it is mistaken for a complete privacy control.
    Fix
    Collect data for an explicit purpose, constrain recipients, and apply a retention and deletion rule to every copy.
    Covered in
    §4 Protect data through its life cycle
  3. M3Adding an audit log without protecting it

    What goes wrong
    The log fails during an investigation and becomes another exposure path.
    Why it happens
    The same administrator can rewrite it, or it records raw tokens and personal records.
    Fix
    Restrict access, make alteration detectable, filter sensitive values, and verify that required events are recorded.
    Covered in
    §6 Make sensitive actions explainable
  4. M4Relying on input validation as the only boundary

    What goes wrong
    A well-formed identifier still targets someone else's resource, and a well-formed string is still dangerous in a query or rendered page.
    Why it happens
    Validation checks shape, which is treated as if it also proved permission and safe use.
    Fix
    Validate shape and business rules, authorize separately, and use context-specific defenses such as parameterized queries and output encoding.
    Covered in
    §5 Validate input and limit abuse
  5. M5Applying a per-instance limit as a global promise

    What goes wrong
    Each new server silently multiplies the caller's allowance; four instances at 100 requests/s admit 4 × 100 = 400 requests/s.
    Why it happens
    Local counters are simple to build and need no coordination.
    Fix
    Define whether the target is per instance or across the fleet, then use a shared or deliberately approximate enforcement design and test it at the expected instance count.
    Covered in
    §5 Validate input and limit abuse

· · Exercises

Practice questions

These questions mix recall, calculation, and application across the guide; each answer is collapsed beneath its question to be opened after working out an answer.

Question 1 (distinction)

How can an encrypted customer database still violate a privacy requirement?

Answer

Encryption protects data against some unauthorized reads of stored copies. A system can still collect fields it does not need, use them for an undisclosed purpose, share them too broadly, or retain them beyond the agreed period. Privacy requirements govern those decisions even when storage is encrypted.

Question 2 (application)

A signed-in customer can retrieve an order by changing the numeric identifier in the URL. Which check is missing, and where should it be enforced?

Answer

The API is missing authorization for the particular order. After authenticating the caller and loading the target order, the server should verify that the caller is permitted to read that order under the current policy. The same rule must cover other paths to the order, including exports and support tools where appropriate; changing the identifier to another customer's order should be denied.

Question 3 (calculation)

A service creates 4 million personal-data events per day at an assumed 300 bytes per event before indexes and replicas. How much logical data does a 14-day retention window hold, and how much would a 90-day window hold?

Answer

Daily data is 4,000,000 × 300 = 1,200,000,000 bytes, or 1.2 GB in decimal units. Fourteen days hold 1.2 × 14 = 16.8 GB; 90 days hold 1.2 × 90 = 108 GB. Check: 108 ÷ 16.8 ≈ 6.43, matching 90 ÷ 14 ≈ 6.43. Copies, indexes, and backups add to both figures and need their own retention treatment.

Question 4 (misconception)

Why is a 100-requests-per-second limiter on each of five API replicas not necessarily a 100-requests-per-second limit for one caller?

Answer

If each replica counts independently and requests are distributed evenly, each can admit 100 requests/s for the same caller. The fleet can then admit up to 5 × 100 = 500 requests/s. Check: at 500 requests/s evenly spread, each replica sees 100 requests/s. A global promise requires coordinated or caller-consistent enforcement, or an explicitly accepted approximation.

Question 5 (open-ended)

An online shop adds a support export of customer orders and a third-party analytics service. Extend its threat model, access policy, privacy rules, audit design, and verification plan.

Answer

Add the support console, export store, transfer path, and analytics recipient to the flow diagram and mark the new trust boundaries. Define which support principals may export which orders, for what purpose, with what limits and review; require resource-level checks rather than a broad “support” login. Minimize or aggregate the fields sent to analytics and set retention and deletion rules for primary data, export files, downstream copies, and logs. Record who initiated an export, its scope, time, and outcome without logging the complete contents. Test unauthorized exports, overbroad fields, expired files, downstream deletion, credential revocation, and the audit trail for a completed export.

Question 6 (application)

A support agent's session may have been stolen. The account is disabled, but a signed token issued earlier remains valid for another 30 minutes, and a queued export has not yet run. What should the service check and contain before claiming the account can no longer expose orders?

Answer

Determine whether resource servers check only the token signature and expiry or also consult a revocation state. If the token remains usable, disable the sensitive export path for that principal or enforce a server-side revocation check at the export boundary. Cancel or reauthorize the queued job before it creates a file. Inspect protected audit events for reads, export requests, completed files, and downloads during the exposure window, then revoke any live file links and assess downstream recipients. Test a request using the old token, a queued job, and a file download after containment; a disabled account flag alone is not proof that all three paths are closed.

· · Finish

Review checklist

Without consulting notes, distinguish security from privacy and explain how each affects an authorized user journey. Map assets, data flows, trust boundaries, and abuse cases before choosing controls. Authenticate principals and authorize the requested action on its actual resource, including alternate and queued paths. Minimize personal data, protect keys and sessions, and plan retention and deletion across primary and secondary copies. Choose validation, context-specific injection defenses, upload controls, and limits for the resource at risk. Design audit events that explain sensitive actions without copying secrets, and connect alerts to a response. Trace each material risk to a control, a positive test, a negative test, and the residual risk. A reader who can do all of these has covered the material.