Skip to Content
Cloud Engineering Academy
5. Security for Banking & Finance

Policy evaluation logic

Predict exactly how AWS decides allow or deny when identity policies, resource policies, permissions boundaries, SCPs, RCPs and session policies all apply, and debug an AccessDenied from the error message, CloudTrail and the IAM policy simulator.

intermediate⏱ 2 h 🟢 FreeSCS-C03SAA-C03DVA-C03

Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.IdentityManagement 4.1.1.2) · AWS CLI v2 · Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Name the seven policy types that can take part in one AWS authorisation decision and say which ones grant permissions and which only cap them.
  • Walk any request through the evaluation order — explicit deny, RCPs, SCPs, resource-based policy, identity-based policy, permissions boundary, session policy — and predict Allow, explicit deny or implicit deny.
  • Explain the same-account resource-policy nuance (granting to a role ARN versus a role session ARN) and why cross-account access needs both sides to allow.
  • Read the policy-type phrase in a modern AccessDenied message ("with an explicit deny in a service control policy", "because no permissions boundary allows…") and go straight to the right policy.
  • Confirm a prediction with the IAM policy simulator from the CLI and from C#, knowing what the simulator does not model.

Prerequisites

Why this matters in banking

It is 16:40 on the last working day of the month. The month-end reconciliation job in the Data Platform account fails with:

User: arn:aws:sts::111122223333:assumed-role/hl-recon-batch/run-2026-11-30 is not authorized to perform:
kms:Decrypt on resource: arn:aws:kms:eu-west-2:444455556666:key/...
because no resource-based policy allows the kms:Decrypt action

Two engineers start "fixing" it. One adds kms:* on * to the batch role. The other asks for a temporary exemption from the organisation's SCP. Neither change helps, because the error already says the problem: the key policy in the other account does not mention the batch role. The broad grant stays in production for a year and becomes an audit finding.

Banks run dozens of accounts, organisation-wide guardrails, permission boundaries for delegated teams and cross-account data flows. Every one of those layers can deny a request. If you understand the evaluation order, you fix the right policy in minutes and you never "fix" access by widening a policy that was not the cause. It is also the single most-tested topic in the IAM domain of SCS-C03.

The idea in plain language

AWS evaluates every policy that applies to a request, then combines them with three simple rules:

  1. Default deny. Nothing is allowed unless something allows it. A request nobody mentions is an implicit deny.
  2. Explicit deny always wins. One matching "Effect": "Deny" anywhere — identity policy, bucket policy, SCP, RCP, boundary, session policy — ends the evaluation. No allow can override it.
  3. Guardrails cap, they never grant. SCPs, RCPs, permissions boundaries and session policies only set a maximum. They must also allow the action, but an allow in them gives nothing by itself.

Permissions are granted by only two policy types: identity-based policies (on the user or role) and resource-based policies (on the bucket, key, secret, queue…).

Analogy: a Harbourline branch vault. Your job description (identity policy) says you may open safe-deposit boxes. The box itself (resource policy) may list who can open it. Head office's branch rules (SCP) cap what anyone in this branch may do; the vault's own rules (RCP) cap who may touch boxes in it at all. Your probation terms (permissions boundary) cap your job description, and today's visitor badge (session policy) caps it further. A single "never" written in any of those documents wins over every "yes".

TermPlain meaning
PrincipalWho is calling: an IAM user, a role session, a federated session, or an AWS service
Request contextAction, resource, principal, plus condition keys such as aws:SourceIp, aws:PrincipalOrgID, aws:MultiFactorAuthPresent
Explicit denyA Deny statement whose action, resource, principal and conditions all match
Implicit denyNo matching allow where one was needed
Effective permissionsThe intersection of everything that caps, applied to the union of everything that grants

What problem the policy model solves

AWS needs one decision procedure that works for a single developer in a sandbox and for a 300-account bank with delegated administration. The layered model lets different owners control different layers without coordinating every change:

LayerTypical owner at HarbourlinePurpose
SCP (AWS Organizations)Cloud platform team"No one in workload accounts may leave the organisation or use unapproved Regions"
RCP (AWS Organizations)Cloud security team"No principal outside our organisation may read our S3, KMS keys or secrets"
Resource-based policyResource owner (data team)"The reporting account's role may read reports/*"
Identity-based policyApplication team"The Accounts API may read its own table"
Permissions boundaryPlatform team, applied to roles developers create"Roles you create can never exceed this"
Session policyThe caller, at AssumeRole time"For this script, read-only"

The cost of this flexibility is that a deny can come from a layer you do not own and cannot see. Sharp edges to know:

  • SCPs and RCPs do not apply to the management account, and SCPs do not restrict service-linked roles. Never run workloads in the management account.
  • RCPs apply only to the services AWS lists as supporting them (S3, STS, KMS, SQS, Secrets Manager and a growing list; ⚠ VERIFY the current list on the RCP documentation page before relying on one).
  • The root user of a member account is still subject to SCPs; the root user of a standalone account is not limited by any policy except resource policies that deny it.
  • The IAM policy simulator evaluates identity policies, SCPs, boundaries and a supplied resource policy, but it does not evaluate RCPs and it cannot simulate resource-based policies for roles. Treat it as strong evidence, not proof.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Azure RBAC role assignment at a scopeIdentity-based policy on a roleAWS policies are JSON documents with actions and ARNs, not role definitions inherited down a scope tree
Azure deny assignments / Azure Policy deny effectExplicit Deny in any policy, SCPsIn AWS any policy type can deny; there is no "Owner overrides"
Management group policySCP on an OUSCPs cap principals; they never grant, and every level from root to account must allow
Resource-level access policies (Key Vault access policies, Storage SAS)Resource-based policies (key policy, bucket policy, secret policy)Resource policies can grant on their own in the same account, and are required cross-account
Privileged Identity Management "eligible" assignmentRole assumption with a session policy and short session durationSession policies are passed by the caller and can only narrow
Entra ID Conditional Access (MFA, location)Condition keys (aws:MultiFactorAuthPresent, aws:SourceIp, aws:SourceVpce)Conditions live inside each statement, not in a separate policy engine
"What-if" / az role assignment listIAM policy simulator, IAM Access AnalyzerThe simulator answers "would this call be allowed?" for one principal and action

The biggest mental shift: in Azure RBAC the effective permission is mostly "union of role assignments minus deny assignments". In AWS it is "union of grants, intersected with every cap, minus every explicit deny".

Architecture

The full single-account flow, simplified from the IAM documentation into one picture:

For cross-account requests AWS runs the evaluation twice — once in the caller's account (identity policy, boundary, session policy, SCPs) and once in the resource owner's account (resource policy, RCPs) — and allows only if both say allow:

Note the last arrow: reading an SSE-KMS object cross-account is two authorisations. The bucket policy can allow s3:GetObject and the request still fails because the KMS key policy does not allow kms:Decrypt for the caller.

Step-by-step implementation

You will reason through the rules on paper first, then confirm with tools. All steps are free.

Rule 1 — find every applicable policy

For the failing request, list the principal (role session ARN), action, resource ARN, resource owner account and the condition keys that matter. Then list every policy that could apply:

  • identity policies on the role (managed and inline);
  • the role's permissions boundary;
  • the session policy, if the session was created with one (you can see it in the AssumeRole CloudTrail event under requestParameters.policy or policyArns);
  • the resource policy (bucket, key, secret, queue, topic, repository…);
  • SCPs on every level from the root to the account (root, each OU, account);
  • RCPs on every level of the resource's account;
  • a VPC endpoint policy if the call went through an interface or gateway endpoint.

Rule 2 — look for an explicit deny first

Scan all of them for a Deny statement whose action, resource and conditions match. Condition matching follows precise missing-key rules, and this is where most mistakes happen:

OperatorKey missing from the requestPractical consequence
StringEquals, Bool, ArnLike…Condition is falseA Deny with "Bool": {"aws:MultiFactorAuthPresent": "false"} does not fire for long-term access keys, where the key is absent
StringNotEquals, ArnNotLike…Condition is trueA Deny with StringNotEquals aws:PrincipalOrgID does fire for AWS service principals, which have no org ID — hence aws:PrincipalIsAWSService exceptions
...IfExistsCondition is trueBoolIfExists aws:MultiFactorAuthPresent false denies both "no MFA" and "key absent"
NullTests presence itself"Null": {"aws:MultiFactorAuthPresent": "true"} matches when the key is absent

Rule 3 — check the guardrails (RCPs, then SCPs)

Every level must contain an Allow that covers the action. AWS attaches FullAWSAccess (SCP) and RCPFullAWSAccess (RCP) by default; an allow-list SCP strategy replaces FullAWSAccess and is a common cause of "because no service control policy allows". RCPs always keep RCPFullAWSAccess, which cannot be detached, so in practice RCPs only ever deny.

Rule 4 — resource policy, then identity policy

  • Same account: either the identity policy or the resource policy can grant. Exceptions: IAM role trust policies and KMS key policies must allow the principal explicitly — for KMS this is usually done through the "enable IAM policies" statement that names the account root, which delegates the decision to IAM.
  • Same account, resource policy names the exact user ARN or role session ARN: the grant is not limited by an implicit deny in the identity policy, boundary or session policy.
  • Same account, resource policy names the role ARN: an implicit deny in the boundary or session policy still blocks it.
  • Cross-account: the resource policy in the owner's account and the identity policy in the caller's account must both allow.

Rule 5 — the caps on identity grants

If an identity policy granted the action, the permissions boundary (if any) and the session policy (if any) must each allow it too. Effective permission = identity ∩ boundary ∩ session.

Rule 6 — confirm with evidence

Use, in this order: the error message (policy type and sometimes ARN), the CloudTrail event (errorCode, errorMessage, userIdentity, and for some services additionalEventData), the IAM policy simulator, and finally a controlled test in the sandbox account. The offline hl-policy evaluate tool in the lab repository lets you replay the reasoning with a printed trace.

Reading modern AccessDenied messages

Most AWS services now include the policy type that caused the denial. The two shapes are:

... is not authorized to perform: <action> on resource: <arn> with an explicit deny in a <type> policy[: <policy ARN>]
... is not authorized to perform: <action> because no <type> policy allows the <action> action
Phrase in the messageGo and look at
with an explicit deny in a service control policySCPs on the account's OU path (management account → Organizations → Policies)
because no service control policy allowsAn allow-list SCP missing the action, or FullAWSAccess detached at some level
with an explicit deny in a resource control policyRCPs on the resource account's OU path
because no resource-based policy allowsThe bucket/key/secret policy — very often a KMS key policy cross-account
because no identity-based policy allowsThe role's attached and inline policies
because no permissions boundary allowsThe boundary set on the role
because no session policy allowsThe Policy/PolicyArns passed to AssumeRole (or an Identity Center permission set's session)
with an explicit deny in the role trust policy / because no role trust policy allowsThe trust policy of the role being assumed
because no VPC endpoint policy allowsThe endpoint policy of the VPC endpoint the call used

Two caveats: when several policy types deny, the message names only one of them; and some services still return the older message without context, so you fall back to the rules above.

AWS Console instructions

  1. Find the denied call. Console → CloudTrail → Event history. Filter Read-only = false or by Event name, open the event and read errorCode (AccessDenied, AccessDeniedException, UnauthorizedOperation), errorMessage and userIdentity.arn.
  2. Open the simulator. Console → IAM → Roles → choose the role → Permissions tab → Simulate (opens the IAM policy simulator, policysim.aws.amazon.com, signed in with your current session).
  3. In the simulator, select the service and action, enter the resource ARN under Simulation settings, add condition-key values (for example aws:RequestedRegion), then Run simulation. Expand the result to see the matched statement, and whether the decision came from an identity policy, the permissions boundary or Organizations SCPs.
  4. SCPs: sign in to the management (or delegated administrator) account → AWS Organizations → Policies → Service control policies → open the policy → Targets to see where it is attached.
  5. Resource policies: S3 → bucket → Permissions → Bucket policy; KMS → Customer managed keys → key → Key policy; Secrets Manager → secret → Resource permissions.

AWS CLI

# Who am I right now? The ARN printed here is the principal AWS evaluates (a role SESSION ARN for SSO).
aws sts get-caller-identity --profile learn-sandbox

# Find recent denied calls in the last day (management events, 90-day Event history).
aws cloudtrail lookup-events --profile learn-sandbox --region us-east-1 \
  --start-time "$(date -u -d '-1 day' +%Y-%m-%dT%H:%M:%SZ)" \
  --query 'Events[].CloudTrailEvent' --output text \
  | grep -i '"errorCode":"AccessDenied' | head -5

# Simulate a role's own policies (and SCPs, if the account is in an organisation) for two actions.
aws iam simulate-principal-policy --profile learn-sandbox \
  --policy-source-arn arn:aws:iam::111122223333:role/hl-m05-developer \
  --action-names secretsmanager:GetSecretValue s3:PutObject \
  --resource-arns "arn:aws:secretsmanager:us-east-1:111122223333:secret:hl-m05/accounts-api/blind-index-key-AbCdEf" \
  --context-entries "ContextKeyName=aws:RequestedRegion,ContextKeyValues=us-east-1,ContextKeyType=string" \
  --query 'EvaluationResults[].[EvalActionName,EvalDecision,PermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary,OrganizationsDecisionDetail.AllowedByOrganizations]' \
  --output table

# Simulate policies that are not attached anywhere yet (pure JSON, nothing created).
aws iam simulate-custom-policy --profile learn-sandbox \
  --policy-input-list file://policies/developer-identity.json \
  --permissions-boundary-policy-input-list file://policies/permission-boundary-developer.json \
  --action-names secretsmanager:GetSecretValue lambda:InvokeFunction \
  --query 'EvaluationResults[].[EvalActionName,EvalDecision]' --output table

# Which condition keys do these policies reference? Supply values for all of them when simulating.
aws iam get-context-keys-for-custom-policy --profile learn-sandbox \
  --policy-input-list file://policies/scp-deny-outside-regions.json

Run the last three from the root of labs/m05-secure-banking-api. The simulator is free and creates nothing.

Infrastructure as Code

The same rules apply to infrastructure you deploy. A common pattern is to ship a role together with its boundary and a deny for the most dangerous actions, so the evaluation result is predictable whoever later attaches extra policies.

using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Constructs;

namespace Harbourline.Security.Infra;

public sealed class EvaluationDemoStack : Stack
{
    public EvaluationDemoStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
    {
        // The cap: whatever is attached to the role later, it can never exceed this.
        var boundary = new ManagedPolicy(this, "Boundary", new ManagedPolicyProps
        {
            ManagedPolicyName = "hl-m05-eval-boundary",
            Statements =
            [
                new PolicyStatement(new PolicyStatementProps
                {
                    Effect = Effect.ALLOW,
                    Actions = ["s3:*", "dynamodb:*", "logs:*"],
                    Resources = ["*"],
                }),
            ],
        });

        var role = new Role(this, "Developer", new RoleProps
        {
            RoleName = "hl-m05-eval-developer",
            AssumedBy = new AccountPrincipal(Account),
            PermissionsBoundary = boundary,
            MaxSessionDuration = Duration.Hours(1),
        });

        // Grants more than the boundary allows: secretsmanager is granted but capped away (implicit deny).
        role.AddToPolicy(new PolicyStatement(new PolicyStatementProps
        {
            Effect = Effect.ALLOW,
            Actions = ["s3:GetObject", "secretsmanager:GetSecretValue"],
            Resources = ["*"],
        }));

        // An explicit deny that no later grant can override.
        role.AddToPolicy(new PolicyStatement(new PolicyStatementProps
        {
            Effect = Effect.DENY,
            Actions = ["s3:DeleteObject"],
            Resources = [$"arn:aws:s3:::hl-m05-audit-logs-{Account}/*"],
        }));

        Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
        Amazon.CDK.Tags.Of(this).Add("Lab", "m05-eval");
        Amazon.CDK.Tags.Of(this).Add("Environment", "learn");
    }
}

IAM roles and policies are free. Deploy, simulate secretsmanager:GetSecretValue (expect implicit deny because of the boundary) and s3:DeleteObject on the audit bucket (expect explicit deny), then destroy.

Complete code

A small .NET tool that does two things a bank's platform team does every week: classify an AccessDenied message by policy type, and confirm a hypothesis with SimulatePrincipalPolicy.

Harbourline.Security.AccessDeniedTriage.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <RootNamespace>Harbourline.Security.AccessDeniedTriage</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.IdentityManagement" Version="4.1.1.2" />
    <PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
  </ItemGroup>
</Project>
Program.cs
using System.Text.RegularExpressions;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

// Usage:
//   dotnet run -- classify "User: arn:aws:sts::... is not authorized to perform: ... because no permissions boundary allows ..."
//   dotnet run -- simulate arn:aws:iam::111122223333:role/hl-m05-developer secretsmanager:GetSecretValue <resource-arn> [key=value ...]
// Credentials: set AWS_PROFILE=learn-sandbox and run `aws sso login` first (simulate only).

if (args.Length >= 2 && args[0] == "classify")
{
    var triage = AccessDeniedClassifier.Classify(args[1]);
    Console.WriteLine($"Denial kind : {triage.Kind}");
    Console.WriteLine($"Policy type : {triage.PolicyType ?? "not stated (older message format)"}");
    Console.WriteLine($"Policy ARN  : {triage.PolicyArn ?? "-"}");
    Console.WriteLine($"Next step   : {triage.NextStep}");
    return 0;
}

if (args.Length >= 4 && args[0] == "simulate")
{
    using var iam = new AmazonIdentityManagementServiceClient();
    var context = args.Skip(4)
        .Select(kv => kv.Split('=', 2))
        .Select(p => new ContextEntry
        {
            ContextKeyName = p[0],
            ContextKeyType = ContextKeyTypeEnum.String,
            ContextKeyValues = [p[1]],
        })
        .ToList();

    var response = await iam.SimulatePrincipalPolicyAsync(new SimulatePrincipalPolicyRequest
    {
        PolicySourceArn = args[1],
        ActionNames = [args[2]],
        ResourceArns = [args[3]],
        ContextEntries = context,
    });

    foreach (var result in response.EvaluationResults ?? [])
    {
        Console.WriteLine($"{result.EvalActionName} on {result.EvalResourceName}: {result.EvalDecision}");
        Console.WriteLine($"  allowed by SCPs       : {result.OrganizationsDecisionDetail?.AllowedByOrganizations?.ToString() ?? "n/a"}");
        Console.WriteLine($"  allowed by boundary   : {result.PermissionsBoundaryDecisionDetail?.AllowedByPermissionsBoundary?.ToString() ?? "no boundary"}");
        foreach (var statement in result.MatchedStatements ?? [])
        {
            Console.WriteLine($"  matched statement in  : {statement.SourcePolicyId} ({statement.SourcePolicyType})");
        }
        foreach (var missing in result.MissingContextValues ?? [])
        {
            Console.WriteLine($"  ⚠ missing context key : {missing} — supply it, or the result may be wrong");
        }
    }
    return 0;
}

Console.Error.WriteLine("usage: classify \"<message>\" | simulate <role-arn> <action> <resource-arn> [key=value ...]");
return 2;

public enum DenialKind { Explicit, Implicit, Unknown }

public sealed record Triage(DenialKind Kind, string? PolicyType, string? PolicyArn, string NextStep);

public static partial class AccessDeniedClassifier
{
    public static Triage Classify(string message)
    {
        ArgumentNullException.ThrowIfNull(message);

        var explicitMatch = ExplicitPattern().Match(message);
        if (explicitMatch.Success)
        {
            var type = explicitMatch.Groups["type"].Value;
            var arn = explicitMatch.Groups["arn"].Success ? explicitMatch.Groups["arn"].Value : null;
            return new Triage(DenialKind.Explicit, type, arn,
                $"Find the Deny statement for this action in the {type} policy{(arn is null ? " (inline or unnamed)" : "")}. Do not add allows elsewhere: they cannot override it.");
        }

        var implicitMatch = ImplicitPattern().Match(message);
        if (implicitMatch.Success)
        {
            var type = implicitMatch.Groups["type"].Value;
            return new Triage(DenialKind.Implicit, type, null, NextStepForImplicit(type));
        }

        return new Triage(DenialKind.Unknown, null, null,
            "Older message format: walk the evaluation order (deny → RCP → SCP → resource → identity → boundary → session) and use the simulator.");
    }

    private static string NextStepForImplicit(string type) => type switch
    {
        "service control" => "An SCP level lacks an Allow (allow-list strategy, or FullAWSAccess detached). Ask the platform team; do not widen the role.",
        "resource control" => "Unusual: RCPFullAWSAccess cannot be detached. Check for a custom RCP setup.",
        "resource-based" => "The resource's own policy (often a KMS key policy cross-account) must name this principal.",
        "identity-based" => "Add the narrowest Allow to the role, scoped to this resource ARN.",
        "permissions boundary" => "The boundary caps the role. Changing it is a platform decision, not an application one.",
        "session" => "The session was created with a session policy. Re-assume without it, or include the action.",
        "VPC endpoint" => "The VPC endpoint policy must allow the action and resource.",
        _ => "Inspect policies of this type for a missing Allow.",
    };

    [GeneratedRegex(@"with an explicit deny in (?:a|an|the) (?<type>[\w\- ]+?) policy(?::\s*(?<arn>arn:\S+))?\s*$", RegexOptions.IgnoreCase)]
    private static partial Regex ExplicitPattern();

    [GeneratedRegex(@"because no (?<type>[\w\- ]+?) (?:policy|policies) allows?", RegexOptions.IgnoreCase)]
    private static partial Regex ImplicitPattern();
}

Run it:

dotnet run -- classify "User: arn:aws:sts::111122223333:assumed-role/hl-m05-developer/alex is not authorized to perform: secretsmanager:GetSecretValue on resource: arn:aws:secretsmanager:us-east-1:111122223333:secret:x because no permissions boundary allows the secretsmanager:GetSecretValue action"

Expected output:

Denial kind : Implicit
Policy type : permissions boundary
Policy ARN  : -
Next step   : The boundary caps the role. Changing it is a platform decision, not an application one.

For the full offline evaluator with ten puzzles, use hl-policy evaluate in labs/m05-secure-banking-api (see Labs 5.1 and 5.2).

Code explained line by line

  1. Project file — AWSSDK.IdentityManagement is the IAM client for SDK v4. AWSSDK.SSO and AWSSDK.SSOOIDC are needed so the default credential chain can use an IAM Identity Center profile; without them the SDK cannot read learn-sandbox tokens.
  2. args[0] == "classify" — classification is pure string work and needs no credentials, so you can paste a message from a ticket on any machine.
  3. new AmazonIdentityManagementServiceClient() — no keys in code. The SDK resolves AWS_PROFILE, then the SSO token cache. IAM is a global service, so the Region does not matter for this call.
  4. ContextEntry list — every condition key your policies reference needs a value, or the simulator treats it as missing and applies the missing-key rules. ContextKeyTypeEnum.String covers most keys; use Boolean for aws:MultiFactorAuthPresent and Ip for aws:SourceIp in a fuller version.
  5. SimulatePrincipalPolicyRequest — PolicySourceArn is the role ARN (the simulator cannot take a session ARN). It evaluates the role's identity policies, its boundary and, if the account is in an organisation, SCPs.
  6. OrganizationsDecisionDetail.AllowedByOrganizations and PermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary — these tell you which layer produced an implicit deny. In SDK v4 these booleans are nullable, hence ?.ToString() ?? "n/a".
  7. MatchedStatements — the statement that decided the result, with SourcePolicyId. For an explicit deny this points to the deny; for implicit deny the list is empty.
  8. MissingContextValues — a warning that a referenced key had no value. Ignore it and you may get a false "allowed".
  9. ExplicitPattern — matches "with an explicit deny in a/an/the X policy" and an optional : arn:.... The ? makes the type lazy so "service control" is captured without the word "policy".
  10. ImplicitPattern — matches "because no X policy allows", covering both "policy" and "policies".
  11. NextStepForImplicit — encodes the ownership lesson: the fix for an SCP or boundary denial is a request to the platform team, not a broader application role.

Security considerations

⚠ Learning shortcut — not for production

The lab gives your SSO role permission to call iam:SimulatePrincipalPolicy on any role. That call discloses other principals' permissions. In production, grant it only to the security and platform teams, or give developers iam:SimulateCustomPolicy, which only evaluates JSON they supply.

  • Never fix an explicit deny by adding allows. It cannot work, and the extra allow stays behind. Find out why the deny exists before asking for an exception.
  • Prefer explicit denies in guardrails over relying on absence. "Nobody granted it" is fragile: one future broad grant opens it. A deny in an SCP or boundary survives.
  • Use IfExists deliberately. BoolIfExists aws:MultiFactorAuthPresent false blocks callers that have no MFA information at all (access keys). Plain Bool silently lets them through.
  • Watch NotAction and NotResource with Allow. They grant every action or resource not listed, including actions AWS launches next year.
  • Always add aws:PrincipalOrgID or aws:SourceAccount / aws:SourceArn conditions to resource policies that name broad principals or services, to stop confused-deputy access.
  • Session policies are set by the caller. They can only narrow, so they are safe to let developers use, and they are a good way to run scripts with less than the role's full permissions.

Banking use case

Harbourline's Data Platform account (444455556666) produces daily balance reports from data in the Payments workload account (111122223333). The design:

  • Workload account bucket hl-m05-exports-111122223333 uses SSE-KMS with key alias/hl-m05-exports.
  • The bucket policy grants s3:GetObject on reports/* to arn:aws:iam::444455556666:role/hl-m05-reporting.
  • The key policy grants kms:Decrypt to the same role ARN, with condition kms:ViaService = s3.eu-west-2.amazonaws.com so the key can only be used through S3.
  • The reporting role's identity policy allows s3:GetObject on that bucket and kms:Decrypt on that key ARN.
  • An RCP on the Workload OU denies S3, KMS and Secrets Manager access to any principal outside the organisation (aws:PrincipalOrgID), with an exception for AWS service principals.
  • An SCP on all workload OUs denies actions outside eu-west-2 and us-east-1, except global services and the break-glass role.

When the reconciliation job in the opening story failed, the error said "no resource-based policy allows the kms:Decrypt action": the key policy had been rewritten by a new IaC module that dropped the reporting statement. The fix was one statement in the key policy, reviewed by the key owner. No role was widened, no SCP exception was granted, and the change appeared in the key's CloudTrail history for the auditor.

Common mistakes

  • Treating SCPs as grants. Attaching an SCP that "allows S3" to an OU gives nobody S3 access. → Grants come only from identity and resource policies.
  • Forgetting that every SCP level must allow. An allow at the OU does not help if the root's policy (an allow-list) lacks the action. → Check the full path root → OU → account.
  • Fixing a cross-account failure on one side only. → Cross-account needs both the identity policy and the resource policy (and, for SSE-KMS, the key policy).
  • Testing with an admin role. Admin sessions do not have boundaries or session policies; your workload does. → Test with the real role, or simulate it.
  • Using Bool for MFA denies. → Use BoolIfExists, or the Null operator.
  • Assuming the simulator saw everything. → It does not evaluate RCPs or VPC endpoint policies, and cannot use resource policies for roles. Confirm in a sandbox.
  • Reading the role ARN in CloudTrail and writing it into a resource policy as the session ARN (or vice versa). → Same-account grants to a session ARN bypass boundaries; grants to a role ARN do not. Choose consciously.

Troubleshooting

SymptomLikely causeFix
with an explicit deny in a service control policyRegion guardrail, or a protective deny (for example on CloudTrail changes)Check aws:RequestedRegion; confirm the action is one the guardrail intends to block; use the approved path
because no service control policy allowsAllow-list SCP lacks the service, or FullAWSAccess detached at one levelPlatform team adds the service to the allow list at the right level
because no resource-based policy allows the kms:Decrypt actionCross-account KMS key policy omits the callerKey owner adds a statement for the caller's role ARN, ideally with kms:ViaService
because no permissions boundary allowsRole created under a boundary that does not include the serviceUse a service inside the boundary, or ask the platform team to review the boundary
because no session policy allowsScript or tool assumed the role with a restrictive session policyRe-assume without the session policy, or extend it for this task
Simulator says allowed, live call deniedRCP, VPC endpoint policy, resource policy not supplied, or missing context keySupply the resource policy and context keys; check RCPs and endpoint policies
AccessDenied with no policy type in the messageService uses the older message formatWalk the six-step order; check CloudTrail errorMessage for more detail
S3 returns 403 for HeadObject on a missing keyWithout s3:ListBucket, S3 returns 403 instead of 404 so you cannot probe for object namesExpected behaviour; grant s3:ListBucket only if listing is genuinely needed

Cost and cleanup

Everything in this lesson is free: IAM, the policy simulator, CloudTrail Event history, hl-policy and the triage tool. If you deployed the IaC example:

# CDK
cdk destroy --profile learn-sandbox
# or Terraform
terraform destroy

# Confirm nothing tagged for this lesson remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m05-eval --profile learn-sandbox --region us-east-1
aws iam get-role --role-name hl-m05-eval-developer --profile learn-sandbox   # expect NoSuchEntity

IAM roles are global and do not appear in the Region-scoped tagging API, hence the explicit get-role check.

Exercises

  • 🟢 Guided: From labs/m05-secure-banking-api, write down your prediction for all ten puzzles in policies/scenarios/, then run dotnet run --project src/Harbourline.Security.PolicyLinter -- evaluate <file> for each. For every wrong prediction, write one sentence naming the rule you missed.
  • 🟡 Challenge: Puzzle 9 allows kms:Decrypt with no identity policy because the key policy names the role. Change the key policy to name the role session ARN instead, add a permissions boundary that does not include KMS, and predict the result. Then change it back to the role ARN with the same boundary. Explain the difference using the IAM documentation's same-account rules.
  • 🔴 Live problem: A ticket says: "Since Tuesday the nightly export to the Data Platform account fails with AccessDenied on s3:GetObject. Nothing changed on our side." The bucket owner says the bucket policy is unchanged. List, in order, the five places you would look, what evidence each would give you, and the one change you suspect most given that "nothing changed" on either team's side.

Assignment

Add a docs/access-model.md to your portfolio repository describing, for one Harbourline workload of your choice, every policy layer that applies (SCP, RCP, resource, identity, boundary, session), who owns each, and three example requests with their predicted decision and the step that decides it. Include one Mermaid diagram and the hl-policy scenario files that prove your predictions.

Solutions

Knowledge check

Interview questions

  • "Walk me through how AWS decides whether a request is allowed." — Default deny; any matching explicit deny in any policy ends it; RCPs and SCPs must allow at every level; then resource policy and identity policy grant (same account either, cross-account both); boundaries and session policies intersect with identity grants. Mention the role-ARN versus session-ARN nuance to show depth.
  • "A developer says their Lambda gets AccessDenied. What do you ask for first?" — The exact error message and the CloudTrail event. The policy-type phrase tells you whether it is their role, a boundary, an SCP or the resource, and therefore who must make the change.
  • "Why would you use an RCP instead of adding conditions to every bucket policy?" — Central enforcement: one policy covers every supported resource in the OU, including resources created tomorrow by teams who forget the condition, and resource owners cannot remove it.
  • "Is it safe to let developers pass session policies?" — Yes; session policies can only narrow the role's permissions, never widen them.

Certification practice

Completion checklist

  • I can state the three combining rules (default deny, explicit deny wins, guardrails cap) without notes
  • I predicted all ten hl-policy puzzles and understand every one I got wrong
  • I can map each AccessDenied phrase to the policy type and the team that owns it
  • I ran simulate-principal-policy or simulate-custom-policy and read the boundary and SCP details
  • I know what the simulator does not evaluate
  • I destroyed any role and boundary I created for this lesson

Key takeaways

  • Only identity-based and resource-based policies grant; SCPs, RCPs, boundaries and session policies only cap.
  • One matching explicit deny anywhere ends evaluation; adding allows never fixes it.
  • Same account: either side can grant (except role trust and KMS key policies); cross-account: both sides must.
  • Grants to a role ARN are limited by boundaries and session policies; grants to a session ARN in the same account are not.
  • Read the policy-type phrase in the AccessDenied message first — it tells you which policy and which team.

Further reading

Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page