Skip to content

Design for Security

Chapter Info

Calculating...

!!Security is not a feature that can be added at the end of development. It emerges from the way a system is designed, built, deployed, and operated.!! !!Every architectural decision affects what can be attacked, how far a compromise can spread, and how quickly the system can recover.!! This chapter presents the enduring principles for reducing those risks across the software supply chain, infrastructure, data, development practices, and incident response. Identity and Zero Trust are covered separately in the Design for Trust chapter.

Design for Security

Introduction

Yesterday's Normal Is Today's Vulnerability

!!What was considered secure yesterday is no longer secure today.!! Algorithms once trusted are now trivial to crack, protocols quietly deprecated, and configurations that felt perfectly reasonable have become textbook mistakes. Every experienced engineer carries a private confession of past practices that would raise alarms in any modern review. This is not a story of individual failure—it is the nature of the field. !!Security moves, and what was standard becomes indefensible.!!

Yesterday's Normal Is Today's Vulnerability

Practices Change, Foundations Endure

!!The practices of security shift constantly, but the underlying principles are few and conceptually simple — least privilege, defense in depth, separation of duties, minimizing exposure.!! These foundations were true decades ago, they are true today, and they will still endure beyond the AI era. This chapter focuses on those foundations, because a software engineer grounded in security principles can adapt to new threats as practices and technologies evolve.

Practices Change, Foundations Endure

Life Continues Under Attack

!!Systems must support continued operation under sustained threat, without assuming attacks stop after one incident.!! Prevention matters, but defenses can fail, so design systems to detect, contain, and repair intrusions while unaffected services keep running. Decide up front which functions can safely continue and which must be isolated.

Life Continues Under Attack

Fundamental Security Principles

Computer security is a complex subject that fills entire books, yet its foundations rest on a few simple ideas. Understanding these principles helps explain why each security decision matters and how the different protections fit together.

Holistic Security: Seeing Security as a System

!!Security must be approached holistically: design security controls as parts of one system, not as a checklist of isolated checks.!! Effectiveness depends on interactions across identities, services, networks, and data — including complete attack paths and what happens when a control fails. !!Security depends on how controls fit together as well as the strength of each one.!!

Holistic Security: Seeing Security as a System

!!Attackers look for the easiest viable path to their objective.!! A forgotten server, excessive permission, or unpatched dependency can bypass stronger protections. Assess weaknesses along complete attack paths, prioritize those that expose critical assets or enable further compromise, and remember that strengthening existing defenses cannot compensate for an overlooked route around them. !!Security reviews must actively look for those gaps.!!

Security is Only as Strong as Its Weakest Link

Rely on Proven Standards, Not Obscurity

!!Prefer established standards and reviewed implementations over custom security mechanisms.!! Public scrutiny exposes strengths and limitations, and maintained libraries receive fixes as weaknesses emerge — whereas custom cryptography or authentication rarely gets sustained independent review. Choose mechanisms fit for your threat model, configure them properly, and keep them updated: !!security must hold even when the mechanism is known.!!

Rely on Proven Standards, Not Obscurity

The Multi-Layered Security Approach

!!Combine complementary protections so one failed control does not leave an asset exposed.!! Some controls prevent access, others limit movement, detect abuse, or support containment. Avoid layers that depend on the same credentials, assumptions, or failure modes: one compromise could defeat them together. !!The value comes from independent barriers with different roles.!! Design their interactions so a bypass can be detected and contained before further damage occurs.

The Multi-Layered Security Approach

Never Trust Your Assumptions — Validate Your Defenses

!!Test whether security controls work together under realistic attack conditions.!! Penetration tests and red team exercises challenge assumptions about entry points, permissions, isolation, and detection. Individual controls may appear correct while their interactions leave an exploitable path. Use findings to correct weaknesses and retest the affected paths. These exercises provide evidence about the defenses tested, rather than proof that no other weaknesses exist.

Never Trust Your Assumptions — Validate Your Defenses

Minimizing the Damage, Reducing the Blast Radius

Even with strong defenses, breaches will still happen. !!Reducing the blast radius means designing systems so that when a failure occurs, its impact stays contained instead of spreading to other components, services, or systems.!! It is not a technique in itself but an outcome: the mechanisms that produce it — segmentation, exposure reduction, least privilege — are what the following sections detail.

Minimizing the Damage, Reducing the Blast Radius

Segmentation: The Mechanism Behind a Small Blast Radius

!!Segmentation uses internal boundaries to contain a compromise within a smaller part of the system.!! Separate resources into zones and restrict the connections and privileges that cross them. Like sealed compartments in a submarine, segmentation limits how far damage can spread. Permitted paths and shared dependencies can still carry an attack, so segmentation must be enforced and tested.

Segmentation: The Mechanism Behind a Small Blast Radius

Minimize Exposure to Reduce Attack Opportunities

!!Reduce how many interfaces are reachable and how long access remains available.!! Exposure depends on reachability, visibility, and duration across services, credentials, infrastructure, and trust relationships — not just public endpoints. Remove unnecessary entry points, narrow permissions, and retire unused resources so attackers have less time and fewer ways in. Every remaining exposed path should have a clear purpose and owner.

Minimize Exposure to Reduce Attack Opportunities

Keep Everything Temporary

!!One of the strongest ways to minimize exposure is to make resources short-lived.!! Ephemeral credentials, temporary compute, expiring tokens, and time-bound access all limit attacker opportunity and force continuous renewal. When everything naturally expires, systems refresh themselves and reduce long-term risk.

Keep Everything Temporary

Data Protection

For most organizations, data is their most valuable asset. Applications, infrastructure, and identities provide ways to use it, but also paths for attackers to reach it. Its exposure or alteration can cause lasting damage to both the organization and its users.

Data Classification

!!Classify data so protection matches its sensitivity and the consequences of compromise.!! Define categories and handling rules appropriate to the organization, covering access, encryption, retention, and monitoring requirements. Without classification, teams either over-protect — making systems slow, costly, and hard to use — or under-protect and leave critical data exposed. What matters most is a clear link between classification and enforced controls: labels alone do not protect data if teams cannot reliably determine how to handle it.

Data Classification

Classify Before You Build

!!Classification is not a label you stamp on a system after it exists — it is an input to the design itself.!! Where sensitive fields live, which tables can join, which services can read what, and what an API exposes are all architectural decisions dressed up as data decisions. A schema drawn without classification leaks sensitivity across boundaries by default, and retrofitting means expensive migrations, painful splits, and controls bolted on after the fact. Classify first, then design around it.

Classify Before You Build

Mixed Data Inherits the Highest Classification

!!When data with different classifications is combined, the result inherits the highest classification present, because a single sensitive field forces the same protection across the whole dataset.!! This high-water mark principle is especially important in analytics pipelines, data lakes, and ML training, where aggregation often hides the sensitivity of individual inputs. Classification always follows the most sensitive data — not the average.

Mixed Data Inherits the Highest Classification

The Best Way to Protect Data Is to Never Collect It

!!Avoid collecting sensitive data that the system does not need.!! Each collected value creates obligations for access control, protection, retention, and deletion. Define its purpose before accepting it, consider whether a less sensitive representation would suffice, and apply the same discipline to logs and telemetry where unnecessary data is easily overlooked. Collecting less reduces both the protection burden and what an attacker can steal or compromise.

The Best Way to Protect Data Is to Never Collect It

Store Proof, Not Secrets

!!When a system only needs to verify a value, store a verifier rather than the original secret.!! For passwords, use a salted hash produced by a dedicated password-hashing algorithm instead of storing a recoverable value. Apply the same logic whenever another sensitive value can be replaced by a derived or verification representation, removing information an attacker could otherwise steal. Protect those records too: storing less reduces exposure, but does not make the retained data harmless.

Store Proof, Not Secrets

Every Copy of Sensitive Data Creates Another Security Risk

!!Every copy of sensitive data is another asset to protect.!! Duplicating a record into a cache, downstream service, analytics warehouse, or report expands the attack surface, audit scope, and deletion footprint. !!Favor controlled access to the authoritative source over unnecessary copies.!! !!When copies are needed for availability, performance, or analytics, keep them explicit, minimized, governed, and independently protected.!!

Every Copy of Sensitive Data Creates Another Security Risk

The Longer You Keep Data, the Greater the Risk

!!Every day data sticks around is another day it can be stolen. Retention is a risk choice, not a filing habit.!! Keeping data "just in case" turns it into a liability when a breach, subpoena, or rule change happens. Automated retention, cache TTLs, expiring backups, and scheduled purges make deletion a built-in system property instead of a manual chore. !!The safest data is data that is already gone.!!

The Longer You Keep Data, the Greater the Risk

Protect Data Confidentiality

Confidentiality ensures that sensitive information is accessible only to authorized parties. Encryption is one of its fundamental mechanisms, protecting data both at rest and in transit by making it unreadable without the appropriate cryptographic keys. However, encryption alone does not guarantee confidentiality: access controls, key management, and proper handling of sensitive information are equally essential.

Protect Data Confidentiality

Protect Data Integrity and Authenticity

Data integrity ensures that information has not been altered without authorization, while authenticity verifies that it comes from the claimed source. Cryptographic mechanisms such as HMACs and digital signatures can provide both guarantees. Digital signatures can also support non-repudiation, providing evidence of origin that makes it difficult for the signer to deny having signed the data.

Protect Data Integrity and Authenticity

Access Control Comes Before Cryptography

Most data breaches don’t break encryption — they exploit legitimate access. Access control determines who can read data, while encryption protects it when storage or communication channels are compromised. Even AES-256 cannot prevent an attacker with stolen credentials or excessive permissions from accessing plaintext. Get access control right first — encryption complements it, but never replaces it.

Access Control Comes Before Cryptography

Minimize Human Access to Data

!!Systems should access data, not people, because every human touchpoint is an opportunity for error, exfiltration, or coercion, and every operator credential is one an attacker can steal.!! Automated pipelines, service accounts, and secure APIs move data between systems without ever exposing it to human eyes. When human access is unavoidable, it should be the exception: short-lived, scoped, approved, and logged. Humans are the audit case, not the default path.

Minimize Human Access to Data

Never Use Production Data Outside Production

Production data carries production risk. Copying it into development, testing, analytics, or training environments extends the confidentiality perimeter to zones with weaker controls, broader access, and looser retention rules — a common source of breaches and regulatory violations (GDPR, HIPAA, PCI DSS). !!Lower environments should use synthetic or fully anonymized datasets by default.!! When real data is genuinely required for a specific use case, it must be sanitized, formally approved, time-boxed, and treated with the same controls as production itself.

Never Use Production Data Outside Production

Separate Storage Access from Decryption Rights

!!Permission to read encrypted storage must not automatically grant permission to decrypt its contents.!! Manage encryption keys through a dedicated key management service or hardware security module, with separate access policies and audit logs. Grant decryption rights only where needed, scoped to the relevant data. Separate storage and backup administration from key administration and decryption, so a stolen database or snapshot alone does not reveal plaintext.

Separate Storage Access from Decryption Rights

Give Customers Control Over Their Encryption Keys

!!Let customers govern the encryption keys protecting their data, whether through CMK, BYOK, or HYOK models.!! Offer control over key access, rotation, and revocation with auditable usage, helping meet compliance and trust requirements. Define which services may decrypt data and how key unavailability affects them. Customer-managed keys strengthen control over encrypted storage, but they do not by themselves stop an authorized, compromised service from accessing plaintext, and revocation timing depends on the service and its caching behavior.

Give Customers Control Over Their Encryption Keys

Inventory and Visibility

Effective security begins with knowing what must be protected. A reliable inventory makes assets, software components, deployments, and access relationships visible — providing the foundation for the controls that follow.

Why Inventory and Control Matter

!!Every production artifact, configuration, and feature-flag change must travel through trusted delivery pipelines.!! Pin inputs and outputs to immutable versions or digests, restrict production writes to approved pipeline identities, and never let an alternative path bypass validation or make security checks optional.

Why Inventory and Control Matter

Unified Asset and Software Inventory

Every device, VM, container, and library running in an organization is part of its attack surface. Any asset that is unknown, unmanaged, or outdated becomes a blind spot an attacker can exploit. !!Unified inventory joins two catalogues — the hardware layer (servers, endpoints, cloud resources, IoT) and the software layer (applications, services, libraries, dependencies).!! Together, they provide the foundation for understanding what needs to be protected, patched, and monitored.

Unified Asset and Software Inventory

Software Bill of Materials (SBOM)

A Software Bill of Materials (SBOM) is a machine-readable inventory of the components, libraries, and dependencies included in a software artifact. Generated from build and dependency information, it makes the software supply chain visible. When a new vulnerability (CVE) is disclosed, teams can identify affected artifacts quickly instead of manually investigating each application.

Software Bill of Materials (SBOM)

Know Where Every Artifact Is Deployed

!!Knowing what components exist in your software (SBOM) is only half the equation—you must also know where those artifacts are actually deployed and running.!! When a critical vulnerability is announced, rapid impact assessment requires answering: "Where is this running?" Without deployment-to-artifact mapping, organizations face a critical blind spot: they can identify that a vulnerable library exists in the artifact repository, but they cannot determine which environments, services, or instances are affected.

Know Where Every Artifact Is Deployed

Controlling Supply Chain Security

Software depends on external components and build systems outside full organizational control. A compromised dependency or build tool can enter a release, so visibility alone is not enough — active controls must block unapproved or untrusted artifacts before production.

Controlling Supply Chain Security

CI Pipeline: The Primary Control Gate

Supply chain security begins in the CI pipeline. !!Every change entering production passes through automated validation gates — SBOM generation, vulnerability scanning, policy compliance, artifact validation — and any failure blocks the change from progressing toward production.!! Treating security as a build-time quality gate, alongside tests, is what makes it cheap: issues are caught when they are still one line of code, not one incident.

CI Pipeline: The Primary Control Gate

Trust the Build, Not the Developer

AI is changing the paradigm of trust in software development: the trust boundary moves from the code producer to the automated system that transforms it. Production should run only artifacts built, verified, and approved by trusted pipelines. Provenance, attestations, and reproducible builds provide evidence of where an artifact came from and how it was made, independently of its author.

Trust the Build, Not the Developer

Artifact Manager: The Single Source of Truth

CI checks are only useful if their results stay tied to the artifact throughout its lifecycle. An Artifact Manager provides a holistic view of the artifact lifecycle, acting as the single source of truth from build to deployment. CI publishes each artifact with its SBOM, scan results, and provenance; CD checks the manager before deploying and reports back where it runs. This two-way flow connects what was approved to what is actually deployed, enabling rapid identification of affected services and environments when a new vulnerability is discovered.

Artifact Manager: The Single Source of Truth

Verify Artifact Integrity Before Deployment

Building an artifact through a trusted pipeline is not enough. Its integrity and origin must also be verified before deployment. Each artifact should be cryptographically signed during the build process, with its signature linked to its exact contents. At deployment time, automated controls verify the signature against a trusted authority and reject any artifact that has been modified, lacks a valid signature, or comes from an untrusted source. This ensures that production runs exactly what the trusted pipeline produced, not something that was replaced or altered along the way.

Verify Artifact Integrity Before Deployment

No Side Doors: The Pipeline Is the Only Path to Production

!!Every production artifact, configuration, and feature-flag change must pass through trusted delivery pipelines.!! Pin inputs and outputs to immutable versions or digests, restrict production writes to approved pipeline identities, and never let a manual bypass or alternative path make security checks optional.

No Side Doors: The Pipeline Is the Only Path to Production

Policy-as-Code: Automated Governance Enforcement

If the pipeline is the only gate, the question becomes: what does it check? !!Policy-as-code turns governance from documentation into executable rules.!! Encryption required, storage never public, resources tagged for ownership, data residency respected — policies are expressed as declarative rules and automatically enforced at the appropriate control points, from CI to deployment and runtime. Compliance becomes built-in rather than bolted on.

Policy-as-Code: Automated Governance Enforcement

Third-Party Component Approval

Third-party components must be approved before they can reach production. Whether introducing a new external library, upgrading an existing third-party component, or reusing an approved one in a different context, the approval process evaluates security risks, licensing, compliance obligations, and maintenance. Once approved, the component can be made available through the trusted repository.

Third-Party Component Approval

Control Your External Dependencies

!!External dependencies must enter builds through a controlled internal repository.!! Public repositories provide software, not trust; admit only approved versions, scan for vulnerabilities and malware, and block prohibited components. Distribute fixes centrally, rebuild, redeploy, and verify affected systems — !!repository updates alone do not repair artifacts already running in production.!!

Control Your External Dependencies

Vulnerability Management

Vulnerabilities are inevitable; leaving them unaddressed is optional. Inventory shows what exists, and supply chain controls filter what enters. !!Vulnerability management reduces exposure through verified remediation, effective mitigation, or explicit risk acceptance.!!

You Can't Fix What You Can't See

Vulnerability management begins with continuous discovery of weaknesses across systems, applications, dependencies, and configurations. Scanning is one mechanism, but the principle is broader. New research, threat intelligence, and configuration drift can expose risks that were previously unknown. Discovery must therefore be continuous, not a one-time check before release.

You Can't Fix What You Can't See

Approved Today Doesn't Mean Safe Tomorrow

Approval is a point-in-time decision, not a permanent guarantee of safety. A dependency that passed every check when introduced can become vulnerable months later, without any change to the application. Continuously correlate the components recorded in SBOMs with newly disclosed vulnerabilities and threat intelligence, and identify which deployed artifacts are affected. Monitoring must continue for as long as the component remains in use.

Approved Today Doesn't Mean Safe Tomorrow

Prioritize Risk, Not Severity Alone

The Common Vulnerability Scoring System (CVSS) rates vulnerability severity on a scale from 0 to 10. Its base score is a signal, not a remediation priority. Risk also depends on exposure, exploitability, existing controls, and business impact. !!Priority must reflect the actual context and evolve when that context changes.!!

Prioritize Risk, Not Severity Alone

Every Vulnerability Needs an Owner

A vulnerability without clear ownership can remain unresolved even when its risk is understood. Every confirmed finding needs an accountable owner, a priority, and a target resolution date. Track it in a shared system of record until remediation is verified or the residual risk is formally accepted. !!Missed deadlines must trigger escalation.!! Risk acceptance must be assessed, approved, and documented, with a review date. It must also be reassessed when threats or exposure change.

Every Vulnerability Needs an Owner

Minimize the Window of Exposure

The risk of a known vulnerability grows with the time it remains exploitable. Reduce that window rather than wait for a perfect fix. Remediation removes the weakness, such as by patching or replacing a vulnerable component; mitigation reduces immediate risk through controls such as restricting access, disabling a feature, or adding a WAF rule. When a permanent fix cannot be deployed immediately, mitigate first, then remediate and verify the deployed system.

Minimize the Window of Exposure

Design for Emergency Security Response

!!A critical vulnerability tests the entire organization's ability to act.!! Architecture must support rapid identification of affected deployments, their owners, and the components that need replacement. Standardized components, automated pipelines, and reliable deployment tracking enable remediation at scale. Clear responsibilities and a rehearsed response plan help teams coordinate. The response ends with verification: has the exposure actually been removed? !!This collective capability must be designed and exercised before the emergency occurs.!!

Design for Emergency Security Response

Check for Prior Exploitation

Discovering a serious vulnerability raises two questions: how do we fix it, and has someone already exploited it? Patching closes the weakness, but it does not undo an earlier compromise. Investigate signs of exploitation, preserve relevant evidence, and trigger a security investigation when exploitation is suspected, escalating to incident response when necessary. Vulnerability remediation and incident containment may need to proceed in parallel.

Check for Prior Exploitation

Network and Perimeter Security

Network and perimeter security controls how traffic enters, leaves, and moves within a system. Segmentation, controlled entry and exit points, and secure remote access limit exposure and help contain compromises.

Network Segmentation

Network segmentation limits the spread of an attack after an entry point has been compromised. !!Separate trust zones and allow only the communications each zone requires.!! Creating subnets alone does not enforce isolation: routing and filtering controls must restrict traffic between zones. Segmentation reduces lateral movement, but attackers may still exploit permitted connections. Those paths must follow least privilege and be monitored. Combined with ingress and egress controls, segmentation reduces the blast radius of a compromise.

Network Segmentation

Controlling Inbound Traffic

!!Inbound traffic should be denied by default and allowed only through explicit, controlled entry points.!! Each exposed service should accept only the protocols, sources, and identities it requires. !!An allowed connection can still carry an attack.!! Network filtering restricts connections, while a Web Application Firewall (WAF) inspects HTTP requests for application attacks. Distributed denial-of-service (DDoS) protection and rate limits help preserve availability under abusive traffic. Protection depends on active rules and enforcement: detection alone does not block traffic. Every allowed path should be intentional, observable, and continuously reviewed.

Controlling Inbound Traffic

Controlling Outbound Traffic

!!Outbound connections should be denied by default and explicitly allowed only to approved destinations, through controlled paths.!! Egress firewalls, proxies, and allowlists block unauthorized connections and reduce opportunities for data exfiltration, command-and-control traffic, and malicious downloads. Approved destinations can still be abused, so permitted traffic must also be monitored for suspicious activity. Every allowed connection should be necessary, observable, and easy to revoke.

Controlling Outbound Traffic

Secure Remote Access

Remote access must expose only the resources needed for a task. !!Require strong authentication, least privilege, and authorization at each resource.!! A Virtual Private Network (VPN) provides an encrypted tunnel to a network; an application access gateway can limit access to specific services. Neither the connection nor the caller's network location establishes trust. Human access should require multi-factor authentication (MFA). Remote sessions must be encrypted, logged, and revocable.

Secure Remote Access

Environment Isolation

Environment isolation defines boundaries between environments, including separate production environments, and controls the access and changes allowed across them. It limits the spread of mistakes and compromises while supporting controlled deployments and routine or emergency access.

Keep Development Isolated from Production

!!Development and production belong to different trust zones.!! Production operates under stricter controls, monitoring, patching, and change-management rules, while development contains experimental code, broader permissions, debugging tools, and frequent human access. A direct Dev-to-Prod path creates both a route for attackers and a route for accidental changes. !!Lower-trust environments must never be able to influence production directly.!!

Keep Development Isolated from Production

Hard Isolation vs Logical Isolation

!!Environment isolation limits the spread of mistakes and compromises.!! Hard isolation separates infrastructure or administrative domains, generally providing stronger containment but adding complexity and potential migrations. Logical isolation uses policies within shared infrastructure. It makes boundaries easier to change, often without moving workloads or data, but depends more heavily on policy correctness and shared controls. Keep identities and secrets scoped to each environment. !!Balance the required protection against operational cost and future flexibility.!!

Hard Isolation vs Logical Isolation

Time-Bound Access to Production

!!Grant engineers administrative access to production for a specific task and duration, with automatic expiry.!! A just-in-time access system limits permissions to the required environment, resources, and operations. Every grant and session must be auditable. When the window closes, end the session and revoke its temporary credentials. Expiry limits the duration of access; it does not undo changes or remove persistence established during a compromise.

Time-Bound Access to Production

Initiate Control Connections from Inside the Environment

!!Initiate control connections from within the environment using trusted, authenticated sources instead of relying on inbound administrative access.!! This reduces exposed entry points while keeping controller permissions scoped. With polling, responsiveness depends on the polling interval, whereas outbound channels can react faster without opening inbound ports.

Initiate Control Connections from Inside the Environment

Safe Proxies Pattern

!!Expose routine production operations as predefined, tested procedures behind safe proxies.!! Users select an operation and provide constrained parameters through an interface or API. The proxy authorizes the request; a backend routine executes the same validated sequence instead of manually entered commands. This makes execution repeatable and reduces operator mistakes. Validate parameters, restrict targets, and log each action. Sensitive operations may require approval. Block direct bypasses and reserve separately authorized console access for ad hoc tasks.

Safe Proxies Pattern

Secure Production Console Access

Ad hoc tasks that cannot be handled through approved operational interfaces may require an interactive console, putting live data and system stability at risk. !!Route these sessions exclusively through a dedicated, hardened administration environment.!! Keep production credentials and tools inside this environment. Require strong authentication, explicit approval, and temporary task-scoped permissions. Every session must be fully audited. Turn recurring console tasks into controlled operations when practical.

Secure Production Console Access

Breakglass Mechanism

!!Breakglass provides emergency access when normal controls fail or cannot grant permissions in time.!! Keep its recovery path usable when the normal access system fails. Protect emergency credentials, limit privileges, and record who accessed what and why. Alert on use, audit actions, and revoke temporary access afterward. Review every activation and test the mechanism regularly. !!Emergency access must remain exceptional and accountable.!!

Breakglass Mechanism

Threat Modeling

Threat modeling identifies how a system could be attacked by examining its architecture, data flows, and trust boundaries. It helps teams spot weaknesses early, prioritize the highest-impact risks, and add defenses before deployment.

Structure the Threat Model Around Four Questions

A threat model records a structured review around four questions. !!How does the system work?!! Describe components, identities, secrets, data flows and storage, cryptographic protections, and trust boundaries. !!What can go wrong?!! Identify threats, attack paths, assumptions, and risks. !!What are we doing about it?!! Document controls, action owners, and accepted risks. !!Did we do a good enough job?!! Record validation results, remaining weaknesses, and follow-up actions. Together, these answers explain what is protected, why the defenses were chosen, and what still needs attention.

Structure the Threat Model Around Four Questions

Source

Adapted from Adam Shostack’s Four Question Framework.

Start Threat Modeling at Design Time

Security weaknesses discovered after implementation can require costly changes to interfaces, permissions, or data flows. !!Threat modeling belongs in design reviews, while these decisions are still open.!! It lets teams compare alternatives and build controls into the architecture before code and dependencies make changes harder. The depth of the review should match the consequences of compromise.

Start Threat Modeling at Design Time

Identify Trust Boundaries and Attack Paths

Every trust boundary is a potential attack opportunity. Threat modeling examines how data, identities, and requests move between components with different levels of trust. External interfaces, service connections, privileged operations, and data flows reveal where an attacker might enter, escalate privileges, or move through the system. Attack trees break an attacker's objective into possible steps and paths. Mapping these paths exposes weaknesses that individual component reviews often miss.

Identify Trust Boundaries and Attack Paths

Turn Threats into Security Controls

Identifying threats is only useful when it leads to architectural decisions. Evaluate each significant threat by its likelihood and potential impact, then select appropriate controls such as isolation, least privilege, authentication, or monitoring. Verify that those controls address the identified threats through targeted tests and attack simulations. Assign owners to mitigation actions and document accepted risks with an approver and review date.

Turn Threats into Security Controls

Keep Your Threat Model Alive

A threat model must evolve with both the system and its threats. Revisit it when architecture, data flows, permissions, or trust boundaries change. New threat intelligence, disclosed vulnerabilities, and security incidents can also invalidate earlier assumptions, even when the system itself is unchanged. Reassess the affected risks and controls so that security decisions reflect the current system and threat landscape. Make this reassessment part of design reviews and the approval of security-sensitive changes.

Keep Your Threat Model Alive

Secure Development Practices

Development decisions shape a system’s security long before it reaches production. Small shortcuts can become lasting weaknesses, especially when copied across a codebase. Secure development makes protection part of everyday engineering rather than a correction left for later.

Secure by Design

!!Security is a design decision, not an implementation detail.!! Retrofitting security into a system that was drawn without it is expensive and rarely complete — trust boundaries drift, privileges accumulate, and the attack surface grows past anyone's mental model. Least privilege, minimized attack surface, and explicit trust boundaries belong on the whiteboard, not in the PR review. An architectural flaw caught during design costs a diagram edit; caught in production, it costs a migration.

Secure by Design

Never Trust Input

!!Treat data crossing a trust boundary as untrusted, even from internal services, messages, or files.!! Validate types, formats, sizes, and allowed values at the boundary, and enforce protections where data is used: parameterized queries for SQL, context-aware encoding for output, and APIs that separate operations from arguments rather than building shell commands from raw strings.

Never Trust Input

Fail Securely

!!A failed security check must deny access, never allow it.!! Handle exceptions, timeouts, and missing security configuration explicitly on authentication, authorization, or policy paths so they cannot fail open; other failures may keep limited functionality only while security guarantees remain intact. !!Define and test safe failure behavior for every security-sensitive path.!!

Fail Securely

Protect Secrets Throughout Their Lifecycle

!!A leaked password, API key, or signing key can let an attacker access protected resources or impersonate a trusted identity.!! Keep plaintext passwords, API keys, and signing keys out of source code, images, and configuration files. Retrieve them from a dedicated secrets manager at runtime, restrict access, automate rotation, and revoke exposed credentials promptly. Scan commits and build artifacts for accidental leaks so they are blocked before release.

Protect Secrets Throughout Their Lifecycle

Make Secure Development the Default

Repeatedly implementing security controls in application code creates opportunities for mistakes. !!Provide libraries, frameworks, and defaults that make secure behavior the easiest choice.!! Use approved cryptographic libraries, established authentication frameworks, parameterized database APIs, and context-aware output encoding. Shared components should apply protections by default and make exceptions explicit. Training and review remain useful, but routine protection should be built into the tools rather than depend on each developer remembering every rule.

Make Secure Development the Default

Keep Security Knowledge Current

Secure defaults and automated checks work better when developers understand the risks they address. !!Provide short, recurring security training that helps teams recognize common vulnerabilities and emerging attack techniques.!! Use relevant OWASP guidance, practical examples, and scenario-based questions tied to the team's technologies. Refresh this knowledge annually and when significant threats or incidents emerge. The goal is to recognize unsafe patterns and know the approved response, rather than memorize rankings.

Keep Security Knowledge Current

Source

OWASP SAMM: Training and Awareness.

Build AI Security Guardrails into CI

!!The platform should provide specialized AI agents that check code and implement proposed security fixes as part of CI.!! Use focused reviews for authorization, input handling, secrets, cryptography, and dependencies. Validate fixes through tests, scanners, and independent review. CI policies must define required checks and block unresolved findings according to risk. Limit agent permissions and keep approval rules outside their control. These agents extend security coverage; their output still requires verification.

Build AI Security Guardrails into CI

Code Security Is a Team Responsibility

!!The security of a service is a shared responsibility of the team that builds and operates it.!! As AI increases code volume, reviewers need judgment to focus attention where security risks are greatest. AI checks and platform guardrails support this work, while the team examines critical assumptions, permissions, and sensitive data flows. !!The team and the developers who review and approve each change remain accountable for its security.!!

Code Security Is a Team Responsibility

AI and Security

AI accelerates both legitimate security work and malicious activity. Connecting models to data and tools also creates new paths from untrusted information to privileged actions, increasing the consequences of mistakes and manipulation.

Attackers Automate Too

!!AI lets attackers repeat and adapt parts of an attack with less manual effort.!! It can assist reconnaissance, vulnerability analysis, and exploit development, increasing how many paths an attacker can explore. Defenders may have less time between disclosure, discovery, and exploitation. Keep mitigation and containment ready to execute, and measure the time needed to revoke access or isolate affected workloads.

Attackers Automate Too

Use AI to Scale Security Operations

!!Use AI to connect evidence and accelerate security investigations.!! Give it scoped access to inventories, vulnerability findings, logs, and deployment history so it can correlate events, test hypotheses, and propose mitigations. Keep source evidence traceable and verify proposed changes through independent checks. Separate read-only investigation from actions that change systems, with execution controlled by risk and permissions.

Use AI to Scale Security Operations

Untrusted Content Can Redirect an Agent

!!Documents, web pages, tool responses, and agent memory can carry instructions that redirect a model.!! This is prompt injection: content supplied as data influences decisions or actions beyond its intended role. Track where content comes from and distinguish it from trusted instructions. Do not treat prompt formatting as an enforced security boundary. Test hostile inputs and repeat security evaluations when models, instructions, retrieval sources, or tools change.

Untrusted Content Can Redirect an Agent

Enforce Agent Permissions Outside the Model

!!Enforce an agent’s authority in application and tool code, independently of model instructions.!! Scope credentials, data access, permitted operations, and destinations to the task. Validate each requested action against policy and delegated authority before execution. Isolate execution environments and bound action rates and resources. Define which high-impact operations require human approval. Record actions and provide a way to stop runs and revoke access.

Enforce Agent Permissions Outside the Model

Control Data Flows Through AI Systems

!!Control sensitive data throughout prompts, context, tool calls, outputs, and retained records.!! Apply classification before sharing information with models or external services. Limit inputs to what the task requires, and define permitted providers, destinations, retention, and training use. Restrict retrieval to data the caller is authorized to access. Apply access controls and deletion rules to conversation history, agent memory, and evaluation datasets.

Control Data Flows Through AI Systems

Sources

NIST: Cyber AI Profile — Preliminary Draft.

Google Threat Intelligence Group: AI-Powered Threats and Defenses.

OWASP: Prompt Injection.

OWASP: Excessive Agency.

OWASP: Sensitive Information Disclosure.

Security Incident Response

Even well-protected systems can be compromised, and an attacker may remain active while services appear healthy. Responding to a security incident means stopping the compromise and limiting its consequences.

Monitor for Suspicious Activity

Detect suspicious activity across identities, workloads, and data access, such as a service account logging in from an unusual location or a workload reading unexpected sensitive data. Correlate events across components and preserve enough context to investigate. !!Route actionable alerts to a responsible team, with a defined escalation path.!!

Monitor for Suspicious Activity

The Audit Trail Must Outlive the Attacker

!!Audit logs must remain trustworthy when a workload is compromised.!! Stream security events promptly to protected storage outside the workload’s administrative control. Allow sources to append records, but prevent compromised workload identities from altering or deleting retained logs. Enforce retention and tightly restrict logging administration. Alert on collection failures so gaps are investigated. !!The identity under investigation must not control its audit evidence.!!

The Audit Trail Must Outlive the Attacker

Contain Before You Recover

!!Contain an intrusion before restoring affected services.!! Prepare and test response procedures and controls to isolate compromised workloads and revoke access quickly. Preserve relevant logs and volatile evidence early, alongside containment. Remove attacker persistence and close exploited entry points. !!Rebuild or restore from verified clean sources, then validate the recovered systems before returning them to production.!!

Contain Before You Recover

Turn Incidents into Security Improvements

!!Use incident reviews to improve the system’s defenses.!! Look beyond the initial exploit: why did the compromised identity have those permissions, why could the attack spread, and why did detection take so long? Translate findings into changes to architecture, controls, or response procedures. Assign each action an owner and a deadline. !!Verify completed improvements through targeted tests or exercises, and update the threat model with what the incident revealed.!!

Turn Incidents into Security Improvements