Secure AI Coding Agents: A Production Control Framework That Scales
One coding agent can open dozens of pull requests in an afternoon. That is useful throughput until the same agent copies a vulnerable dependency across twelve repositories, weakens an IAM policy to make a test pass, or follows instructions hidden in an issue body. Human review alone does not scale at machine speed.
AWS published a two-pillar control framework for AI coding agents on July 30, 2026. Author-time controls shape what the agent is allowed to produce. Build-time controls verify what can merge and deploy. The important idea is not a particular AWS product. It is the separation between probabilistic guidance, deterministic enforcement, and human judgment.
This guide makes that separation operational. It defines risk tiers, dedicated identities, sandbox boundaries, MCP allowlists, specification gates, pipeline checks, evidence, metrics, and a rollout plan. It also answers the uncomfortable question that gets lost in governance decks: which changes can an agent ship without a person, and which ones must stop?
The old SDLC is necessary but insufficient
Secure software development already includes branch protection, peer review, static analysis, dependency scanning, secrets detection, tests, artifact signing, and deployment approvals. Keep all of it. Agents do not invalidate those controls.
They do change three properties of the system:
- Volume. A flawed pattern can move across many files and repositories before the first reviewer notices.
- Input trust. Agents ingest issue text, documentation, web pages, package metadata, and MCP responses in the same context used to make decisions.
- Reach. Tool integrations can turn a code suggestion into a database query, cloud change, or production deployment.
The AWS framework for coding-agent controls names seven major risks: prompt and context injection, data disclosure, uncontrolled production changes, supply-chain compromise, uncontrolled external access, hallucinated or incorrect code, and scope creep. Every production design should map controls to those risks rather than installing scanners without a threat model.
If your agents already call AWS or internal tools through MCP, pair this guide with the least-privilege MCP access patterns. Connectivity and authorization are separate problems.
Use three control types on purpose
The strongest design does not ask a language model to enforce a rule that a parser can enforce exactly.
| Control type | Examples | Best use | Failure mode |
|---|---|---|---|
| Deterministic | Tests, SAST, secret scanning, policy-as-code, signatures | Rules with an objective pass/fail result | Misses intent and novel design flaws |
| Non-deterministic | Steering, LLM review, spec-compliance review | Context, intent, and cross-file reasoning | Variable results and false confidence |
| Human | Architecture approval, privileged change review, incident decisions | Irreversible or ambiguous risk | Queueing, fatigue, rubber-stamping |
Use a deterministic gate for “no public S3 bucket.” Use a model-assisted review for “does this change preserve the authentication design?” Use a human for “should this migration delete the old customer table?”
Routing everything to a person is not automatically safer. A reviewer facing fifty routine approvals learns to click. Concentrate human attention on high-impact changes and let tested low-risk work flow.
Assign a risk tier before the agent starts
Risk classification belongs in the task specification, not after the diff appears.
| Tier | Typical work | Agent authority | Required gates |
|---|---|---|---|
| 0: Read-only | Explain code, search logs, draft a plan | No repository or system writes | Audit log only |
| 1: Local reversible | Tests, docs, formatting, isolated refactor | Worktree writes; no protected branch | Tests, lint, scope check |
| 2: Shared code | Feature code, dependency updates, IaC modules | Pull request only | Full CI, security scans, reviewer |
| 3: Privileged | IAM, networking, secrets, data migration | Sandboxed proposal; no direct execution | Named owner, change set, security approval |
| 4: Irreversible | Production deletion, key revocation, public release | No autonomous action | Explicit human execution and rollback plan |
The tier should be computed from target paths and requested actions. A documentation task that unexpectedly edits terraform/iam.tf moves to Tier 3. A bug fix that adds a migration with DROP COLUMN moves to Tier 4. The system must fail closed when classification changes.
Store the tier in machine-readable metadata:
task_id: ENG-4821
risk_tier: 2
allowed_paths:
- services/catalog/**
denied_paths:
- infra/**
- migrations/**
allowed_tools:
- git_read
- repo_write
- unit_test
requires_human_review: true
max_files_changed: 20
That file becomes input to the sandbox, tool gateway, CI policy, and review UI. It is more useful than a paragraph saying “be careful.”
Author-time controls: shape the work before code exists
Put security invariants in steering
A steering file gives the agent persistent organizational context. AWS uses Kiro as one example; the pattern works with any agent that loads repository instructions. The Kiro steering documentation explains its mechanism.
Write short, testable rules:
# Security invariants
- IAM policies must name actions and resources. Wildcard resources require a documented exception.
- Applications retrieve credentials from AWS Secrets Manager; never add credentials to source or fixtures.
- Internet-facing security groups may expose only ports listed in architecture/approved-ingress.yaml.
- New dependencies must exist in the approved registry and be pinned in the lockfile.
- Never disable a failing security test. Report it and stop.
Steering reduces bad output; it is not enforcement. Back each invariant with a pipeline rule where possible. If Action: "*" is forbidden, scan for it. If the exceptions are legitimate, require a waiver file with an owner and expiry.
Require a reviewed specification
Vague prompts create scope creep. A specification should name the behavior to add, the behavior that must remain unchanged, files or components in scope, test evidence, and rollback.
WHEN an authenticated customer requests an invoice
THE SYSTEM SHALL return only invoices whose tenant_id matches the session tenant.
Unchanged behavior:
- Existing pagination and sort order
- Admin export endpoint
- Audit event schema
Out of scope:
- Database schema changes
- IAM or deployment configuration
The Kiro specification workflow is one implementation. The broader principle is stronger: review intent before reviewing thousands of generated lines. Code is a derivative artifact.
Separate trusted orchestration from untrusted reading
Prompt injection is an architecture problem. A model cannot reliably distinguish data from instructions when both occupy the same context. The OWASP LLM prompt-injection guidance treats indirect instructions from files and web pages as a primary risk.
Use two roles:
- A reader processes untrusted tickets, pages, and repository content with read-only tools.
- An executor receives a structured, bounded task from the trusted orchestration layer and holds only the tools needed for that tier.
Do not pass arbitrary reader text directly into a privileged tool call. Convert it to a schema, validate fields, and apply policy outside the model.

Give every agent its own identity
An agent using a developer’s broad credential is impossible to contain or audit cleanly. Use a workload identity per agent class and environment. Short-lived credentials should carry task context such as repository, ticket, risk tier, and session ID when the identity system supports it.
The identity policy should answer four questions:
- Which tool may be invoked?
- Which resource can that tool touch?
- Which action is allowed?
- Under which task context and expiry?
For delegated multi-agent systems, the Cedar and Verified Permissions pattern shows how to keep a child agent from acquiring authority its parent never had.
Never hand the agent the same credentials used by the CI administrator. Repository write access does not imply deployment access. Reading a secret name does not imply reading its value. Generating a CloudFormation change set does not imply executing it.
Sandbox the work, not only the shell
A container is a packaging boundary unless configured as a security boundary. Agent workspaces need:
- a fresh checkout or disposable worktree;
- no host Docker socket;
- a read-only base image and writable task volume;
- CPU, memory, process, disk, and wall-clock limits;
- egress allowlists or a dependency proxy;
- no ambient cloud credentials;
- tool calls through an authorization gateway;
- destruction when the task ends.
For hostile or unknown code, use stronger isolation. The Docker Sandbox and MicroVM security comparison explains why kernel sharing matters, and the Lambda MicroVM sandbox implementation shows a stateful alternative for untrusted execution.
The workspace path restriction must be enforced below the model. Reject symlink escapes, absolute paths, .. traversal, mounted sockets, and tool arguments that target outside the task root. Log the normalized target, not only the original string.
MCP is an authorization surface
MCP makes integrations easier. It does not make them safe by default. Treat each server configuration like an IAM policy.
| MCP design choice | Production rule |
|---|---|
| Tool catalog | Allowlist named tools per risk tier |
| Credential | Dedicated service identity, never the user’s exported token |
| Arguments | Validate against a schema and resource policy |
| Network | Restrict server and destination egress |
| Result | Label untrusted content before it re-enters model context |
| Audit | Record caller, task, tool, normalized arguments, decision, and result digest |
| Destructive action | Require a separate approval token bound to the exact action |
An approval should not be a reusable “yes.” Bind it to the resource, action, parameters, hash of the proposed change, approver, and expiration. If the agent changes the request, the approval no longer applies.
Build-time controls: verify every derivative artifact
Author-time controls help the agent produce better work. The pipeline decides whether that work can ship.
A practical sequence is:
scope check -> compile/lint -> unit tests -> secret scan -> SAST
-> dependency and SBOM scan -> IaC policy -> provenance/signature
-> spec-compliance review -> risk-based approval -> deployment
Fail early on cheap checks. A diff outside the allowlist should stop before a thirty-minute integration suite. Run the expensive and probabilistic reviews after deterministic hygiene passes.
For AWS-centered repositories, Automated Security Helper can aggregate security tools. Use Amazon Inspector or another SCA platform for dependencies. Generate an SBOM and sign the release. The SBOM and container-signing pipeline covers the evidence chain, while the GitLab SAST/DAST guide provides a concrete multi-scanner pipeline.
Enforce scope with a simple gate
#!/usr/bin/env bash
set -euo pipefail
git diff --name-only origin/main...HEAD > changed-files.txt
if rg -n '^(infra/|migrations/|\.github/workflows/)' changed-files.txt; then
echo "Privileged path changed; Tier 3 review required" >&2
exit 1
fi
changed_count=$(wc -l < changed-files.txt)
if [ "$changed_count" -gt 20 ]; then
echo "Task exceeded the 20-file scope boundary" >&2
exit 1
fi
The real pipeline should read the task metadata rather than hard-code one policy, but the example shows the important property: the model cannot negotiate with this check.
Add a non-deterministic review after tests
Ask a separate reviewer model to compare the spec, diff, tests, and steering rules. Require structured findings with file, line, violated requirement, confidence, and suggested test. Do not let the authoring model review itself and mark its own work safe.
Model review is advisory unless a human or deterministic rule confirms the finding. It is valuable for missing behavior and scope drift, not as a replacement for SAST or tests. Evaluate the reviewer against a labeled corpus before making it a merge gate.
Decide what can merge automatically
| Change | Auto-merge? | Reason |
|---|---|---|
| Documentation typo inside allowed path | Yes, after basic checks | Low impact and reversible |
| Generated test with no production-code change | Usually | Still enforce dependency and scope policy |
| Library patch update | Conditional | Require registry, lockfile, SCA, tests, and provenance |
| Application feature | No by default | Functional intent deserves owner review |
| IAM, network, secret, CI, or deployment change | No | Privilege and blast radius are high |
| Data migration or deletion | Never autonomously | Irreversible state change |
Organizations can relax this table from evidence. Start conservative. Measure false positives, escaped defects, review time, rollback rate, and incident contribution. Expand autonomous authority only for a class of changes with a stable success record.
Preserve evidence for every agent change
A pull request should carry:
- task and risk-tier metadata;
- model and agent version;
- steering and specification hashes;
- tools invoked and authorization decisions;
- source commit and generated diff;
- test, scan, SBOM, and policy results;
- reviewer findings and human approvals;
- artifact digest and deployment outcome.
Do not store raw secrets or complete sensitive tool responses in the trace. Record redacted arguments and cryptographic digests where content retention would create a new data leak.
This evidence supports incident response and control tuning. It also separates “the agent proposed it” from “the organization authorized and deployed it.”
Secure instructions and agent configuration as code
Steering files, MCP configuration, hooks, agent skills, and workflow prompts influence generated code. Treat them as privileged source. A pull request that changes .kiro/, AGENTS.md, MCP servers, or tool policy can be more dangerous than a production-code change.
Put those paths in Tier 3 by default. Require CODEOWNERS review from platform security, run schema validation, and display the effective tool diff. Sign released skill bundles or pin them by commit. Do not download the latest instruction package at session start.
Scan instructions for suspicious patterns such as disabling security tests, reading credential paths, adding arbitrary egress, weakening approvals, or directing output to external endpoints. A model-assisted review can help, but deterministic rules should protect known invariants.
Repository content remains untrusted to the executor until the orchestrator validates the task. A malicious README must not be able to edit the global steering file that every future session loads.
Build and exercise kill switches
Every agent platform needs stop controls at several layers:
| Kill switch | Effect |
|---|---|
| Revoke workload identity | Stops cloud and external tool access |
| Disable MCP provider | Removes an integration from all assigned tasks |
| Pause merge/deploy bot | Preserves proposals but blocks promotion |
| Deny agent session creation | Stops new work while active sandboxes expire |
| Network egress deny | Contains suspicious execution |
| Repository rule | Blocks agent-authored commits or pull requests |
Exercise them quarterly. Measure how long it takes to identify active sessions, revoke tokens, stop queued jobs, preserve evidence, and prevent deployment. A console button nobody has tested is not a control.
Define triggers: unauthorized tool attempts, leaked credential evidence, a compromised dependency, unexplained cross-repository changes, or a rollback-rate spike. One owner declares the stop; a separate owner approves resumption after cause and scope are understood.
When an agent incident occurs, preserve task metadata, prompts under retention policy, tool decisions, workspace snapshot, diff, credentials issued, and deployed artifacts. Rotate exposed credentials and search for the same generated pattern across repositories.
Run the framework as a measured rollout
Start with read-only tasks. Then allow local reversible edits in disposable sandboxes. Move to pull-request creation only after scope gates and identity boundaries have proven reliable. Privileged changes remain proposals until a separate operator executes them.
Track these metrics by risk tier:
| Metric | What it reveals |
|---|---|
| Accepted changes without rework | Useful agent precision |
| Scope violations per 100 tasks | Specification and enforcement quality |
| Security findings per 1,000 changed lines | Risk concentration |
| Human review minutes per accepted change | Whether automation reduces workload |
| Rollback and escaped-defect rate | Real production quality |
| Unauthorized tool attempts | Identity or prompt-injection pressure |
| Approval overrides and expiry | Governance health |
A fast agent that doubles review time is not productive. An agent with a low test-failure rate but a rising rollback rate is optimizing the wrong metric.
A 30-day implementation sequence
Week one: inventory agents, MCP servers, credentials, repositories, and direct production paths. Disable shared long-lived credentials. Define the five risk tiers.
Week two: add steering, task metadata, disposable workspaces, path restrictions, and tool allowlists. Make all production tools unavailable to the default identity.
Week three: enforce scope, tests, secrets, SAST, SCA, SBOM, and IaC policy in CI. Add branch protection so agents cannot bypass those jobs.
Week four: add structured model review, evidence bundles, dashboards, kill switches, and a low-risk auto-merge pilot. Exercise an incident in which untrusted issue text attempts to invoke a destructive tool.
Review the control plane when the agent changes
A model upgrade is a security-relevant change even when tool schemas and prompts stay constant. Re-run scope, injection, secrets, destructive-command, and review-bypass evaluations against the candidate. Compare not only task success but also tool selection, denied attempts, diff size, and requests for extra authority.
Apply the same discipline to MCP server upgrades, IDE extensions, runner images, steering files, and repository hooks. Each can alter what the agent observes or can execute. Pin versions where practical and promote them through a test environment before organization-wide rollout.
Keep one control independent of the agent vendor and model: branch protection, cloud authorization, workload isolation, or the deployment gate must still stop an unsafe change when the model behaves unexpectedly. Defense in depth is valuable here because agent behavior is probabilistic, while the final authority decision can remain deterministic.
The useful security boundary is not “a human watched the agent.” It is a chain of explicit authority, deterministic checks, bounded execution, and evidence. Let agents move quickly inside that boundary. Make the boundary itself boring, testable, and outside the model’s control.
Comments