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.
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
AccessDeniedmessage ("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
- IAM in depth — principals, roles and policy JSON
- Helpful but not required: Permission boundaries, SCPs, RCPs and resource-based policies, which this lesson's rules explain
- Tools: AWS CLI v2 with the
learn-sandboxSSO profile, .NET 10 SDK (or Docker), the lab repositorylabs/m05-secure-banking-api
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 actionTwo 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:
- Default deny. Nothing is allowed unless something allows it. A request nobody mentions is an implicit deny.
- 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. - 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".
| Term | Plain meaning |
|---|---|
| Principal | Who is calling: an IAM user, a role session, a federated session, or an AWS service |
| Request context | Action, resource, principal, plus condition keys such as aws:SourceIp, aws:PrincipalOrgID, aws:MultiFactorAuthPresent |
| Explicit deny | A Deny statement whose action, resource, principal and conditions all match |
| Implicit deny | No matching allow where one was needed |
| Effective permissions | The 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:
| Layer | Typical owner at Harbourline | Purpose |
|---|---|---|
| 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 policy | Resource owner (data team) | "The reporting account's role may read reports/*" |
| Identity-based policy | Application team | "The Accounts API may read its own table" |
| Permissions boundary | Platform team, applied to roles developers create | "Roles you create can never exceed this" |
| Session policy | The 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 equivalent | What's different |
|---|---|---|
| Azure RBAC role assignment at a scope | Identity-based policy on a role | AWS policies are JSON documents with actions and ARNs, not role definitions inherited down a scope tree |
Azure deny assignments / Azure Policy deny effect | Explicit Deny in any policy, SCPs | In AWS any policy type can deny; there is no "Owner overrides" |
| Management group policy | SCP on an OU | SCPs 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" assignment | Role assumption with a session policy and short session duration | Session 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 list | IAM policy simulator, IAM Access Analyzer | The 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
AssumeRoleCloudTrail event underrequestParameters.policyorpolicyArns); - 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:
| Operator | Key missing from the request | Practical consequence |
|---|---|---|
StringEquals, Bool, ArnLike… | Condition is false | A Deny with "Bool": {"aws:MultiFactorAuthPresent": "false"} does not fire for long-term access keys, where the key is absent |
StringNotEquals, ArnNotLike… | Condition is true | A Deny with StringNotEquals aws:PrincipalOrgID does fire for AWS service principals, which have no org ID — hence aws:PrincipalIsAWSService exceptions |
...IfExists | Condition is true | BoolIfExists aws:MultiFactorAuthPresent false denies both "no MFA" and "key absent" |
Null | Tests 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 message | Go and look at |
|---|---|
with an explicit deny in a service control policy | SCPs on the account's OU path (management account → Organizations → Policies) |
because no service control policy allows | An allow-list SCP missing the action, or FullAWSAccess detached at some level |
with an explicit deny in a resource control policy | RCPs on the resource account's OU path |
because no resource-based policy allows | The bucket/key/secret policy — very often a KMS key policy cross-account |
because no identity-based policy allows | The role's attached and inline policies |
because no permissions boundary allows | The boundary set on the role |
because no session policy allows | The 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 allows | The trust policy of the role being assumed |
because no VPC endpoint policy allows | The 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
- 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),errorMessageanduserIdentity.arn. - 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). - 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. - 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.
- 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.jsonRun 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.
<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>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
- Project file —
AWSSDK.IdentityManagementis the IAM client for SDK v4.AWSSDK.SSOandAWSSDK.SSOOIDCare needed so the default credential chain can use an IAM Identity Center profile; without them the SDK cannot readlearn-sandboxtokens. args[0] == "classify"— classification is pure string work and needs no credentials, so you can paste a message from a ticket on any machine.new AmazonIdentityManagementServiceClient()— no keys in code. The SDK resolvesAWS_PROFILE, then the SSO token cache. IAM is a global service, so the Region does not matter for this call.ContextEntrylist — every condition key your policies reference needs a value, or the simulator treats it as missing and applies the missing-key rules.ContextKeyTypeEnum.Stringcovers most keys; useBooleanforaws:MultiFactorAuthPresentandIpforaws:SourceIpin a fuller version.SimulatePrincipalPolicyRequest—PolicySourceArnis 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.OrganizationsDecisionDetail.AllowedByOrganizationsandPermissionsBoundaryDecisionDetail.AllowedByPermissionsBoundary— these tell you which layer produced an implicit deny. In SDK v4 these booleans are nullable, hence?.ToString() ?? "n/a".MatchedStatements— the statement that decided the result, withSourcePolicyId. For an explicit deny this points to the deny; for implicit deny the list is empty.MissingContextValues— a warning that a referenced key had no value. Ignore it and you may get a false "allowed".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".ImplicitPattern— matches "because no X policy allows", covering both "policy" and "policies".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
IfExistsdeliberately.BoolIfExists aws:MultiFactorAuthPresent falseblocks callers that have no MFA information at all (access keys). PlainBoolsilently lets them through. - Watch
NotActionandNotResourcewithAllow. They grant every action or resource not listed, including actions AWS launches next year. - Always add
aws:PrincipalOrgIDoraws:SourceAccount/aws:SourceArnconditions 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-111122223333uses SSE-KMS with keyalias/hl-m05-exports. - The bucket policy grants
s3:GetObjectonreports/*toarn:aws:iam::444455556666:role/hl-m05-reporting. - The key policy grants
kms:Decryptto the same role ARN, with conditionkms:ViaService = s3.eu-west-2.amazonaws.comso the key can only be used through S3. - The reporting role's identity policy allows
s3:GetObjecton that bucket andkms:Decrypton 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-2andus-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
Boolfor MFA denies. → UseBoolIfExists, or theNulloperator. - 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
| Symptom | Likely cause | Fix |
|---|---|---|
with an explicit deny in a service control policy | Region 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 allows | Allow-list SCP lacks the service, or FullAWSAccess detached at one level | Platform team adds the service to the allow list at the right level |
because no resource-based policy allows the kms:Decrypt action | Cross-account KMS key policy omits the caller | Key owner adds a statement for the caller's role ARN, ideally with kms:ViaService |
because no permissions boundary allows | Role created under a boundary that does not include the service | Use a service inside the boundary, or ask the platform team to review the boundary |
because no session policy allows | Script or tool assumed the role with a restrictive session policy | Re-assume without the session policy, or extend it for this task |
| Simulator says allowed, live call denied | RCP, VPC endpoint policy, resource policy not supplied, or missing context key | Supply the resource policy and context keys; check RCPs and endpoint policies |
AccessDenied with no policy type in the message | Service uses the older message format | Walk the six-step order; check CloudTrail errorMessage for more detail |
S3 returns 403 for HeadObject on a missing key | Without s3:ListBucket, S3 returns 403 instead of 404 so you cannot probe for object names | Expected 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 NoSuchEntityIAM 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 inpolicies/scenarios/, then rundotnet 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:Decryptwith 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
The expected answers are in each file's expected field, and the test suite asserts them. The ones people most often get wrong: puzzle 4 (implicit deny — the identity policy allows Secrets Manager but the boundary does not list it, and boundaries intersect), puzzle 6 (implicit deny — cross-account needs the bucket policy to name the reporting role; an identity grant alone is not enough), puzzle 9 (allow — in the same account a key policy that names the role grants on its own, and KMS key policies are one of the places where the resource side must allow anyway), and puzzle 10 (explicit deny — BoolIfExists treats the absent MFA key as matching, so the deny fires).
Naming the role session ARN in a same-account resource policy grants directly to that session, so an implicit deny in the boundary does not limit it: the result is Allow. Naming the role ARN, the grant is still limited by an implicit deny in a permissions boundary or session policy: the result is implicit deny. In hl-policy, a direct session match is reported as "the exact caller ARN" and returns at step 4; a role match goes on to steps 6 and 7. In practice banks avoid session-ARN grants because session names change and the bypass surprises reviewers.
- The error message in the job log: the policy-type phrase usually ends the investigation. 2. CloudTrail in both accounts for the failing call and for any
PutBucketPolicy,PutKeyPolicy,AttachPolicy,UpdatePolicy(Organizations) since Monday. 3. The KMS key policy: SSE-KMS objects needkms:Decrypttoo, and the error for that arrives as a 403 onGetObject. 4. SCPs/RCPs: a new RCP enforcingaws:PrincipalOrgIDwould block a reporting account that is outside the organisation, or a new Region guardrail if the job runs elsewhere. 5. The objects themselves: a producer that started writing with a different KMS key, or with ACLs underBucketOwnerEnforceddisabled. Most suspicious when "nothing changed" on both teams: an organisation-level change (RCP or SCP) by the platform team, or a new KMS key on the producer side — both are owned by someone outside the two teams in the ticket.
Knowledge check
Answer: No — implicit deny. SCPs cap principals in member accounts; every level must allow the action, and this one does not include SQS. AdministratorAccess grants it, but the cap removes it. (The management account and service-linked roles would not be affected, but neither is the case here.)
Answer: Implicit deny. A resource-policy grant to the role ARN is limited by an implicit deny in the permissions boundary. If the policy had named the role session ARN, the boundary would not limit it.
Answer: The first is an organisation-level RCP with a matching Deny — owned by the security/platform team; no change to the resource itself helps. The second is the resource's own policy (bucket, key, secret) not granting the caller — owned by the resource owner, and typical for cross-account access.
Answer: With long-term keys the key is absent from the request context. For a positive operator such as Bool, an absent key makes the condition false, so the deny does not match. BoolIfExists treats absence as a match.
Answer: The KMS key policy does not allow kms:Decrypt for the caller's role (and/or the caller's identity policy lacks kms:Decrypt on that key ARN). Decrypting is a separate authorisation with its own cross-account rules.
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
A platform team lets developers create IAM roles for Lambda functions. Every created role must carry the boundary hl-app-boundary, which allows DynamoDB and SQS only. A developer creates a role with the boundary and attaches AmazonS3FullAccess. The function calls s3:PutObject. What happens?
A. Allowed, because AmazonS3FullAccess is an AWS managed policy and takes precedence.
B. Explicitly denied, because the boundary contains a Deny for S3.
C. Implicitly denied, because effective permissions are the intersection of the identity policy and the boundary.
D. Allowed, because boundaries apply only to IAM users.
Answer: C. A is wrong: managed policies have no precedence over boundaries. B is wrong: the boundary has no Deny; the result is implicit, not explicit. D is wrong: boundaries apply to users and roles.
A role in account A reads SSE-KMS objects from a bucket in account B. The bucket policy allows the role s3:GetObject, and the role's identity policy allows s3:GetObject on the bucket and kms:Decrypt on the key ARN. Requests fail with AccessDenied. Which change fixes it with least privilege?
A. Add kms:* on * to the role's identity policy.
B. Add a statement to the KMS key policy in account B allowing the role kms:Decrypt, with a kms:ViaService condition for S3.
C. Add an SCP in account A that allows kms:Decrypt.
D. Re-encrypt the objects with SSE-S3 and delete the key.
Answer: B. Cross-account KMS use needs the key policy to allow the external principal. A is broader and still fails without the key policy. C is wrong: SCPs never grant. D removes the customer managed key control the bank chose deliberately.
An organisation must ensure that no workload account can use any Region except eu-west-2, even if account administrators attach AdministratorAccess to their roles. The solution must not affect IAM, which is a global service. What should the architect use?
A. A permissions boundary on every role.
B. An SCP with a Deny on all actions when aws:RequestedRegion is not eu-west-2, using NotAction to exclude global services.
C. A resource-based policy on every resource.
D. An IAM policy in each account with a Deny for other Regions.
Answer: B. SCPs apply to every principal in member accounts and cannot be removed by account administrators. A and D can be removed or bypassed by account administrators. C does not cover resources created later and does not restrict API calls that create resources.
A deployment script assumes a role that can read and write an S3 bucket, but this script must only read. The team cannot change the role. What is the simplest secure option?
A. Create a second IAM user with read-only keys.
B. Pass a session policy allowing only s3:GetObject and s3:ListBucket when calling AssumeRole.
C. Add a Deny for s3:PutObject to the bucket policy.
D. Use the role but avoid calling write APIs in code.
Answer: B. A session policy narrows that session only and needs no change to the role. A introduces long-term keys. C would also block legitimate writers. D is not a control.
Completion checklist
- I can state the three combining rules (default deny, explicit deny wins, guardrails cap) without notes
- I predicted all ten
hl-policypuzzles 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-policyorsimulate-custom-policyand 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
- Policy evaluation logic (IAM User Guide)
- How AWS enforcement code logic evaluates requests to allow or deny access
- Cross-account policy evaluation logic
- Troubleshoot access denied error messages
- SimulatePrincipalPolicy (IAM API Reference)
- Next: AWS KMS, where key policies add their own twist to these rules.
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.
IAM in depth: identities, roles and every policy type
Explain IAM users, groups, roles and the root user, read and write policy JSON with confidence, and recognise all nine policy types a request can meet — then audit an account for risky IAM users from C#.
Least privilege in practice with IAM Access Analyzer
Run a repeatable least-privilege workflow: start narrow, use condition keys and ABAC, generate policies from CloudTrail activity, remove unused access, and gate every policy change with IAM Access Analyzer checks from C#.