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

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#.

intermediate⏱ 2 h 🟡 Low costSCS-C03SAA-C03DVA-C03

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

Learning objectives

By the end of this lesson you can:

  • Describe a least-privilege lifecycle — design, generate, validate, deploy, monitor, trim — and who owns each step in a bank.
  • Use the condition keys that do most of the work in financial-services policies: aws:PrincipalOrgID, aws:ResourceOrgID, aws:SourceVpce, aws:SourceVpc, aws:MultiFactorAuthPresent, aws:PrincipalTag and aws:ResourceTag (ABAC).
  • Use IAM Access Analyzer for external access, internal access and unused access findings, policy validation, custom policy checks and policy generation — and say which of these cost money.
  • Read last accessed information (Access Advisor) to remove permissions nobody uses.
  • Build a C# policy gate that fails a pipeline when a policy has errors, security warnings, or grants a forbidden action.

Prerequisites

  • IAM in depth — policy grammar and the nine policy types
  • Policy evaluation logic — how allows and denies combine
  • A CloudTrail trail in the sandbox account is needed only for the policy-generation step (see CloudTrail for banks); the first management-events trail is free
  • Tools: AWS CLI v2, .NET 10 SDK, learn-sandbox profile

Why this matters in banking

Harbourline's Accounts API team asked for "S3 full access" two years ago because a deadline was close. The role still has it. Nobody remembers why. Today that role could delete statement archives, change bucket policies to public, or read the data platform's customer extracts. Nothing bad has happened — yet — but the internal auditor's finding is blunt: "Access is not restricted to business need; no evidence of periodic review."

Least privilege is the principle that every identity holds only the permissions it needs for its job, for as long as it needs them. Regulators and standards bodies expect it (PCI DSS, for example, has a whole requirement on restricting access by business need to know). The hard part is not agreeing with the principle; it is doing it continuously across hundreds of roles without breaking production. That is what this lesson is about.

Security of vs in the cloud: AWS provides the tools (Access Analyzer, last accessed data, condition keys). Choosing, reviewing and trimming permissions is entirely Harbourline's responsibility.

The idea in plain language

Least privilege is not a one-off clean-up; it is a loop:

  1. Start narrow. Write the smallest policy you can justify from the design: specific actions, specific resource ARNs, and conditions on where and how the request may come from.
  2. Generate from evidence. If you inherit a broad role, let AWS tell you what it actually used (CloudTrail-based policy generation and last accessed data).
  3. Validate before deploy. Automatically check every policy for mistakes and for forbidden permissions in the pipeline.
  4. Monitor. Get findings when something is shared outside the organisation, or when granted permissions go unused.
  5. Trim. Remove what is unused, through the normal change process, and record the review as evidence.

Analogy: A new branch employee does not get a master key "in case they need it". They get the keys for their counter. Every quarter the branch manager reviews the key log: keys that were never used are collected, and any key found in another branch's lock triggers an investigation. IAM Access Analyzer is the key log reviewer that never takes a holiday.

What problem IAM Access Analyzer solves

IAM Access Analyzer is a feature set inside IAM that uses automated reasoning (mathematical analysis of policies, not sampling) and activity data to answer "who can access what?" It has six capabilities:

CapabilityQuestion it answersScopeCost (checked 2026-11-17)
External access analyzerWhich of my resources can a principal outside my zone of trust (account or organisation) reach?Resource-based policies of S3 buckets, IAM role trust policies, KMS keys, Lambda, SQS, SNS, Secrets Manager, EBS/RDS snapshots, ECR, EFS, DynamoDB tables and streams and more; per RegionNo additional charge
Internal access analyzerWhich principals inside my organisation or account can reach my selected critical resources?Selected S3 buckets, DynamoDB tables and streams, RDS snapshotsCharged per monitored resource per Region per month (about USD 9 at the time of writing ⚠ VERIFY on the pricing page)
Unused access analyzerWhich roles, users, access keys, passwords, services and actions have not been used for N days?All IAM roles and users in the account or organisation; not Region-specificUSD 0.20 per IAM role or user analysed per analyzer per month; service-linked roles are not counted
Policy validationDoes this policy have grammar errors, security warnings or best-practice issues?Any policy you submitNo additional charge
Custom policy checksDoes this policy grant new access compared with the old one? Does it grant any of these forbidden actions? Could this resource policy allow public access?Any policy you submitUSD 0.0020 per API call
Policy generationWhat did this role actually do over the last N days?Up to 90 days of CloudTrail management eventsNo additional charge (standard S3 request charges for reading the logs)

Limitations to know before you rely on it:

  • External access analyzers are Regional. Create one in every Region you use (or let your organisation-level automation do it).
  • Policy generation does not see data events (for example s3:GetObject) at action level, and never sees iam:PassRole, because CloudTrail does not record it as a separate event. You must add these by hand.
  • Policy generation cannot read the CloudTrail bucket that AWS Control Tower creates in the log-archive account, because of Control Tower's own guardrails. Use a separate trail for generation if you run Control Tower.
  • Findings are only as good as your zone of trust. An analyzer for the account treats other accounts in your organisation as external; an organisation analyzer does not.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Entra ID access reviewsAccess Analyzer unused access findings + Identity Center assignment reviewsAWS findings are generated automatically from activity; the review decision is still yours
Entra Permissions Management (CIEM)Access Analyzer unused access + policy generationNative, per account or organisation; no separate product to license
Azure Policy "audit" for public storageAccess Analyzer external access findings, S3 Block Public AccessAnalyzer reasons over the policy logic, not just a flag
Azure RBAC custom roles with NotActionsPolicies with specific Action lists; avoid NotAction with AllowAWS has thousands of actions; wildcards like s3:Get* are common but must be deliberate
Conditional Access (location, MFA)Global condition keys: aws:SourceIp, aws:SourceVpce, aws:MultiFactorAuthPresentConditions are part of each policy statement, evaluated per API call
ABAC with Azure attributes in role assignment conditionsABAC with aws:PrincipalTag / aws:ResourceTagWorks across most services; tags on sessions can come from the IdP

Architecture

The least-privilege lifecycle at Harbourline:

Where Access Analyzer sits in an organisation:

Security-boundary view: the organisation is the zone of trust. Anything that lets a principal outside it reach a resource inside it is a finding to review. Inside the organisation, unused access findings and internal access analysis find the "too much access" problems that external analysis cannot see.

Condition keys that do the heavy lifting

Most of a bank's least-privilege value comes from a small number of global condition keys:

KeyUse it to…Example
aws:PrincipalOrgIDAllow only principals from your organisation in a resource policyBucket policy that lets any Harbourline account write logs, but nobody else
aws:ResourceOrgIDAllow your principals to reach only resources owned by your organisationEndpoint or identity policy that stops data being copied to a personal bucket
aws:SourceVpce / aws:SourceVpcRequire that a request arrives through your VPC endpointStatements bucket readable only from the private network
aws:SourceIpRestrict by public IP — only meaningful for requests that come over the internetLegacy IAM user restricted to the data centre egress range
aws:MultiFactorAuthPresent, aws:MultiFactorAuthAgeRequire MFA (and recent MFA) for sensitive actionsDeny kms:ScheduleKeyDeletion without MFA
aws:PrincipalTag/…, aws:ResourceTag/…, aws:RequestTag/…, aws:TagKeysAttribute-based access control (ABAC)A team=payments session can only touch resources tagged team=payments
aws:SourceAccount, aws:SourceArnStop a service principal acting for someone else (confused deputy)CloudTrail may write to the bucket only for your trail
kms:ViaService, kms:EncryptionContext:…Allow key use only through a specific service or for a specific contextDecrypt allowed only via DynamoDB in us-east-1

A data-perimeter bucket policy for Harbourline's statement archive combines several of them:

hl-m05-statements-bucket-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "DenyOutsideOrganisation",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": ["arn:aws:s3:::hl-m05-statements", "arn:aws:s3:::hl-m05-statements/*"],
      "Condition": {
        "StringNotEqualsIfExists": { "aws:PrincipalOrgID": "o-exampleorgid" },
        "BoolIfExists": { "aws:PrincipalIsAWSService": "false" }
      }
    },
    {
      "Sid": "DenyObjectReadsOutsideVpcEndpoint",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::hl-m05-statements/*",
      "Condition": {
        "StringNotEquals": { "aws:SourceVpce": "vpce-0a1b2c3d4e5f67890" }
      }
    },
    {
      "Sid": "DenyInsecureTransport",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": ["arn:aws:s3:::hl-m05-statements", "arn:aws:s3:::hl-m05-statements/*"],
      "Condition": { "Bool": { "aws:SecureTransport": "false" } }
    }
  ]
}

Read it as three fences: nobody outside the organisation (except AWS services acting on your behalf), no object reads except through the bank's VPC endpoint, and no unencrypted HTTP. None of these statements grants anything — the Accounts API role still needs an identity policy allowing s3:GetObject. That separation (resource policy fences, identity policy grants) keeps the bucket policy short and stable.

ABAC in two statements

Role-based access control (RBAC) needs a new policy for every team and resource. Attribute-based access control (ABAC) writes one policy that compares tags:

hl-m05-abac-team-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ManageOwnTeamsQueues",
      "Effect": "Allow",
      "Action": ["sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes"],
      "Resource": "arn:aws:sqs:us-east-1:111122223333:hl-*",
      "Condition": {
        "StringEquals": { "aws:ResourceTag/team": "${aws:PrincipalTag/team}" }
      }
    },
    {
      "Sid": "DenyChangingTeamTag",
      "Effect": "Deny",
      "Action": ["sqs:TagQueue", "sqs:UntagQueue"],
      "Resource": "*",
      "Condition": { "ForAnyValue:StringEquals": { "aws:TagKeys": ["team"] } }
    }
  ]
}

The second statement matters: if people can change the team tag on a resource, they can grant themselves access. ABAC is only as strong as the governance of the tags — who can set them, and an SCP or tag policy that protects them.

Step-by-step implementation

Turn on an external access analyzer

Create an account-level external access analyzer in us-east-1 (free). Within about 30 minutes it reports any existing resource shared outside the account. In the sandbox, the OrganizationAccountAccessRole trust policy (trusting the management account) is a typical first finding — archive it with a note, because it is intended.

Create something that should be flagged

Create a bucket hl-m05-share-test-<yourname> and add a bucket policy granting s3:GetObject to a made-up external account arn:aws:iam::999988887777:root. Leave Block Public Access on. Within minutes Access Analyzer reports a cross-account finding. Delete the policy and choose Rescan: the finding moves to Resolved.

Read last accessed information

Pick any role you have used in the sandbox (for example the SSO role) and open Access Advisor. Note services granted but never used. Then generate an action-level report with the CLI (generate-service-last-accessed-details --granularity ACTION_LEVEL).

(Optional, credits) Create an unused access analyzer

An unused access analyzer costs USD 0.20 per role or user analysed per month. A sandbox with 15 roles costs about USD 3 per month while it exists; delete it the same day. It shows unused roles, unused services and actions per role, and unused credentials.

Generate a policy from activity

If you have a CloudTrail trail, generate a policy for a role you have used today (time range: the last day). Compare the generated template with the role's current policy. Add resource ARNs where the template has placeholders.

Add the policy gate

Build the C# policy gate from Complete code and run it against the good and bad policies. In your pipeline, the gate runs on every change to an IAM policy file.

AWS Console instructions

  • Console → IAM → Access analyzer → Analyzer settings → Create analyzer → Finding type: External access analysis → Zone of trust: Current account → name hl-m05-external.
  • Console → IAM → Access analyzer → Resource analysis (external and internal findings) and Unused access list findings. Choose a finding to see the principal, the access level and the policy statement that grants it. Archive with a reason for intended access; set up archive rules for patterns you accept organisation-wide.
  • Console → IAM → Roles → (role) → Access Advisor shows each service with Last accessed; for some services (for example EC2, IAM, Lambda, S3) it drills down to actions.
  • Console → IAM → Roles → (role) → Permissions → Generate policy based on CloudTrail events → choose up to 90 days, the trail and a service role → Generate policy. The generated template is viewable for 7 days.
  • Console → IAM → Policies → (policy) → Edit → JSON shows Policy validation results live. The Check for new access tab runs a custom policy check (charged per check).

AWS CLI

# 1. External access analyzer for this account (free).
aws accessanalyzer create-analyzer --profile learn-sandbox --region us-east-1 \
  --analyzer-name hl-m05-external --type ACCOUNT \
  --tags Project=cea-lab,Lab=m05-least-privilege,Environment=learn,Owner=alex

# 2. List active findings (v2 API covers all finding types).
ANALYZER_ARN=$(aws accessanalyzer get-analyzer --analyzer-name hl-m05-external \
  --profile learn-sandbox --region us-east-1 --query analyzer.arn --output text)
aws accessanalyzer list-findings-v2 --analyzer-arn "$ANALYZER_ARN" \
  --filter '{"status":{"eq":["ACTIVE"]}}' --profile learn-sandbox --region us-east-1

# 3. (Credits) Unused access analyzer: report anything unused for 30+ days.
aws accessanalyzer create-analyzer --profile learn-sandbox --region us-east-1 \
  --analyzer-name hl-m05-unused --type ACCOUNT_UNUSED_ACCESS \
  --configuration '{"unusedAccess":{"unusedAccessAge":30}}' \
  --tags Project=cea-lab,Lab=m05-least-privilege,Environment=learn,Owner=alex

# 4. Last accessed data, action level, for one role (free, asynchronous job).
JOB_ID=$(aws iam generate-service-last-accessed-details --profile learn-sandbox \
  --arn arn:aws:iam::111122223333:role/hl-m05-accounts-api --granularity ACTION_LEVEL \
  --query JobId --output text)
aws iam get-service-last-accessed-details --job-id "$JOB_ID" --profile learn-sandbox \
  --query "ServicesLastAccessed[].{Service:ServiceNamespace,Last:LastAuthenticated}"

# 5. Validate a policy (free): errors, security warnings, warnings, suggestions.
aws accessanalyzer validate-policy --profile learn-sandbox --region us-east-1 \
  --policy-type IDENTITY_POLICY --policy-document file://candidate-policy.json \
  --query "findings[].{Type:findingType,Code:issueCode,Detail:findingDetails}"

# 6. Custom check (USD 0.002 per call): does the policy grant any forbidden action?
aws accessanalyzer check-access-not-granted --profile learn-sandbox --region us-east-1 \
  --policy-type IDENTITY_POLICY --policy-document file://candidate-policy.json \
  --access '[{"actions":["kms:ScheduleKeyDeletion","cloudtrail:StopLogging","iam:CreateAccessKey"]}]'

# 7. Custom check: does the new version grant anything the old one did not?
aws accessanalyzer check-no-new-access --profile learn-sandbox --region us-east-1 \
  --policy-type IDENTITY_POLICY \
  --existing-policy-document file://current-policy.json --new-policy-document file://candidate-policy.json

# 8. Policy generation from CloudTrail (free; needs a trail and a service role).
aws accessanalyzer start-policy-generation --profile learn-sandbox --region us-east-1 \
  --policy-generation-details principalArn=arn:aws:iam::111122223333:role/hl-m05-accounts-api \
  --cloud-trail-details '{
    "trails":[{"cloudTrailArn":"arn:aws:cloudtrail:us-east-1:111122223333:trail/hl-m05-trail","allRegions":true}],
    "accessRole":"arn:aws:iam::111122223333:role/service-role/AccessAnalyzerMonitorServiceRole_hlm05",
    "startTime":"2026-11-16T00:00:00Z"}'
aws accessanalyzer get-generated-policy --job-id <job-id-from-previous-output> \
  --profile learn-sandbox --region us-east-1

The --filter syntax for list-findings-v2 and the exact JSON shape of --cloud-trail-details are worth checking with aws accessanalyzer <command> help if your CLI version differs ⚠ VERIFY.

Infrastructure as Code

infra/AccessAnalyzerStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.AccessAnalyzer;
using Constructs;

namespace Harbourline.Security.Infra;

public sealed class AccessAnalyzerStack : Stack
{
    public AccessAnalyzerStack(Construct scope, string id, IStackProps? props = null) : base(scope, id, props)
    {
        // External access analyzer: free, one per Region you use.
        _ = new CfnAnalyzer(this, "External", new CfnAnalyzerProps
        {
            AnalyzerName = "hl-m05-external",
            Type = "ACCOUNT", // "ORGANIZATION" from the delegated administrator account
            // Union-typed CDK properties are 'object' in C#, so use explicit arrays, not collection expressions.
            ArchiveRules = new[]
            {
                // Intended: the management account may assume OrganizationAccountAccessRole.
                new CfnAnalyzer.ArchiveRuleProperty
                {
                    RuleName = "org-access-role",
                    Filter = new[]
                    {
                        new CfnAnalyzer.FilterProperty { Property = "resource", Contains = new[] { "OrganizationAccountAccessRole" } }
                    }
                }
            }
        });

        // Unused access analyzer: charged per role/user analysed per month. Off by default in labs.
        if (Node.TryGetContext("enableUnusedAccess") as string == "true")
        {
            _ = new CfnAnalyzer(this, "Unused", new CfnAnalyzerProps
            {
                AnalyzerName = "hl-m05-unused",
                Type = "ACCOUNT_UNUSED_ACCESS",
                AnalyzerConfiguration = new CfnAnalyzer.AnalyzerConfigurationProperty
                {
                    UnusedAccessConfiguration = new CfnAnalyzer.UnusedAccessConfigurationProperty
                    {
                        UnusedAccessAge = 30
                    }
                }
            });
        }

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

Deploy with cdk deploy -c enableUnusedAccess=false (the default) to stay free.

Complete code

A pipeline policy gate: it reads every *.json policy in a folder, runs free validation, then a paid CheckAccessNotGranted for Harbourline's forbidden actions, and exits non-zero on any failure. It needs a role with access-analyzer:ValidatePolicy and access-analyzer:CheckAccessNotGranted (both support only "Resource": "*").

Harbourline.Security.PolicyGate.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.PolicyGate</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.AccessAnalyzer" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
  </ItemGroup>
</Project>
Program.cs
using Amazon;
using Amazon.AccessAnalyzer;
using Amazon.AccessAnalyzer.Model;

// Usage: dotnet run -- <folder-with-identity-policies> [--skip-paid-checks]
if (args.Length == 0 || !Directory.Exists(args[0]))
{
    Console.Error.WriteLine("Usage: dotnet run -- <policy-folder> [--skip-paid-checks]");
    return 2;
}

var skipPaid = args.Contains("--skip-paid-checks");

// Actions no workload policy at Harbourline may grant. Owned by the security team.
string[] forbiddenActions =
[
    "iam:CreateAccessKey", "iam:CreateUser", "iam:PutRolePolicy", "iam:AttachRolePolicy",
    "kms:ScheduleKeyDeletion", "kms:PutKeyPolicy",
    "cloudtrail:StopLogging", "cloudtrail:DeleteTrail",
    "s3:PutBucketPolicy", "s3:DeleteBucketPolicy", "s3:PutBucketPublicAccessBlock"
];

// The SDK uses the default credential chain: AWS_PROFILE=learn-sandbox locally, the pipeline role in CI.
using var analyzer = new AmazonAccessAnalyzerClient(RegionEndpoint.USEast1);
var failed = false;

foreach (var file in Directory.EnumerateFiles(args[0], "*.json").Order())
{
    var document = await File.ReadAllTextAsync(file);
    Console.WriteLine($"== {Path.GetFileName(file)}");

    // 1. Free: grammar and best-practice validation (follows pagination).
    var findings = new List<ValidatePolicyFinding>();
    await foreach (var f in analyzer.Paginators.ValidatePolicy(new ValidatePolicyRequest
                   {
                       PolicyDocument = document,
                       PolicyType = PolicyType.IDENTITY_POLICY
                   }).Findings)
    {
        findings.Add(f);
    }

    foreach (var f in findings)
    {
        var blocking = f.FindingType == ValidatePolicyFindingType.ERROR
                       || f.FindingType == ValidatePolicyFindingType.SECURITY_WARNING;
        failed |= blocking;
        Console.WriteLine($"   {(blocking ? "FAIL" : "info")} {f.FindingType} {f.IssueCode}: {f.FindingDetails}");
    }

    if (skipPaid) continue;

    // 2. Paid (USD 0.002 per call): does the policy grant any forbidden action?
    var check = await analyzer.CheckAccessNotGrantedAsync(new CheckAccessNotGrantedRequest
    {
        PolicyDocument = document,
        PolicyType = AccessCheckPolicyType.IDENTITY_POLICY,
        Access = [new Access { Actions = [.. forbiddenActions] }]
    });

    if (check.Result == CheckAccessNotGrantedResult.FAIL)
    {
        failed = true;
        Console.WriteLine($"   FAIL forbidden access: {check.Message}");
        foreach (var reason in check.Reasons ?? [])
            Console.WriteLine($"        statement {reason.StatementIndex} ({reason.StatementId}): {reason.Description}");
    }
    else
    {
        Console.WriteLine("   pass no forbidden actions granted");
    }
}

Console.WriteLine(failed ? "Policy gate: FAILED" : "Policy gate: passed");
return failed ? 1 : 0;

Two sample inputs to try:

policies/good-accounts-api.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadAccounts",
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:Query"],
      "Resource": "arn:aws:dynamodb:us-east-1:111122223333:table/hl-m05-accounts"
    }
  ]
}
policies/bad-ops-helper.json
{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": "iam:PassRole", "Resource": "*" },
    { "Effect": "Allow", "Action": ["kms:*", "s3:Put*"], "Resource": "*" }
  ]
}

Expected output (abridged):

== bad-ops-helper.json
   FAIL SECURITY_WARNING PASS_ROLE_WITH_STAR_IN_RESOURCE: Using the iam:PassRole action with wildcards (*) in the resource can be overly permissive ...
   FAIL forbidden access: The policy document grants access to perform one or more of the listed actions.
        statement 1 (): ...
== good-accounts-api.json
   pass no forbidden actions granted
Policy gate: FAILED

The exact issue codes and wording come from AWS and may change; do not match on message text in automation — match on FindingType and Result.

Code explained line by line

  1. skipPaid — lets developers run the free checks locally as often as they like and leave the paid check to the pipeline.
  2. forbiddenActions — a short, security-owned list. These actions are reserved for the platform and security pipelines; a workload role that gets one of them has a privilege-escalation path.
  3. new AmazonAccessAnalyzerClient(RegionEndpoint.USEast1) — no explicit credentials: the default chain uses AWS_PROFILE on your laptop and the pipeline's OIDC role in CI. Never put credentials in this tool.
  4. analyzer.Paginators.ValidatePolicy(...) — validation can return many findings; the paginator follows NextToken.
  5. PolicyType.IDENTITY_POLICY — validation rules differ for RESOURCE_POLICY and SERVICE_CONTROL_POLICY; choose the type matching the file. A real gate would read the type from the folder name.
  6. ERROR and SECURITY_WARNING block; WARNING and SUGGESTION are printed for the reviewer. That split keeps the gate strict without being noisy.
  7. CheckAccessNotGrantedAsync with Access = [new Access { Actions = [...] }] — automated reasoning proves whether any statement in the policy could allow any listed action, including through wildcards such as kms:*. That is why the bad policy fails even though it never spells out kms:ScheduleKeyDeletion.
  8. check.Reasons — points to the statement index that grants the access, so the developer knows what to fix. In SDK v4 the list may be null, hence ?? [].
  9. return failed ? 1 : 0; — a non-zero exit fails the pipeline step.

⚠ Learning shortcut — not for production

The gate checks identity policies only and treats every file the same. A production gate also validates resource policies (RESOURCE_POLICY with the matching ValidatePolicyResourceType), SCPs and RCPs, runs CheckNoNewAccess against the deployed version so reviewers see exactly what is being added, and runs CheckNoPublicAccess on bucket and key policies. Many teams run the same checks on synthesised CloudFormation templates with the open-source IAM Policy Validator for CloudFormation and Terraform. Keep the forbidden list in a separate, security-owned repository so a workload team cannot edit it in the same pull request.

Security considerations

  • Archive findings with a reason, never just dismiss them. Archive rules are themselves evidence: "we accept that the management account can assume this role, because…".
  • Look at the trend, not only the backlog. A rising count of unused-access findings means roles are being created faster than they are reviewed.
  • Least privilege includes time. Short session durations and just-in-time elevation (see IAM Identity Center, MFA and temporary credentials) reduce exposure as much as narrow actions do.
  • Do not trust generated policies blindly. They reflect what happened, including mistakes and misuse during the window. Review them and add resource ARNs and conditions.
  • Protect the tags that ABAC depends on with deny statements and SCPs.
  • Use guardrails as a backstop. Even with perfect workload policies, SCPs deny the catastrophic actions organisation-wide (see Permission boundaries, SCPs, RCPs and resource policies).

Banking use case

Harbourline's quarterly access review for the Payments account used to be a spreadsheet exercise. Now:

  1. The unused access analyzer (organisation-wide, run from the security tooling account) lists roles unused for 90 days and services unused within active roles. Findings flow into Security Hub.
  2. Each team receives a generated report and must either remove the unused permission through a pull request or record why it is needed (for example, a disaster-recovery role exercised only during the annual test).
  3. The pull request passes through the policy gate. CheckNoNewAccess proves the change only removes access.
  4. The review record, the findings export and the merged pull requests form the evidence pack for internal audit.

Whether this process satisfies a particular regulatory access-review requirement is for Harbourline's compliance team and auditors to confirm.

Common mistakes

  • Starting broad "and tightening later" → later never comes → start narrow; let developers request additions with justification.
  • Using aws:SourceIp for requests that come through a VPC endpoint → requests through an endpoint carry a private address, not your public IP → use aws:SourceVpce or aws:SourceVpc for private traffic.
  • Forgetting IfExists on organisation conditions → AWS service principals do not have aws:PrincipalOrgID, so the deny blocks CloudTrail or Config from writing → combine with aws:PrincipalIsAWSService as in the bucket policy above.
  • Generating a policy over a window that missed the month-end batch → production breaks on the first of the month → choose a window that covers a full business cycle, or add known periodic actions by hand.
  • Leaving the unused access analyzer running in a sandbox → small but recurring charge → delete it after the lab.
  • Treating Access Analyzer's external findings as covering identity policies → it analyses resource policies; over-broad identity policies show up in unused-access findings and policy checks instead.

Troubleshooting

SymptomLikely causeFix
No findings in the analyzer after creating a shared bucketWrong Region, or the analysis has not run yetAnalyzers are Regional; wait up to about 30 minutes or use Rescan
Policy generation fails with an access error to the trail bucketService role lacks s3:GetObject/kms:Decrypt, or logs are in another accountFix the service role; for cross-account trails update the bucket and key policy as documented
Generated policy has only service-level entries (s3:* placeholders)Action-level data not available for that serviceChoose actions by hand from the Service Authorization Reference
ValidatePolicy returns ERROR MISSING_VERSIONNo Version elementAdd "Version": "2012-10-17"
CheckAccessNotGranted returns FAIL for a policy that "doesn't mention" the actionA wildcard (kms:*, *:*) or NotAction covers itReplace the wildcard with explicit actions
Unused access finding for a role you know is usedThe role is used only through a service that does not report last accessed data, or less often than the thresholdIncrease the threshold, or archive with a reason

Cost and cleanup

ItemCost
External access analyzer, policy validation, policy generationNo additional charge
Custom policy checksUSD 0.002 per call — the gate above costs well under one cent per run
Unused access analyzerUSD 0.20 per role/user analysed per month (optional step)
Internal access analyzerCharged per monitored resource per Region per month — not used in this lab
CloudTrail first management-events trailFree; S3 storage for the logs is a few cents

Free alternative for the optional steps: use Access Advisor (last accessed data) and --skip-paid-checks.

# Delete analyzers created in this lesson.
aws accessanalyzer delete-analyzer --analyzer-name hl-m05-unused --profile learn-sandbox --region us-east-1
aws accessanalyzer delete-analyzer --analyzer-name hl-m05-external --profile learn-sandbox --region us-east-1

# Remove the test bucket (and its policy) from the guided steps.
aws s3 rb s3://hl-m05-share-test-alex --force --profile learn-sandbox

# Confirm nothing tagged for this lab remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m05-least-privilege \
  --region us-east-1 --profile learn-sandbox --query "ResourceTagMappingList[].ResourceARN"

Many organisations keep the free external access analyzer running permanently in every Region — that is a sensible production choice, not a leftover.

Exercises

  • 🟢 Guided: Create the external analyzer, produce a cross-account finding with a test bucket policy, archive it with a rule, then remove the policy and confirm the finding is resolved.
  • 🟡 Challenge: Extend the policy gate to call CheckNoNewAccess: compare each file in policies/ with the version on the main branch (git show main:policies/<file>) and print the statements that add access.
  • 🔴 Live problem: The data platform team's Glue job role has AmazonS3FullAccess and AWSGlueServiceRole. They are about to process card-transaction extracts. You have one week, no downtime allowed, and the team says "we don't know which buckets the job touches". Plan the reduction.

Assignment

Add labs/m05-secure-banking-api/policies/-style samples to your own repository: three good and three bad identity policies for Harbourline workloads, the policy gate, and a GitHub Actions job that runs it with --skip-paid-checks on pull requests and the full gate on main. Document the forbidden-actions list and who owns it.

Solutions

Knowledge check

Interview questions

  • "How do you implement least privilege across 100 roles you inherited?" — Guardrails first (SCPs, boundaries) to stop the worst; gather evidence (CloudTrail including data events, last accessed data, unused-access findings); generate and review policies; deploy through a gated pipeline; repeat on a schedule; measure the backlog.
  • "What is the difference between aws:SourceIp and aws:SourceVpce?" — SourceIp is the public IP of internet-routed requests; requests through a VPC endpoint carry private addresses, so you restrict those with SourceVpce or SourceVpc.
  • "How would you stop a developer's pull request from granting iam:PassRole on *?" — Policy validation flags it as a security warning; CheckAccessNotGranted blocks forbidden actions; reviewers see CheckNoNewAccess output; an SCP or boundary is the runtime backstop.
  • "What is ABAC and when would you not use it?" — Permissions based on matching tags on principals and resources. Avoid it when tag governance is weak or when auditors need a simple list of "who can access X" — RBAC is easier to explain.

Certification practice

Completion checklist

  • I can describe the six-step least-privilege lifecycle and who owns each step
  • I created an external access analyzer, produced a finding, archived and resolved it
  • I read last accessed information for a role
  • I ran the policy gate against a good and a bad policy
  • I deleted any unused access analyzer and test bucket

Key takeaways

  • Least privilege is a loop — design, generate, validate, deploy, monitor, trim — not a project.
  • Resource policies fence (aws:PrincipalOrgID, aws:SourceVpce, aws:SecureTransport); identity policies grant specific actions on specific ARNs.
  • IAM Access Analyzer gives you external, internal and unused access findings, free validation, paid custom checks and free policy generation — know which costs money.
  • Generated policies reflect history, not need; review them and add iam:PassRole and data-event actions by hand.
  • Automate the gate in the pipeline so least privilege does not depend on reviewers spotting wildcards.

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