Cloud IAM, Networking, Secrets & Rollouts
Model least-privilege IAM permissions, private network egress boundaries, short-lived or managed secret resolution, and staged canary rollouts with rollback gates in fde-04-3 using pytest and GitHub Actions.
A containerized service with healthy probes can still create serious operational risk if it runs with over-broad IAM permissions, exposes internal dependencies unnecessarily, stores static secrets in config files, or cuts over 100% of traffic without canary guardrails.
In this module, you will build deterministic policy, secret-lease, network-boundary, and staged rollout evaluators in fde-04-3, verified with a pytest suite and a GitHub Actions workflow.
Enterprise Scenario: Northwind Freight
Northwind’s infrastructure team is preparing to deploy the freight-exception triage service into a cloud environment connected to internal shipment tables, a secret store, and external carrier APIs. Before promoting a rollout stage, deployment checks must verify least-privilege IAM rules, private egress controls, short-lived secret leases, and canary health thresholds.
What You Will Build
- IAM, network, secret, and rollout schemas: Define strict Pydantic v2 models in
src/fde_04_3/schemas.pywithextra="forbid",strict=True, and range/non-blank validation. - Security and rollout evaluators: Implement
evaluate_iam_policy,evaluate_network_and_secrets,evaluate_rollout_stages, andevaluate_deployment_gateinsrc/fde_04_3/controls.py. - Automated tests and CI pipeline: Add unit tests in
tests/test_controls.pyand run verification locally and in.github/workflows/tests.yml.
1. Least Privilege, Private Networking, Secrets, and Staged Rollouts
- Least-privilege IAM: Grant only specific actions and resources. This teaching evaluator rejects wildcard actions or resources on every rule, including read-only rules.
- Private networking and secret rotation: Require private egress, check every requested endpoint against an explicit allow-list, accept only the documented managed-reference formats (
secretsmanager://andvault://), reject inline values, and enforce lease TTL limits. The reference-format check is illustrative; real deployments must verify the provider-side secret identity and access policy. - Staged canary rollouts with rollback triggers: Require at least two uniquely named stages, strictly increasing traffic percentages, and a final 100% stage. Trigger rollback if any stage exceeds the configured error-rate or P95-latency ceiling.
- Teaching scope boundary: This teaching module models cloud IAM, network, secret-lease, and rollout checks as deterministic Python rules so you can test them offline in CI. Real cloud deployments pair these checks with provider IAM policies, VPC security groups/private links, secret managers, and automated traffic-shifting controllers.
Deployment Guardrail Layers
| Layer | What it checks | Failure behavior |
|---|---|---|
| IAM policy | No wildcard * in any action or resource; explicit non-blank scope | Flags over-broad IAM rules and blocks gate |
| Network & secrets | Requested endpoints must be allow-listed; private egress enabled; managed secret references only; lease TTL bounded and unexpired | Flags insecure networking or secret hygiene issues |
| Canary rollout | At least two uniquely named, strictly increasing traffic stages ending at 100%; error/latency ceilings | Triggers rollback recommendation and blocks promotion |
2. Step-by-Step Build Walkthrough
- Create the
fde-04-3repository and project scaffold:mkdir -p fde-04-3/src/fde_04_3 fde-04-3/tests fde-04-3/.github/workflows cd fde-04-3 git init cat > .gitignore <<'EOF' .venv/ .env __pycache__/ .pytest_cache/ *.egg-info/ dist/ build/ EOF cat > pyproject.toml <<'EOF' [build-system] requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [project] name = "fde-04-3" version = "0.1.0" description = "Cloud IAM, private networking, secret leases, and staged canary rollouts" requires-python = ">=3.11" dependencies = ["pydantic>=2.6,<3"] [project.optional-dependencies] dev = ["pytest>=8.0,<9"] [tool.setuptools.packages.find] where = ["src"] [tool.pytest.ini_options] testpaths = ["tests"] EOF cat > .env.example <<'EOF' # Deterministic offline deployment policy checks; no cloud credentials required. EOF python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .env - Define strict Pydantic v2 schemas in
src/fde_04_3/schemas.py:"""Strict Pydantic v2 schemas for IAM, networking, secret leases, and rollouts.""" from __future__ import annotations import math from pydantic import BaseModel, ConfigDict, Field, field_validator def _require_non_blank(value: str, field_name: str) -> str: cleaned = value.strip() if not cleaned: raise ValueError(f"{field_name} must not be blank") return cleaned def _require_finite_non_negative(value: float, field_name: str) -> float: if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError(f"{field_name} must be a finite number, not bool") numeric = float(value) if not math.isfinite(numeric) or numeric < 0.0: raise ValueError(f"{field_name} must be a non-negative finite number") return numeric def _require_positive_int(value: int, field_name: str) -> int: if isinstance(value, bool) or not isinstance(value, int): raise ValueError(f"{field_name} must be an integer, not bool") if value < 1: raise ValueError(f"{field_name} must be at least 1") return value class IamPolicyRule(BaseModel): """Single permission rule attached to a service identity.""" model_config = ConfigDict(extra="forbid", strict=True) role_name: str = Field(min_length=1) action: str = Field(min_length=1) resource: str = Field(min_length=1) mutating: bool = False @field_validator("role_name", "action", "resource") @classmethod def _validate_text(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) class NetworkBoundaryPolicy(BaseModel): """Private egress policy plus the endpoints this workload actually needs.""" model_config = ConfigDict(extra="forbid", strict=True) vpc_id: str = Field(min_length=1) private_egress_only: bool = True allowed_private_endpoints: list[str] = Field(min_length=1) requested_private_endpoints: list[str] = Field(min_length=1) @field_validator("vpc_id") @classmethod def _validate_vpc(cls, value: str) -> str: return _require_non_blank(value, "vpc_id") @field_validator("allowed_private_endpoints", "requested_private_endpoints") @classmethod def _validate_endpoints(cls, values: list[str], info) -> list[str]: cleaned = [_require_non_blank(item, info.field_name) for item in values] if len(cleaned) != len(set(cleaned)): raise ValueError(f"{info.field_name} must not contain duplicates") return cleaned class SecretLeaseRecord(BaseModel): """Managed secret reference and lease metadata; never stores raw values.""" model_config = ConfigDict(extra="forbid", strict=True) secret_name: str = Field(min_length=1) secret_ref: str = Field(min_length=1) lease_ttl_seconds: int max_allowed_ttl_seconds: int = Field(default=3600) expired: bool = False inline_value_present: bool = False @field_validator("secret_name") @classmethod def _validate_secret_name(cls, value: str) -> str: return _require_non_blank(value, "secret_name") @field_validator("secret_ref") @classmethod def _validate_secret_ref(cls, value: str) -> str: cleaned = _require_non_blank(value, "secret_ref") supported_prefixes = ("secretsmanager://", "vault://") has_supported_path = any( cleaned.startswith(prefix) and bool(cleaned[len(prefix):].strip("/")) for prefix in supported_prefixes ) if ( not has_supported_path or any(character.isspace() for character in cleaned) or "?" in cleaned or "#" in cleaned ): raise ValueError( "secret_ref must be a non-blank managed reference using " "secretsmanager:// or vault://, without whitespace, query, or fragment" ) return cleaned @field_validator("lease_ttl_seconds", "max_allowed_ttl_seconds") @classmethod def _validate_ttls(cls, value: int, info) -> int: ttl = _require_positive_int(value, info.field_name) if info.field_name == "max_allowed_ttl_seconds" and ttl > 86400: raise ValueError("max_allowed_ttl_seconds must not exceed 86400") return ttl class RolloutStage(BaseModel): """Single traffic stage and observed telemetry for a canary rollout.""" model_config = ConfigDict(extra="forbid", strict=True) stage_name: str = Field(min_length=1) traffic_percent: int observed_error_rate: float observed_p95_latency_ms: float max_error_rate: float = Field(default=0.02) max_p95_latency_ms: float = Field(default=800.0) @field_validator("stage_name") @classmethod def _validate_stage_name(cls, value: str) -> str: return _require_non_blank(value, "stage_name") @field_validator("traffic_percent") @classmethod def _validate_traffic_percent(cls, value: int) -> int: if isinstance(value, bool) or not isinstance(value, int): raise ValueError("traffic_percent must be an integer, not bool") if value < 1 or value > 100: raise ValueError("traffic_percent must be between 1 and 100") return value @field_validator( "observed_error_rate", "observed_p95_latency_ms", "max_error_rate", "max_p95_latency_ms", ) @classmethod def _validate_metrics(cls, value: float, info) -> float: numeric = _require_finite_non_negative(value, info.field_name) if info.field_name in {"observed_error_rate", "max_error_rate"} and numeric > 1.0: raise ValueError(f"{info.field_name} must be between 0.0 and 1.0") return numeric class DeploymentGateResult(BaseModel): """Combined outcome across IAM, network/secret, and rollout checks.""" model_config = ConfigDict(extra="forbid", strict=True) approved: bool iam_ok: bool network_and_secrets_ok: bool rollout_ok: bool rollback_recommended: bool findings: list[str] = Field(default_factory=list) - Implement IAM, network/secret, and rollout checks in
src/fde_04_3/controls.py:"""Policy evaluations for cloud IAM, networking, secret leases, and canary rollouts.""" from __future__ import annotations from fde_04_3.schemas import ( DeploymentGateResult, IamPolicyRule, NetworkBoundaryPolicy, RolloutStage, SecretLeaseRecord, ) def evaluate_iam_policy(rules: list[IamPolicyRule]) -> tuple[bool, list[str]]: """Reject wildcard actions/resources for every permission, including read-only rules.""" if not rules: return False, ["IAM policy must define at least one rule"] findings: list[str] = [] for rule in rules: if "*" in rule.action or "*" in rule.resource: findings.append( f"IAM rule '{rule.role_name}' uses a wildcard " f"(action='{rule.action}', resource='{rule.resource}')" ) return len(findings) == 0, findings def evaluate_network_and_secrets( network: NetworkBoundaryPolicy, secrets: list[SecretLeaseRecord], ) -> tuple[bool, list[str]]: """Validate private egress, requested endpoint allow-list, and managed secret leases.""" findings: list[str] = [] if not network.private_egress_only: findings.append(f"VPC '{network.vpc_id}' does not enforce private_egress_only") allowed = set(network.allowed_private_endpoints) for endpoint in network.requested_private_endpoints: if endpoint not in allowed: findings.append( f"Requested endpoint '{endpoint}' is not in the allowed private endpoint list" ) if not secrets: findings.append("At least one managed secret lease must be configured") for secret in secrets: if secret.inline_value_present: findings.append( f"Secret '{secret.secret_name}' has an inline value instead of a managed reference" ) if secret.expired: findings.append(f"Secret lease for '{secret.secret_name}' is expired") if secret.lease_ttl_seconds > secret.max_allowed_ttl_seconds: findings.append( f"Secret '{secret.secret_name}' TTL ({secret.lease_ttl_seconds}s) exceeds " f"max allowed ({secret.max_allowed_ttl_seconds}s)" ) return len(findings) == 0, findings def evaluate_rollout_stages(stages: list[RolloutStage]) -> tuple[bool, bool, list[str]]: """Require a genuine multi-stage canary and enforce rollback telemetry thresholds.""" if len(stages) < 2: return False, False, ["Rollout plan must define at least two stages for a canary"] findings: list[str] = [] rollback_needed = False previous_percent = 0 seen_names: set[str] = set() for stage in stages: if stage.stage_name in seen_names: findings.append(f"Duplicate rollout stage name '{stage.stage_name}'") seen_names.add(stage.stage_name) if stage.traffic_percent <= previous_percent: findings.append( f"Stage '{stage.stage_name}' traffic ({stage.traffic_percent}%) is not " f"strictly greater than previous stage ({previous_percent}%)" ) previous_percent = stage.traffic_percent if stage.observed_error_rate > stage.max_error_rate: rollback_needed = True findings.append( f"Stage '{stage.stage_name}' error rate ({stage.observed_error_rate}) " f"exceeded max ({stage.max_error_rate}); trigger rollback" ) if stage.observed_p95_latency_ms > stage.max_p95_latency_ms: rollback_needed = True findings.append( f"Stage '{stage.stage_name}' P95 latency ({stage.observed_p95_latency_ms}ms) " f"exceeded max ({stage.max_p95_latency_ms}ms); trigger rollback" ) if stages[-1].traffic_percent != 100: findings.append( f"Final rollout stage '{stages[-1].stage_name}' must reach 100% traffic " f"(got {stages[-1].traffic_percent}%)" ) rollout_ok = len(findings) == 0 and not rollback_needed return rollout_ok, rollback_needed, findings def evaluate_deployment_gate( iam_rules: list[IamPolicyRule], network: NetworkBoundaryPolicy, secrets: list[SecretLeaseRecord], rollout_stages: list[RolloutStage], ) -> DeploymentGateResult: """Evaluate all deployment guardrails before approving a release.""" iam_ok, iam_findings = evaluate_iam_policy(iam_rules) net_sec_ok, net_sec_findings = evaluate_network_and_secrets(network, secrets) rollout_ok, rollback_needed, rollout_findings = evaluate_rollout_stages(rollout_stages) all_findings = [*iam_findings, *net_sec_findings, *rollout_findings] approved = iam_ok and net_sec_ok and rollout_ok and not rollback_needed return DeploymentGateResult( approved=approved, iam_ok=iam_ok, network_and_secrets_ok=net_sec_ok, rollout_ok=rollout_ok, rollback_recommended=rollback_needed, findings=all_findings, ) - Add unit tests in
tests/test_controls.py:"""Tests for IAM least privilege, network allow-lists, secret leases, and canary rollouts.""" from __future__ import annotations import pytest from pydantic import ValidationError from fde_04_3.controls import ( evaluate_deployment_gate, evaluate_iam_policy, evaluate_network_and_secrets, evaluate_rollout_stages, ) from fde_04_3.schemas import ( IamPolicyRule, NetworkBoundaryPolicy, RolloutStage, SecretLeaseRecord, ) def _valid_inputs(): iam = [ IamPolicyRule( role_name="northwind-triage-role", action="shipments:ReadStatus", resource="arn:aws:s3:::northwind-manifests/prod/object-1", mutating=False, ), IamPolicyRule( role_name="northwind-triage-role", action="claims:CreateDraft", resource="arn:aws:sqs:us-east-1:123456789012:claim-drafts", mutating=True, ), ] network = NetworkBoundaryPolicy( vpc_id="vpc-northwind-prod", private_egress_only=True, allowed_private_endpoints=["vpce-secretsmanager", "vpce-rds-shipments"], requested_private_endpoints=["vpce-secretsmanager", "vpce-rds-shipments"], ) secrets = [ SecretLeaseRecord( secret_name="carrier_api_token", secret_ref="secretsmanager://northwind/prod/carrier-token", lease_ttl_seconds=900, max_allowed_ttl_seconds=3600, expired=False, inline_value_present=False, ) ] stages = [ RolloutStage( stage_name="canary-10", traffic_percent=10, observed_error_rate=0.005, observed_p95_latency_ms=320.0, ), RolloutStage( stage_name="full-100", traffic_percent=100, observed_error_rate=0.008, observed_p95_latency_ms=350.0, ), ] return iam, network, secrets, stages def test_approves_valid_deployment() -> None: iam, network, secrets, stages = _valid_inputs() result = evaluate_deployment_gate(iam, network, secrets, stages) assert result.approved is True assert result.iam_ok is True assert result.network_and_secrets_ok is True assert result.rollout_ok is True assert result.rollback_recommended is False assert result.findings == [] def test_rejects_wildcard_read_only_permission() -> None: rule = IamPolicyRule( role_name="reader", action="*", resource="arn:example:resource", mutating=False, ) ok, findings = evaluate_iam_policy([rule]) assert ok is False assert "wildcard" in findings[0] def test_rejects_wildcard_mutating_permission() -> None: rule = IamPolicyRule( role_name="writer", action="records:Update", resource="*", mutating=True, ) ok, findings = evaluate_iam_policy([rule]) assert ok is False assert findings def test_rejects_requested_endpoint_outside_allow_list() -> None: _, network, secrets, _ = _valid_inputs() network = network.model_copy( update={"requested_private_endpoints": ["vpce-unapproved-public-proxy"]} ) ok, findings = evaluate_network_and_secrets(network, secrets) assert ok is False assert any("not in the allowed" in item for item in findings) def test_rejects_public_egress() -> None: _, network, secrets, _ = _valid_inputs() network = network.model_copy(update={"private_egress_only": False}) ok, findings = evaluate_network_and_secrets(network, secrets) assert ok is False assert any("private_egress_only" in item for item in findings) def test_rejects_empty_secret_list() -> None: _, network, _, _ = _valid_inputs() ok, findings = evaluate_network_and_secrets(network, []) assert ok is False assert any("At least one" in item for item in findings) def test_rejects_expired_secret_and_excessive_ttl() -> None: _, network, secrets, _ = _valid_inputs() secrets[0] = secrets[0].model_copy( update={"expired": True, "lease_ttl_seconds": 7200} ) ok, findings = evaluate_network_and_secrets(network, secrets) assert ok is False assert any("expired" in item for item in findings) assert any("exceeds max allowed" in item for item in findings) def test_rejects_inline_secret_value() -> None: _, network, secrets, _ = _valid_inputs() secrets[0] = secrets[0].model_copy(update={"inline_value_present": True}) ok, findings = evaluate_network_and_secrets(network, secrets) assert ok is False assert any("inline value" in item for item in findings) def test_rejects_unmanaged_secret_reference() -> None: with pytest.raises(ValidationError): SecretLeaseRecord( secret_name="token", secret_ref="env://TOKEN", lease_ttl_seconds=300, ) def test_rejects_secret_reference_with_whitespace_or_query() -> None: for secret_ref in ("vault://northwind/secret name", "vault://northwind/token?version=latest"): with pytest.raises(ValidationError): SecretLeaseRecord( secret_name="token", secret_ref=secret_ref, lease_ttl_seconds=300, ) def test_rejects_error_rates_above_one() -> None: with pytest.raises(ValidationError): RolloutStage( stage_name="bad-rate", traffic_percent=10, observed_error_rate=1.1, observed_p95_latency_ms=100.0, ) def test_rejects_secret_max_ttl_above_one_day() -> None: with pytest.raises(ValidationError): SecretLeaseRecord( secret_name="token", secret_ref="vault://northwind/token", lease_ttl_seconds=300, max_allowed_ttl_seconds=86401, ) def test_rejects_single_stage_full_traffic_rollout() -> None: _, rollback, findings = evaluate_rollout_stages([ RolloutStage( stage_name="all-at-once", traffic_percent=100, observed_error_rate=0.0, observed_p95_latency_ms=100.0, ) ]) assert rollback is False assert any("at least two stages" in item for item in findings) def test_rejects_non_monotonic_or_incomplete_rollout() -> None: _, rollback, findings = evaluate_rollout_stages([ RolloutStage( stage_name="stage-50", traffic_percent=50, observed_error_rate=0.0, observed_p95_latency_ms=100.0, ), RolloutStage( stage_name="stage-40", traffic_percent=40, observed_error_rate=0.0, observed_p95_latency_ms=100.0, ), ]) assert rollback is False assert any("not strictly greater" in item for item in findings) assert any("must reach 100%" in item for item in findings) def test_rejects_duplicate_stage_names() -> None: _, rollback, findings = evaluate_rollout_stages([ RolloutStage( stage_name="canary", traffic_percent=10, observed_error_rate=0.0, observed_p95_latency_ms=100.0, ), RolloutStage( stage_name="canary", traffic_percent=100, observed_error_rate=0.0, observed_p95_latency_ms=100.0, ), ]) assert rollback is False assert any("Duplicate rollout stage name" in item for item in findings) def test_recommends_rollback_when_canary_error_rate_exceeds_threshold() -> None: _, rollback, findings = evaluate_rollout_stages([ RolloutStage( stage_name="canary-10", traffic_percent=10, observed_error_rate=0.05, observed_p95_latency_ms=300.0, ), RolloutStage( stage_name="full-100", traffic_percent=100, observed_error_rate=0.01, observed_p95_latency_ms=350.0, ), ]) assert rollback is True assert any("error rate" in item for item in findings) def test_recommends_rollback_when_canary_latency_exceeds_threshold() -> None: _, rollback, findings = evaluate_rollout_stages([ RolloutStage( stage_name="canary-10", traffic_percent=10, observed_error_rate=0.01, observed_p95_latency_ms=1450.0, max_p95_latency_ms=800.0, ), RolloutStage( stage_name="full-100", traffic_percent=100, observed_error_rate=0.01, observed_p95_latency_ms=350.0, ), ]) assert rollback is True assert any("P95 latency" in item for item in findings) def test_rejects_boolean_traffic_percent() -> None: with pytest.raises(ValidationError): RolloutStage( stage_name="bad", traffic_percent=True, observed_error_rate=0.0, observed_p95_latency_ms=100.0, ) - Configure GitHub Actions in
.github/workflows/tests.ymland run tests:name: Python tests on: push: pull_request: permissions: contents: read jobs: test: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" - name: Install package and test dependencies run: | python -m pip install --upgrade pip python -m pip install -e ".[dev]" - name: Run tests run: python -m pytest -v
3. Common Pitfalls and Operational Hygiene
- Leaving wildcard actions or resources in IAM rules: This module rejects wildcards for read and write permissions alike. In production, validate permissions against the actual provider policy model and workload requirements.
- Embedding static secrets or ignoring lease expiration: Reference managed secrets with bounded TTLs instead of storing static secret values in configuration or source files.
- Skipping canary rollback gates: Always enforce error and latency ceilings on early rollout stages so regressions trigger rollback before full traffic cutover.
4. Completion Criteria
IamPolicyRule,NetworkBoundaryPolicy,SecretLeaseRecord,RolloutStage, andDeploymentGateResultvalidate inputs strictly with Pydantic v2.evaluate_iam_policyrejects wildcard actions/resources;evaluate_network_and_secretsenforces requested-endpoint allow-listing, private egress, managed secret-reference formats, and lease TTL checks;evaluate_rollout_stagesrequires a valid multi-stage progression and enforces rollback thresholds.- All
pytesttests pass locally and in GitHub Actions, andfde-04-3is pushed to GitHub.
Build this
In fde-04-3, implement strict Pydantic v2 models in src/fde_04_3/schemas.py (IamPolicyRule, NetworkBoundaryPolicy, SecretLeaseRecord, RolloutStage, RolloutPlan, and DeploymentGateResult) and security/rollout evaluators in src/fde_04_3/controls.py.
- Validate IAM policies against least-privilege rules (rejecting wildcard actions or resources on mutating permissions and requiring explicit resource scoping).
- Validate private VPC/egress boundaries and secret resolution (rejecting plaintext/static inline secrets and flagging expired or over-long secret leases).
- Evaluate staged/canary rollout plans against error-rate and latency rollback thresholds, add
pytesttests intests/test_controls.py, and configure.github/workflows/tests.yml.
Test your understanding
- How do short-lived credentials or secret managers reduce blast radius compared to static config files or long-lived API keys?
- Why should mutating IAM permissions avoid wildcard actions (
*) and wildcard resources? - What role does private networking (VPC / private endpoints) play alongside IAM for an AI service calling internal data stores or APIs?
- Why run a staged or canary rollout with explicit error and latency rollback thresholds instead of an immediate 100% cutover?
Reveal self-review answers (attempt the questions first)
- Short-lived credentials and secret managers: Ephemeral tokens and centrally managed secrets expire automatically, can be revoked or rotated without redeploying code, and avoid committing sensitive values to Git or environment dumps, limiting how long leaked credentials remain usable.
- Avoiding wildcards on mutating permissions: Over-broad permissions let a compromised workload or prompt-hijacked tool read or modify unrelated buckets, queues, or records; scoping actions and target resources restricts damage to intended boundaries.
- Private networking defense-in-depth: Keeping internal databases, vector stores, and partner APIs reachable over private subnets or private endpoints rather than the public internet shrinks network exposure even if a token or rule is misconfigured.
- Canary rollouts and rollback gates: Gradually shifting traffic (such as 5% to 25% to 100%) while watching error rates and latency lets you halt and roll back bad releases before all users are affected.
Questions or notes on this module?