AWS Builder Center

When IAM Meets Non Determinism: Enforcing Agentic Blast Radius at the Platform Layer

When IAM Meets Non-Determinism: Enforcing Agentic Blast Radius at the Platform Layer

Senior DevOps & SRE | IEEE Senior Member | AI Observability & Cloud Resilience

Traditional IAM was designed for deterministic code. It was never designed for an LLM that invents its own execution path at runtime.
When your agentic system has a valid IAM role and MCP tool access, the cloud provider executes whatever API calls arrive whether those calls were generated by a secure prompt, a hallucinated reasoning loop, or a prompt injection payload embedded in a retrieved log file. The IAM evaluation happens at the API boundary. It has no visibility into the reasoning trace that produced the call.
This creates a specific, underappreciated security architecture problem: the blast radius of an agentic system is currently bounded by its IAM role, not by any deterministic enforcement of what the agent is allowed to reason about vs. what it is allowed to execute. These need to be separate enforcement layers. They rarely are.
This post covers three production patterns for decoupling agentic reasoning authority from infrastructure execution authority on AWS, implemented as part of the  agentsre  library.



Why Standard IAM Fails Here

A standard IAM role evaluated against a standard API call works correctly for all three of these failure modes:
Failure Mode
IAM Response
Actual Risk
Reasoning loop → API storm
Authorizes every call in the loop
Rate exhaustion, cost spikes, self-inflicted degradation
Prompt injection via retrieved context
Authorizes the injected command
Full execution authority of the agent's role
Authority conflation (plan ≠ execute)
Authorizes execution of unvalidated plan
Production side effects from unreviewed actions
IAM evaluates the API call. It has no model of the reasoning session that produced it. Closing these gaps requires controls that operate above the IAM layer at the agent runtime, not at the permission boundary.



Pattern 1: Pre-Execution Policy Gate (Intent vs. Action Separation)

The enforcement point that most teams skip: between the agent producing a proposed action and that action reaching the AWS API.
The agent synthesizes a structured proposal. A deterministic policy engine no LLM in the critical path evaluates the proposal against explicit guardrails before any API call is made.
python
import boto3
import logging
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Optional

logger = logging.getLogger(__name__)

class ActionClass(str, Enum):
READ_ONLY = "READ_ONLY"
MUTATION = "MUTATION" # Config changes, scaling, restarts
DESTRUCTIVE = "DESTRUCTIVE" # Terminations, deletions, policy modifications

class EnvironmentTier(str, Enum):
SANDBOX = "SANDBOX"
STAGING = "STAGING"
PRODUCTION = "PRODUCTION"

@dataclass
class ProposedAction:
"""
Structured output of the agent reasoning layer.
This is what the agent is ALLOWED to produce — a proposal, not an execution.

The policy gate evaluates this before any AWS API call is made.
The agent has no path to self-authorize beyond what the gate approves.
"""
action_id: str
action_class: ActionClass
aws_service: str # e.g. "ecs", "ec2", "rds"
api_action: str # e.g. "StopInstances", "UpdateService"
resource_arn: str
parameters: dict
agent_reasoning_summary: str # Free-text rationale from the model
proposed_at_utc: datetime = field(default_factory=lambda: datetime.now(tz=timezone.utc))

@dataclass
class GateVerdict:
"""
Deterministic policy engine output.
approved=True is the ONLY path to live AWS API execution.
"""
action_id: str
approved: bool
rule_fired: str
environment_tier: EnvironmentTier
cooldown_remaining_seconds: int = 0
verdict_reason: str = ""

# Resource modification cooldown registry (resource ARN → last modified UTC)
# In production: back this with ElastiCache or DynamoDB for cross-instance state
_cooldown_registry: dict[str, datetime] = {}

COOLDOWN_SECONDS: dict[ActionClass, int] = {
ActionClass.READ_ONLY: 0,
ActionClass.MUTATION: 600, # 10 minutes between mutations on same resource
ActionClass.DESTRUCTIVE: 3600, # 1 hour between destructive ops on same resource
}

# Action classes permitted per environment tier
PERMITTED_ACTIONS: dict[EnvironmentTier, set[ActionClass]] = {
EnvironmentTier.SANDBOX: {ActionClass.READ_ONLY, ActionClass.MUTATION, ActionClass.DESTRUCTIVE},
EnvironmentTier.STAGING: {ActionClass.READ_ONLY, ActionClass.MUTATION},
EnvironmentTier.PRODUCTION: {ActionClass.READ_ONLY}, # Mutations always require human review in prod
}

def _resolve_environment_tier(resource_arn: str) -> EnvironmentTier:
"""
Resolve environment tier from resource ARN tags.
Requires resource to be tagged with Environment=sandbox|staging|production.
Falls back to PRODUCTION (fail-safe: unknown = most restrictive).
"""
try:
tagging = boto3.client("resourcegroupstaggingapi")
response = tagging.get_resources(ResourceARNList=[resource_arn])
resources = response.get("ResourceTagMappingList", [])
if not resources:
logger.warning(
"Resource not found in tag API — defaulting to PRODUCTION tier",
extra={"resource_arn": resource_arn},
)
return EnvironmentTier.PRODUCTION

tags = {t["Key"]: t["Value"] for t in resources[0].get("Tags", [])}
env_tag = tags.get("Environment", "").lower()
tier_map = {
"sandbox": EnvironmentTier.SANDBOX,
"staging": EnvironmentTier.STAGING,
"production": EnvironmentTier.PRODUCTION,
"prod": EnvironmentTier.PRODUCTION,
}
return tier_map.get(env_tag, EnvironmentTier.PRODUCTION)
except Exception as e:
logger.error(
"Tag resolution failed — defaulting to PRODUCTION (fail-safe)",
extra={"resource_arn": resource_arn, "error": str(e)},
)
return EnvironmentTier.PRODUCTION # Always fail toward most restrictive

def evaluate_proposed_action(action: ProposedAction) -> GateVerdict:
"""
Pre-execution policy gate: deterministic evaluation of a proposed action
before any AWS API call is made.

Rules evaluated (in order — first match wins):
1. Destructive actions against production → always blocked
2. Mutation actions against production → always blocked (human review required)
3. Cooldown check → blocked if resource was modified within the cooldown window
4. All other cases → approved

The LLM agent has NO path to influence this evaluation. The gate is
entirely deterministic and operates on structured data from the proposal,
not on the agent's reasoning_summary.

Parameters
----------
action : ProposedAction
Structured action proposal from the agent reasoning layer.

Returns
-------
GateVerdict
approved=True is required for any live AWS API execution.
Logs full context to CloudWatch on every verdict.

Example
-------
>>> verdict = evaluate_proposed_action(proposed)
>>> if not verdict.approved:
... logger.warning("Gate blocked: %s", verdict.verdict_reason)
... return # Never reaches AWS API
"""
env_tier = _resolve_environment_tier(action.resource_arn)
now = datetime.now(tz=timezone.utc)

# Rule 1 & 2: Tier-based action class enforcement
permitted = PERMITTED_ACTIONS.get(env_tier, set())
if action.action_class not in permitted:
verdict = GateVerdict(
action_id=action.action_id,
approved=False,
rule_fired="TIER_ACTION_CLASS_BLOCK",
environment_tier=env_tier,
verdict_reason=(
f"Action class {action.action_class} not permitted in {env_tier} tier. "
f"Permitted classes: {[a.value for a in permitted]}. "
f"Human review required for mutations against {env_tier}."
),
)
_log_verdict(verdict, action)
return verdict

# Rule 3: Cooldown check
cooldown_seconds = COOLDOWN_SECONDS.get(action.action_class, 0)
if cooldown_seconds > 0 and action.resource_arn in _cooldown_registry:
last_modified = _cooldown_registry[action.resource_arn]
elapsed = (now - last_modified).total_seconds()
if elapsed < cooldown_seconds:
remaining = int(cooldown_seconds - elapsed)
verdict = GateVerdict(
action_id=action.action_id,
approved=False,
rule_fired="COOLDOWN_ACTIVE",
environment_tier=env_tier,
cooldown_remaining_seconds=remaining,
verdict_reason=(
f"Resource {action.resource_arn} was last modified {int(elapsed)}s ago. "
f"Cooldown for {action.action_class}: {cooldown_seconds}s. "
f"Remaining: {remaining}s."
),
)
_log_verdict(verdict, action)
return verdict

# Approved: register modification time for cooldown tracking
if action.action_class != ActionClass.READ_ONLY:
_cooldown_registry[action.resource_arn] = now

verdict = GateVerdict(
action_id=action.action_id,
approved=True,
rule_fired="APPROVED",
environment_tier=env_tier,
verdict_reason=f"Action class {action.action_class} approved for {env_tier} tier.",
)
_log_verdict(verdict, action)
return verdict

def _log_verdict(verdict: GateVerdict, action: ProposedAction):
level = logging.INFO if verdict.approved else logging.WARNING
logger.log(
level,
"Policy gate verdict",
extra={
"action_id": verdict.action_id,
"approved": verdict.approved,
"rule_fired": verdict.rule_fired,
"environment_tier": verdict.environment_tier,
"action_class": action.action_class,
"aws_service": action.aws_service,
"api_action": action.api_action,
"resource_arn": action.resource_arn,
"verdict_reason": verdict.verdict_reason,
},
)
The critical design constraint: the  agent_reasoning_summary  field on  ProposedAction  is logged for observability but never evaluated by the gate. The gate operates on structured fields only. The model's free-text reasoning cannot influence the policy evaluation.



Pattern 2: Runtime Session Monitor with Authority Severance

This is the circuit breaker for reasoning loops and API storms. It tracks tool-calling telemetry at the session level and severs IAM authority when anomalous patterns are detected.
python
import time
import threading
import boto3
import logging
from dataclasses import dataclass, field
from collections import deque
from typing import Optional

logger = logging.getLogger(__name__)

@dataclass
class SessionConfig:
"""
Thresholds for a monitored agent session.
Tune per agent type and environment tier.
"""
session_id: str
agent_id: str
iam_role_arn: str # Role to suspend on threshold breach
max_calls_per_minute: int = 20
max_session_cost_usd: float = 5.0
max_resource_modifications: int = 10
max_session_duration_seconds: int = 300 # 5-minute hard cap
sns_alert_topic_arn: Optional[str] = None

@dataclass
class SessionTelemetry:
"""Live telemetry for an active agent session."""
session_id: str
call_timestamps: deque = field(default_factory=lambda: deque(maxlen=1000))
estimated_cost_usd: float = 0.0
resource_modifications: int = 0
session_start: float = field(default_factory=time.time)
authority_severed: bool = False
severance_reason: str = ""

class AgentSessionMonitor:
"""
Runtime monitor for agentic tool-calling sessions.

Tracks API call rate, estimated cost, and resource modification count
per session. When any threshold is crossed, the session's IAM role is
suspended via an inline deny policy and the on-call engineer is paged.

The agent can continue reasoning after severance. It cannot execute.

This directly addresses the "reasoning loop → API storm" failure class:
the circuit trips at the infrastructure layer, not at the model layer.

Parameters
----------
config : SessionConfig
Threshold configuration for this session.

Example
-------
>>> monitor = AgentSessionMonitor(config)
>>> monitor.start()
>>> # In the agent execution loop:
>>> if not monitor.record_call(estimated_cost_usd=0.002, is_mutation=True):
... raise RuntimeError("Session authority severed — tool-calling suspended")
"""

def __init__(self, config: SessionConfig):
self.config = config
self._telemetry = SessionTelemetry(session_id=config.session_id)
self._lock = threading.Lock()
self._iam = boto3.client("iam")
self._sns = boto3.client("sns") if config.sns_alert_topic_arn else None
self._monitor_thread: Optional[threading.Thread] = None

def start(self):
"""Start the background session duration monitor."""
self._monitor_thread = threading.Thread(
target=self._duration_watchdog, daemon=True
)
self._monitor_thread.start()
logger.info(
"Agent session monitor started",
extra={
"session_id": self.config.session_id,
"agent_id": self.config.agent_id,
"max_calls_per_minute": self.config.max_calls_per_minute,
"max_resource_modifications": self.config.max_resource_modifications,
},
)

def record_call(
self,
estimated_cost_usd: float = 0.0,
is_mutation: bool = False,
) -> bool:
"""
Record a tool call and evaluate thresholds.

Call this BEFORE executing each tool call. If it returns False,
the session's authority has been severed — do not proceed with
the API call.

Parameters
----------
estimated_cost_usd : float
Estimated AWS cost of this API call for budget tracking.
is_mutation : bool
True if this call modifies infrastructure state.

Returns
-------
bool
True if the call is permitted.
False if authority has been severed (call must not proceed).
"""
with self._lock:
if self._telemetry.authority_severed:
return False

now = time.time()
self._telemetry.call_timestamps.append(now)
self._telemetry.estimated_cost_usd += estimated_cost_usd
if is_mutation:
self._telemetry.resource_modifications += 1

# Check: calls per minute (rolling 60s window)
window_start = now - 60
calls_in_window = sum(
1 for t in self._telemetry.call_timestamps if t >= window_start
)
if calls_in_window > self.config.max_calls_per_minute:
return self._sever_authority(
f"API call rate exceeded: {calls_in_window} calls in last 60s "
f"(limit: {self.config.max_calls_per_minute}). "
"Possible reasoning loop detected."
)

# Check: session cost budget
if self._telemetry.estimated_cost_usd > self.config.max_session_cost_usd:
return self._sever_authority(
f"Session cost budget exceeded: "
f"${self._telemetry.estimated_cost_usd:.4f} "
f"(limit: ${self.config.max_session_cost_usd:.2f})"
)

# Check: resource modification count
if self._telemetry.resource_modifications > self.config.max_resource_modifications:
return self._sever_authority(
f"Resource modification limit exceeded: "
f"{self._telemetry.resource_modifications} modifications "
f"(limit: {self.config.max_resource_modifications})"
)

return True

def _duration_watchdog(self):
"""Background thread: enforce max session duration."""
time.sleep(self.config.max_session_duration_seconds)
with self._lock:
if not self._telemetry.authority_severed:
self._sever_authority(
f"Session duration limit reached: "
f"{self.config.max_session_duration_seconds}s hard cap"
)

def _sever_authority(self, reason: str) -> bool:
"""
Sever the session's IAM execution authority.

Attaches an inline deny policy to the session's IAM role that blocks
all write-class API calls. The role retains read access so the agent
can continue observing — it cannot execute.

Returns False always (caller should treat this as a circuit open).
"""
self._telemetry.authority_severed = True
self._telemetry.severance_reason = reason

logger.error(
"Agent session authority severed",
extra={
"session_id": self.config.session_id,
"agent_id": self.config.agent_id,
"iam_role_arn": self.config.iam_role_arn,
"reason": reason,
"total_calls": len(self._telemetry.call_timestamps),
"total_cost_usd": self._telemetry.estimated_cost_usd,
"resource_modifications": self._telemetry.resource_modifications,
},
)

# Attach inline deny policy to block write-class actions
try:
import json
role_name = self.config.iam_role_arn.split("/")[-1]
deny_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AgentSessionCircuitBreaker",
"Effect": "Deny",
"Action": [
"ec2:*",
"ecs:*",
"rds:*",
"eks:*",
"autoscaling:*",
"elasticloadbalancing:*",
"lambda:InvokeFunction",
"ssm:StartSession",
"ssm:SendCommand",
],
"Resource": "*",
"Condition": {
"StringEquals": {
"aws:RequestedRegion": boto3.session.Session().region_name or "us-east-1"
}
},
}
],
}
self._iam.put_role_policy(
RoleName=role_name,
PolicyName=f"circuit-breaker-{self.config.session_id}",
PolicyDocument=json.dumps(deny_policy),
)
logger.info(
"IAM circuit breaker policy attached",
extra={"role_name": role_name, "session_id": self.config.session_id},
)
except Exception as e:
logger.critical(
"FAILED to attach IAM circuit breaker policy — manual intervention required",
extra={"error": str(e), "iam_role_arn": self.config.iam_role_arn},
)

# Page on-call
if self._sns:
try:
self._sns.publish(
TopicArn=self.config.sns_alert_topic_arn,
Subject=f"[CRITICAL] Agent session authority severed — {self.config.agent_id}",
Message=(
f"Session ID: {self.config.session_id}\n"
f"Agent ID: {self.config.agent_id}\n"
f"IAM Role: {self.config.iam_role_arn}\n"
f"Reason: {reason}\n"
f"Total API calls this session: {len(self._telemetry.call_timestamps)}\n"
f"Estimated cost: ${self._telemetry.estimated_cost_usd:.4f}\n"
f"Resource modifications: {self._telemetry.resource_modifications}\n\n"
"ACTION REQUIRED: Review the agent session, validate no unintended "
"infrastructure changes occurred, then manually remove the "
f"circuit-breaker-{self.config.session_id} inline policy from the role."
),
)
except Exception as e:
logger.error("SNS alert failed", extra={"error": str(e)})

return False

def cleanup(self):
"""
Remove the circuit breaker policy on clean session end.
Call this when the session completes normally.
"""
try:
role_name = self.config.iam_role_arn.split("/")[-1]
self._iam.delete_role_policy(
RoleName=role_name,
PolicyName=f"circuit-breaker-{self.config.session_id}",
)
except self._iam.exceptions.NoSuchEntityException:
pass # Policy was never attached (clean session)
except Exception as e:
logger.warning("Session cleanup failed", extra={"error": str(e)})



Pattern 3: Isolated Sandbox Session Manager

Agents executing scripts or commands against infrastructure should never run with persistent credentials in shared terminal space. This pattern provisions short-lived ECS task environments with session-scoped IAM roles.
python
import uuid
import boto3
import logging
from dataclasses import dataclass
from typing import Optional

logger = logging.getLogger(__name__)

@dataclass
class SandboxConfig:
"""
Configuration for an isolated agent execution sandbox.

Each sandbox is a short-lived ECS task with:
- A session-scoped IAM role assumed at task start (expires at task end)
- Resource tag-based scope limiting (agents only see tagged resources)
- Network egress restricted to a defined CIDR allowlist
- A hard TTL after which the task is force-terminated
"""
agent_id: str
ecs_cluster_arn: str
task_definition_arn: str
subnet_ids: list[str]
security_group_ids: list[str]
base_iam_role_arn: str # Role assumed by the sandbox task
session_ttl_seconds: int = 300 # 5-minute hard cap
resource_tag_scope: Optional[dict] = None # e.g. {"Environment": "sandbox"}
sns_alert_topic_arn: Optional[str] = None

@dataclass
class SandboxSession:
"""A provisioned sandbox session for a single agent execution."""
sandbox_id: str
ecs_task_arn: str
assumed_role_arn: str
session_credentials: dict
expires_at_epoch: float

class AgentSandboxManager:
"""
Provisions and governs isolated ECS-based execution environments
for agentic infrastructure operations.

Each sandbox:
- Runs in a dedicated ECS task (not shared with other agents or services)
- Uses credentials assumed for the session duration only (no persistent keys)
- Expires automatically at session_ttl_seconds regardless of task state
- Has structural blast radius limits via resource tag-based IAM conditions

The sandbox is the answer to "what if the agent's IAM role is the blast radius?"
The session-scoped role has a bounded resource scope. When the session ends,
the credentials are gone. There is no carry-over between executions.

Parameters
----------
config : SandboxConfig
Configuration for sandbox provisioning.

Example
-------
>>> manager = AgentSandboxManager(config)
>>> session = manager.provision_sandbox()
>>> try:
... # Run agent with session.session_credentials
... agent.run(credentials=session.session_credentials)
... finally:
... manager.terminate_sandbox(session)
"""

def __init__(self, config: SandboxConfig):
self.config = config
self._ecs = boto3.client("ecs")
self._sts = boto3.client("sts")

def provision_sandbox(self) -> SandboxSession:
"""
Provision a new isolated execution sandbox for an agent session.

Assumes a session-scoped IAM role with a TTL-bound session policy,
then launches an ECS task using those credentials.

Returns
-------
SandboxSession
Contains the ECS task ARN and scoped session credentials.
Credentials expire at sandbox TTL.

Raises
------
RuntimeError
If ECS task launch or role assumption fails.
"""
sandbox_id = f"sandbox-{self.config.agent_id}-{uuid.uuid4().hex[:8]}"
import time
expires_at = time.time() + self.config.session_ttl_seconds

# Build a session policy that restricts the assumed role to tagged resources
session_policy = self._build_session_policy()

# Assume session-scoped role
try:
sts_response = self._sts.assume_role(
RoleArn=self.config.base_iam_role_arn,
RoleSessionName=sandbox_id,
DurationSeconds=self.config.session_ttl_seconds,
Policy=session_policy,
)
except Exception as e:
raise RuntimeError(
f"Failed to assume sandbox role {self.config.base_iam_role_arn}: {e}"
) from e

credentials = sts_response["Credentials"]
assumed_role_arn = sts_response["AssumedRoleUser"]["Arn"]

# Launch isolated ECS task
try:
task_response = self._ecs.run_task(
cluster=self.config.ecs_cluster_arn,
taskDefinition=self.config.task_definition_arn,
launchType="FARGATE",
networkConfiguration={
"awsvpcConfiguration": {
"subnets": self.config.subnet_ids,
"securityGroups": self.config.security_group_ids,
"assignPublicIp": "DISABLED",
}
},
overrides={
"containerOverrides": [
{
"name": "agent-sandbox",
"environment": [
{"name": "SANDBOX_ID", "value": sandbox_id},
{"name": "AGENT_ID", "value": self.config.agent_id},
{"name": "AWS_ACCESS_KEY_ID", "value": credentials["AccessKeyId"]},
{"name": "AWS_SECRET_ACCESS_KEY", "value": credentials["SecretAccessKey"]},
{"name": "AWS_SESSION_TOKEN", "value": credentials["SessionToken"]},
{"name": "SESSION_TTL_SECONDS", "value": str(self.config.session_ttl_seconds)},
],
}
]
},
tags=[
{"key": "SandboxId", "value": sandbox_id},
{"key": "AgentId", "value": self.config.agent_id},
{"key": "ManagedBy", "value": "agentsre"},
],
)
except Exception as e:
raise RuntimeError(f"Failed to launch sandbox ECS task: {e}") from e

task_arn = task_response["tasks"][0]["taskArn"]

logger.info(
"Agent sandbox provisioned",
extra={
"sandbox_id": sandbox_id,
"agent_id": self.config.agent_id,
"ecs_task_arn": task_arn,
"assumed_role_arn": assumed_role_arn,
"session_ttl_seconds": self.config.session_ttl_seconds,
},
)

return SandboxSession(
sandbox_id=sandbox_id,
ecs_task_arn=task_arn,
assumed_role_arn=assumed_role_arn,
session_credentials={
"AccessKeyId": credentials["AccessKeyId"],
"SecretAccessKey": credentials["SecretAccessKey"],
"SessionToken": credentials["SessionToken"],
"Expiration": credentials["Expiration"].isoformat(),
},
expires_at_epoch=expires_at,
)

def terminate_sandbox(self, session: SandboxSession):
"""
Terminate a sandbox session and stop the ECS task.

The session-scoped credentials expire automatically at TTL.
This method ensures the ECS task is also stopped, preventing
orphaned tasks from accumulating.
"""
try:
self._ecs.stop_task(
cluster=self.config.ecs_cluster_arn,
task=session.ecs_task_arn,
reason=f"Normal sandbox session end: {session.sandbox_id}",
)
logger.info(
"Agent sandbox terminated",
extra={
"sandbox_id": session.sandbox_id,
"ecs_task_arn": session.ecs_task_arn,
},
)
except Exception as e:
logger.error(
"Failed to stop sandbox ECS task — manual cleanup required",
extra={"ecs_task_arn": session.ecs_task_arn, "error": str(e)},
)

def _build_session_policy(self) -> str:
"""
Build an inline session policy that restricts the assumed role
to resources matching the configured tag scope.

This provides structural blast radius containment: even if the
base role has broad permissions, the session policy limits the
effective scope to resources tagged for sandbox use.
"""
import json

if not self.config.resource_tag_scope:
# No tag scope configured — allow all (base role permissions apply)
return json.dumps({
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "*", "Resource": "*"}],
})

# Build tag condition for all configured scope tags
tag_conditions = {
f"aws:ResourceTag/{k}": v
for k, v in self.config.resource_tag_scope.items()
}

return json.dumps({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["ec2:Describe*", "ecs:Describe*", "ecs:List*",
"cloudwatch:GetMetricData", "logs:GetLogEvents"],
"Resource": "*", # Read-only ops don't need tag scoping
},
{
"Effect": "Allow",
"Action": ["ec2:*", "ecs:*", "rds:*", "autoscaling:*"],
"Resource": "*",
"Condition": {"StringEquals": tag_conditions},
},
],
})



Composing the Three Patterns

All three patterns compose into a complete agentic security control plane:
Agent Reasoning Layer
│
▼ (ProposedAction — structured, not free text)
┌──────────────────────────┐
│ Pattern 1: Policy Gate │ ← Deterministic. No LLM in critical path.
│ - Tier enforcement │ Blocks production mutations, enforces
│ - Cooldown registry │ cooldowns, logs every verdict.
└──────────┬───────────────┘
│ (approved verdicts only)
▼
┌──────────────────────────┐
│ Pattern 2: Session Mon │ ← Runtime circuit breaker.
│ - Call rate limiter │ Severs IAM authority on anomaly.
│ - Cost budget tracker │ Pages on-call. Agent can still reason.
│ - Mod count limiter │ It cannot execute.
└──────────┬───────────────┘
│ (within thresholds only)
▼
┌──────────────────────────┐
│ Pattern 3: Sandbox │ ← Structural blast radius containment.
│ - Session-scoped creds │ Short-lived ECS task. Credentials
│ - Tag-scoped policy │ expire at session end. No carry-over.
│ - Hard TTL enforcement │
└──────────────────────────┘
│
▼
AWS API Call
The agent's IAM role is no longer the blast radius. The policy gate, the session monitor, and the sandbox scope collectively define what any single agent session can actually reach — deterministically, without delegating that question to the model's reasoning.
These patterns ship as the  agentic_security  module in the  agentsre  library.


How is your team structurally decoupling the reasoning layer from the execution authority boundary? Drop the implementation detail in the comments.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article