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

Federation and segregation of duties

Connect Microsoft Entra ID or Active Directory to IAM Identity Center, federate CI/CD pipelines with OIDC, use attributes for access control, and design roles that separate building, approving, deploying and auditing.

intermediate⏱ 1 h 50 min🟢 FreeSCS-C03SAA-C03DVA-C03

Assumes: .NET 10 LTS · AWS SDK for .NET v4 (AWSSDK.SSOAdmin 4.1.1.2, AWSSDK.IdentityStore 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:

  • Choose an identity source for IAM Identity Center (its own directory, Active Directory, or an external IdP such as Microsoft Entra ID) and explain the role of SAML 2.0 and SCIM.
  • Federate a GitHub Actions pipeline into AWS with OIDC, without any stored access keys, and scope the trust to one repository and environment.
  • Use attributes for access control (ABAC) so that Entra ID attributes such as department become session tags in AWS.
  • Design a segregation of duties (SoD) model for a bank: separate build, approve, deploy, operate, audit, key administration and break-glass.
  • Enforce SoD with permission sets, an SCP and pipeline approvals, and detect violations with a C# tool and CloudTrail.

Prerequisites

Why this matters in banking

A Harbourline engineer leaves the bank on Friday. HR disables her Entra ID account at 17:00. If her AWS access lived in separate IAM users with passwords and access keys, she could still log in to AWS on Monday — and nobody would notice until the quarterly access review. With federation, the bank's single identity provider is the only place a person exists; disable them there and every AWS session they could start is gone.

Segregation of duties is the other half. Regulators, internal audit and frameworks such as PCI DSS expect that no single person can both change and approve a production payment system, that the person who manages encryption keys cannot also read the data they protect, and that auditors have read-only access that nobody else can tamper with. A developer with AdministratorAccess in production breaks every one of these rules, even if they never misuse it. You must be able to show separation, not just promise it.

The idea in plain language

Federation means AWS trusts someone else to say who you are. Instead of AWS storing your password, the bank's identity provider (IdP) — usually Microsoft Entra ID or Active Directory — signs you in, applies the bank's MFA and conditional-access rules, and hands AWS a signed statement ("this is alex.morgan, member of group aws-payments-developers"). AWS swaps that statement for temporary credentials for a role.

  • SAML 2.0 is the older XML standard for that signed statement, used for people signing in through a browser.
  • OIDC (OpenID Connect) is the newer JSON/JWT standard, used for people and for machines — for example, a GitHub Actions job proving "I am the deploy workflow of repo harbourline/payments-api on branch main".
  • SCIM is a separate standard for provisioning: it copies users and groups from the IdP into IAM Identity Center automatically, and removes them when they leave.

Segregation of duties means splitting a sensitive process into steps performed by different people (or systems), so that one compromised or careless person cannot complete it alone. The classic banking form is maker-checker (four-eyes): one person prepares a payment, another approves it. In cloud engineering: one person writes the change, another reviews and approves it, an automated pipeline (not a human) deploys it, and a separate auditor role can read — but never alter — the evidence.

Analogy: Federation is the bank's staff badge being accepted at a partner's building: the partner does not issue its own badges; it trusts head office's badge system and lets you in for one visit. Segregation of duties is the vault rule that two different keyholders must turn their keys at the same time — neither can open it alone, and the CCTV operator who records them has no key at all.

What problem each service solves

ComponentWhat it doesWhen to use itLimitations and sharp edges
IAM Identity Center — external IdPUses Entra ID, Okta, etc. for sign-in (SAML 2.0) and SCIM for provisioningThe bank already has Entra ID with MFA and conditional access — the normal choiceOne identity source per instance; Entra's provisioning does not flatten nested groups; removing an attribute in Entra does not remove it in Identity Center (a known Entra limitation)
IAM Identity Center — Active DirectoryUses on-premises AD via AD Connector (a proxy, no data stored in AWS) or AWS Managed Microsoft AD (a real AD domain run by AWS, which can trust on-prem AD)The bank's source of truth is on-prem AD and Entra is not used for AWSDirectory Service has hourly charges; network connectivity (VPN/Direct Connect) to domain controllers needed for AD Connector
IAM Identity Center directoryUsers and groups stored in Identity Center itselfLabs, small organisationsA second set of identities to manage — avoid in a bank
IAM SAML identity providerPer-account SAML trust directly to IAM rolesLegacy setups; special casesYou manage roles and SAML apps per account; Identity Center is preferred for people
IAM OIDC identity providerPer-account trust for a JWT issuer (GitHub Actions, GitLab, Terraform Cloud, EKS)Workloads and pipelines that need AWS credentials without keysThe trust policy must restrict the token's sub claim — IAM refuses GitHub trust policies whose sub is missing or just a wildcard
Attributes for access controlPasses IdP attributes as session tags (aws:PrincipalTag/…)ABAC — one permission set serving many teamsPolicies become data-dependent; test thoroughly and protect tags
Permission setsTemplates that become AWSReservedSSO_… roles in each assigned accountAll human accessSession 1–12 hours; changes reprovision all assigned accounts

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Entra ID enterprise app for SAML SSOEntra ID gallery app AWS IAM Identity CenterOne app for all AWS accounts; accounts and roles are chosen in the AWS access portal
Entra ID automatic user provisioning (SCIM)Identity Center automatic provisioning (SCIM endpoint + bearer token)Token is shown once and expires; plan its rotation ⚠ VERIFY current token lifetime
Azure RBAC role assignment at subscription scopePermission set assigned to a group on an accountAssignments are per account, not per resource group
Entra ID PIM (eligible roles, approval, time-bound)No native equivalent; separate permission sets with short sessions plus an approval workflow (for example AWS's open-source temporary elevated access solution ⚠ VERIFY name and support status)Plan JIT elevation explicitly
Azure DevOps service connection with workload identity federationIAM OIDC provider + role trusting token.actions.githubusercontent.com (or your CI's issuer)Same idea: no secrets; scope by repo, branch and environment
Conditional access policiesEnforced in Entra before the SAML assertion is issued; AWS adds aws:SourceIp, aws:MultiFactorAuthPresent, SCPsMFA for external-IdP users happens in the IdP, not in Identity Center
Entra ID dynamic groups by departmentABAC with AccessControl:Department → aws:PrincipalTag/DepartmentTag-based policies, evaluated per request
Azure DevOps approvals and checks / branch policiesGitHub environment protection rules (required reviewers), CodePipeline manual approvalThe approver identity is recorded in GitHub/CodePipeline, not CloudTrail, unless you export it

Architecture

Security-boundary view. There are two trust anchors: Entra ID for people and GitHub's OIDC issuer for pipelines. AWS never stores a long-term password or access key for either. Only the pipeline role can change production; people's roles in production are read-only, approval or audit. The management account (where Identity Center lives) is a separate, tightly held boundary — whoever administers Identity Center can grant themselves anything, so that permission set is itself a privileged, dual-controlled role.

Segregation of duties at Harbourline

The Harbourline permission-set design

Permission setAssigned to (Entra group)AccountsSessionCanCannot
PaymentsDeveloperaws-payments-developerspayments-dev, payments-test8 hBuild and deploy in non-prod; create roles only with the app boundaryAnything in prod; touch KMS key policies
PaymentsReadOnlyaws-payments-developerspayments-prod4 hRead configuration, metrics, logs (masked)Read data stores, secrets or decrypt; change anything
PaymentsOperatoraws-payments-operationspayments-prod4 hRestart/scale ECS services, run approved SSM Automation runbooksDeploy code, change IAM, read secrets
ReleaseApproveraws-change-approverspayments-prod (read only)1 hRead change sets and pipeline stateDeploy; approve their own change (enforced in GitHub)
KeyAdministratoraws-crypto-custodianssecurity-tooling, payments-prod1 hCreate, rotate, disable, schedule deletion of keys; edit key policieskms:Decrypt, kms:GenerateDataKey, read data
SecurityAuditoraws-internal-auditall4 hSecurityAudit + ViewOnlyAccess, read the log archiveAny write; any decrypt of customer data
IdentityAdministratoraws-identity-admins (2 people)management1 hManage Identity Center assignmentsWorkload access; change SCPs (separate OrgPolicyAdministrator)
BreakGlassnone (sealed procedure)all1 hAdministratorUse without alerting the SOC and a post-incident review

Rules of thumb behind the table:

  1. Nobody deploys to production by hand. Only the pipeline role can.
  2. Key administrators cannot use keys; key users cannot administer them. This is enforced in the KMS key policy (see AWS KMS).
  3. Whoever grants access cannot also grant it to themselves without a second person. Identity Center assignments are changed through an approved request and logged; a periodic review compares assignments with the HR system.
  4. Auditors read, never write — and the log archive they read is in a separate account with Object Lock (see CloudTrail for banks).
  5. Toxic combinations are forbidden, for example PaymentsDeveloper in prod, or KeyAdministrator + PaymentsOperator for the same person.

Step-by-step implementation

Choose and connect the identity source

In the management account: IAM Identity Center → Settings → Identity source → Actions → Change identity source → External identity provider. Download the AWS service-provider metadata, keep the page open, then in the Microsoft Entra admin center add the gallery application AWS IAM Identity Center, upload the AWS metadata under Single sign-on → SAML, download Entra's Federation Metadata XML, and upload it back into Identity Center. Type ACCEPT to confirm. Changing the identity source can remove existing users and assignments ⚠ — do it before you create assignments, or plan the migration.

Turn on SCIM provisioning

In Identity Center → Settings → Identity source → Automatic provisioning → Enable, copy the SCIM endpoint and access token (shown only once). In Entra, open the app's Provisioning, set mode Automatic, paste the endpoint as Tenant URL and the token as Secret Token, Test connection, then assign groups (not individual users) and Start provisioning. Store the token in the bank's secret vault and record its expiry date in the operations calendar.

Enable attributes for access control (optional ABAC)

In Entra Single sign-on → Attributes & Claims, add a claim named AccessControl:Department with namespace https://aws.amazon.com/SAML/Attributes and source user.department. In Identity Center Settings → Attributes for access control → Enable. The attribute arrives in AWS sessions as the tag aws:PrincipalTag/Department.

Create permission sets and assign groups

Create the permission sets from the table above (IaC below). Assign groups to accounts — never individual users, so that joiner/mover/leaver changes happen only in Entra.

Federate the pipeline with OIDC

In the payments account, create an IAM OIDC provider for https://token.actions.githubusercontent.com with audience sts.amazonaws.com, and a role hl-payments-deployer whose trust policy accepts only the production environment of the harbourline/payments-api repository. In GitHub, protect the production environment with required reviewers from the change-approvers team.

Add a preventive SoD guardrail and a detective check

Attach an SCP to the production OU that denies deployment actions to every principal except the pipeline role, and denies key administration except to KeyAdministrator. Then run the C# SoD checker weekly to detect people who hold conflicting permission sets.

AWS Console instructions

  • Permission set: IAM Identity Center → Multi-account permissions → Permission sets → Create permission set → Custom permission set. Attach managed policies or an inline policy, set Session duration, add tags, Create.
  • Assignment: Multi-account permissions → AWS accounts → select the account → Assign users or groups → Groups tab → choose group → choose permission set → Submit.
  • OIDC provider: IAM → Identity providers → Add provider → OpenID Connect, provider URL https://token.actions.githubusercontent.com, audience sts.amazonaws.com.
  • Role for GitHub: IAM → Roles → Create role → Web identity → provider token.actions.githubusercontent.com, audience sts.amazonaws.com, enter organisation, repository and branch. Then edit the trust policy to use the environment subject (shown below).
  • Evidence: CloudTrail → Event history, filter Event name = AssumeRoleWithWebIdentity (pipeline) or AssumeRoleWithSAML (people federating via IAM SAML).

AWS CLI

# --- Identity Center (management account) ---
# Find the Identity Center instance and its identity store.
aws sso-admin list-instances --profile learn-mgmt \
  --query 'Instances[0].[InstanceArn,IdentityStoreId]' --output text

INSTANCE_ARN=arn:aws:sso:::instance/ssoins-1111222233334444
# Create a permission set with a 1-hour session (ISO 8601 duration).
aws sso-admin create-permission-set --instance-arn "$INSTANCE_ARN" \
  --name KeyAdministrator --session-duration PT1H \
  --description "Manage KMS keys; never use them" \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m05-sod --profile learn-mgmt

# Assign a GROUP to an account with that permission set.
aws sso-admin create-account-assignment --instance-arn "$INSTANCE_ARN" \
  --target-id 111122223333 --target-type AWS_ACCOUNT \
  --permission-set-arn arn:aws:sso:::permissionSet/ssoins-1111222233334444/ps-aaaabbbbccccdddd \
  --principal-type GROUP --principal-id 9a1b2c3d-1111-2222-3333-444455556666 --profile learn-mgmt

# --- GitHub OIDC (workload account) ---
# Register GitHub's OIDC issuer. IAM validates GitHub's certificate chain itself,
# so a thumbprint is no longer required for this provider.
aws iam create-open-id-connect-provider \
  --url https://token.actions.githubusercontent.com \
  --client-id-list sts.amazonaws.com \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m05-sod --profile learn-sandbox

# Create the deployer role with a trust policy scoped to one repo + environment.
aws iam create-role --role-name hl-m05-github-deployer \
  --assume-role-policy-document file://trust-github.json \
  --max-session-duration 3600 \
  --tags Key=Project,Value=cea-lab Key=Lab,Value=m05-sod --profile learn-sandbox

# Evidence: who assumed the pipeline role in the last day?
aws cloudtrail lookup-events --profile learn-sandbox \
  --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \
  --start-time "$(date -u -d '-1 day' +%Y-%m-%dT%H:%M:%SZ)" \
  --query 'Events[].CloudTrailEvent' --output text

The trust policy for the pipeline role:

trust-github.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "GitHubProductionEnvironmentOnly",
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:harbourline/payments-api:environment:production"
        }
      }
    }
  ]
}

Why the environment subject rather than a branch: a GitHub job that targets the production environment can only start after the environment's protection rules pass (required reviewers, allowed branches). The sub claim then carries environment:production, so AWS will only issue credentials to jobs that went through the approval. A branch-based subject (ref:refs/heads/main) would let any workflow on main deploy without the approval step.

The matching GitHub workflow:

.github/workflows/deploy.yml
name: deploy-payments
on:
  push:
    branches: [main]
permissions:
  id-token: write   # allow the job to request an OIDC token
  contents: read
jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production   # protection rules: required reviewers from change-approvers
    steps:
      - uses: actions/checkout@v5
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: arn:aws:iam::111122223333:role/hl-m05-github-deployer
          aws-region: us-east-1
          role-session-name: gh-${{ github.run_id }}
      - run: aws sts get-caller-identity

Infrastructure as Code

SegregationOfDutiesStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.SSO;
using Constructs;

namespace Harbourline.Security.Infra;

// Deploy to the MANAGEMENT account (or Identity Center delegated admin account).
public sealed class SegregationOfDutiesStack : Stack
{
    public SegregationOfDutiesStack(Construct scope, string id, string instanceArn,
        string prodAccountId, string cryptoCustodiansGroupId, IStackProps? props = null)
        : base(scope, id, props)
    {
        // Key administrators manage keys but can never use them.
        var keyAdmin = new CfnPermissionSet(this, "KeyAdministrator", new CfnPermissionSetProps
        {
            InstanceArn = instanceArn,
            Name = "KeyAdministrator",
            Description = "Manage KMS keys; no cryptographic use",
            SessionDuration = "PT1H",
            InlinePolicy = new PolicyDocument(new PolicyDocumentProps
            {
                Statements = new[]
                {
                    new PolicyStatement(new PolicyStatementProps
                    {
                        Sid = "ManageKeys",
                        Actions = new[]
                        {
                            "kms:Create*", "kms:Describe*", "kms:Enable*", "kms:List*", "kms:Put*",
                            "kms:Update*", "kms:Revoke*", "kms:Disable*", "kms:Get*", "kms:TagResource",
                            "kms:UntagResource", "kms:ScheduleKeyDeletion", "kms:CancelKeyDeletion",
                            "kms:RotateKeyOnDemand"
                        },
                        Resources = new[] { "*" }
                    }),
                    new PolicyStatement(new PolicyStatementProps
                    {
                        Sid = "NeverUseKeys",
                        Effect = Effect.DENY,
                        Actions = new[] { "kms:Decrypt", "kms:Encrypt", "kms:GenerateDataKey*",
                                          "kms:ReEncrypt*", "kms:Sign" },
                        Resources = new[] { "*" }
                    })
                }
            }).ToJSON()
        });

        // Assign the Entra-provisioned group (by Identity Store group ID) to production.
        _ = new CfnAssignment(this, "KeyAdminProd", new CfnAssignmentProps
        {
            InstanceArn = instanceArn,
            PermissionSetArn = keyAdmin.AttrPermissionSetArn,
            PrincipalType = "GROUP",
            PrincipalId = cryptoCustodiansGroupId,
            TargetType = "AWS_ACCOUNT",
            TargetId = prodAccountId
        });

        // Auditor: AWS managed read-only policies.
        _ = new CfnPermissionSet(this, "SecurityAuditor", new CfnPermissionSetProps
        {
            InstanceArn = instanceArn,
            Name = "SecurityAuditor",
            SessionDuration = "PT4H",
            ManagedPolicies = new[]
            {
                "arn:aws:iam::aws:policy/SecurityAudit",
                "arn:aws:iam::aws:policy/job-function/ViewOnlyAccess"
            }
        });

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

PolicyDocument.ToJSON() produces the JSON object that InlinePolicy expects. Deploying this stack needs the Identity Center instance ARN and the Identity Store group ID of the SCIM-provisioned group (from aws identitystore list-groups).

The SoD guardrail SCP (production OU)

hl-scp-prod-sod.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "OnlyPipelineDeploys",
      "Effect": "Deny",
      "Action": [
        "cloudformation:CreateStack", "cloudformation:UpdateStack", "cloudformation:DeleteStack",
        "cloudformation:ExecuteChangeSet", "lambda:UpdateFunctionCode",
        "ecs:RegisterTaskDefinition", "ecr:PutImage"
      ],
      "Resource": "*",
      "Condition": {
        "ArnNotLike": {
          "aws:PrincipalArn": [
            "arn:aws:iam::*:role/hl-payments-deployer",
            "arn:aws:iam::*:role/cdk-*-cfn-exec-role-*",
            "arn:aws:iam::*:role/hl-security-breakglass"
          ]
        }
      }
    },
    {
      "Sid": "OnlyKeyAdminsAdministerKeys",
      "Effect": "Deny",
      "Action": [
        "kms:PutKeyPolicy", "kms:ScheduleKeyDeletion", "kms:DisableKey", "kms:CreateGrant"
      ],
      "Resource": "*",
      "Condition": {
        "ArnNotLike": {
          "aws:PrincipalArn": [
            "arn:aws:iam::*:role/aws-reserved/sso.amazonaws.com/*AWSReservedSSO_KeyAdministrator_*",
            "arn:aws:iam::*:role/hl-payments-deployer",
            "arn:aws:iam::*:role/cdk-*-cfn-exec-role-*",
            "arn:aws:iam::*:role/hl-security-breakglass"
          ]
        },
        "BoolIfExists": { "aws:ViaAWSService": "false" }
      }
    }
  ]
}

Line notes: Identity Center roles live under the path /aws-reserved/sso.amazonaws.com/ (some Regions add the Region to the path ⚠ VERIFY your exact path with aws iam list-roles --path-prefix /aws-reserved/), so the pattern uses wildcards. The CDK execution role pattern cdk-*-cfn-exec-role-* is included because CloudFormation itself performs the create/update calls on the pipeline's behalf. kms:CreateGrant is often used by AWS services (EBS, RDS) on your behalf, hence aws:ViaAWSService.

Complete code

The SoD checker lists every account assignment in Identity Center, expands group memberships, and reports any person who holds a forbidden combination of permission sets in the same account. Run it with a read-only role in the management account (it needs sso:List*, sso:Describe* and identitystore:List*, identitystore:Describe*). All calls are free.

SodChecker.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.SodChecker</RootNamespace>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.SSOAdmin" Version="4.1.1.2" />
    <PackageReference Include="AWSSDK.IdentityStore" 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.IdentityStore;
using Amazon.IdentityStore.Model;
using Amazon.Runtime.CredentialManagement;
using Amazon.SSOAdmin;
using Amazon.SSOAdmin.Model;

namespace Harbourline.Security.SodChecker;

public sealed record Grant(string AccountId, string UserId, string PermissionSet);

public static class SodRules
{
    // Pairs of permission sets one person must never hold in the same account.
    public static readonly (string A, string B, string Why)[] ToxicPairs =
    [
        ("PaymentsDeveloper", "ReleaseApprover", "maker cannot approve own release"),
        ("KeyAdministrator", "PaymentsOperator", "key custodian must not operate the data service"),
        ("IdentityAdministrator", "PaymentsOperator", "access granter must not hold workload access"),
        ("PaymentsDeveloper", "SecurityAuditor", "auditor must be independent of the audited team"),
    ];

    public static IEnumerable<string> FindViolations(IEnumerable<Grant> grants) =>
        grants
            .GroupBy(g => (g.AccountId, g.UserId))
            .SelectMany(group =>
            {
                var held = group.Select(g => g.PermissionSet).ToHashSet(StringComparer.Ordinal);
                return ToxicPairs
                    .Where(p => held.Contains(p.A) && held.Contains(p.B))
                    .Select(p => $"{group.Key.AccountId} user {group.Key.UserId}: {p.A} + {p.B} ({p.Why})");
            });
}

internal static class Program
{
    private static async Task<int> Main()
    {
        var chain = new CredentialProfileStoreChain();
        if (!chain.TryGetAWSCredentials("learn-mgmt", out var creds))
        {
            Console.Error.WriteLine("Profile 'learn-mgmt' not found. Run: aws sso login --profile learn-mgmt");
            return 2;
        }

        using var sso = new AmazonSSOAdminClient(creds, RegionEndpoint.USEast1);
        using var store = new AmazonIdentityStoreClient(creds, RegionEndpoint.USEast1);

        var instance = (await sso.ListInstancesAsync(new ListInstancesRequest())).Instances?.FirstOrDefault()
            ?? throw new InvalidOperationException("No IAM Identity Center instance found.");

        var grants = new List<Grant>();
        var groupCache = new Dictionary<string, List<string>>();

        foreach (var psArn in await ListPermissionSetsAsync(sso, instance.InstanceArn))
        {
            var ps = await sso.DescribePermissionSetAsync(new DescribePermissionSetRequest
            {
                InstanceArn = instance.InstanceArn,
                PermissionSetArn = psArn
            });
            var psName = ps.PermissionSet.Name;

            foreach (var accountId in await ListAccountsAsync(sso, instance.InstanceArn, psArn))
            {
                foreach (var a in await ListAssignmentsAsync(sso, instance.InstanceArn, accountId, psArn))
                {
                    if (a.PrincipalType == PrincipalType.USER)
                    {
                        grants.Add(new Grant(accountId, a.PrincipalId, psName));
                        continue;
                    }

                    // Expand group membership once per group.
                    if (!groupCache.TryGetValue(a.PrincipalId, out var members))
                    {
                        members = await ListGroupMembersAsync(store, instance.IdentityStoreId, a.PrincipalId);
                        groupCache[a.PrincipalId] = members;
                    }
                    grants.AddRange(members.Select(userId => new Grant(accountId, userId, psName)));
                }
            }
        }

        var violations = SodRules.FindViolations(grants).ToList();
        Console.WriteLine($"Checked {grants.Count} effective grants.");
        violations.ForEach(v => Console.WriteLine($"VIOLATION {v}"));
        return violations.Count == 0 ? 0 : 1;
    }

    private static async Task<List<string>> ListPermissionSetsAsync(IAmazonSSOAdmin sso, string instanceArn)
    {
        var result = new List<string>();
        string? token = null;
        do
        {
            var page = await sso.ListPermissionSetsAsync(new ListPermissionSetsRequest
            { InstanceArn = instanceArn, NextToken = token });
            result.AddRange(page.PermissionSets ?? []);
            token = page.NextToken;
        } while (token is not null);
        return result;
    }

    private static async Task<List<string>> ListAccountsAsync(IAmazonSSOAdmin sso, string instanceArn, string psArn)
    {
        var result = new List<string>();
        string? token = null;
        do
        {
            var page = await sso.ListAccountsForProvisionedPermissionSetAsync(
                new ListAccountsForProvisionedPermissionSetRequest
                { InstanceArn = instanceArn, PermissionSetArn = psArn, NextToken = token });
            result.AddRange(page.AccountIds ?? []);
            token = page.NextToken;
        } while (token is not null);
        return result;
    }

    private static async Task<List<AccountAssignment>> ListAssignmentsAsync(
        IAmazonSSOAdmin sso, string instanceArn, string accountId, string psArn)
    {
        var result = new List<AccountAssignment>();
        string? token = null;
        do
        {
            var page = await sso.ListAccountAssignmentsAsync(new ListAccountAssignmentsRequest
            { InstanceArn = instanceArn, AccountId = accountId, PermissionSetArn = psArn, NextToken = token });
            result.AddRange(page.AccountAssignments ?? []);
            token = page.NextToken;
        } while (token is not null);
        return result;
    }

    private static async Task<List<string>> ListGroupMembersAsync(
        IAmazonIdentityStore store, string identityStoreId, string groupId)
    {
        var result = new List<string>();
        string? token = null;
        do
        {
            var page = await store.ListGroupMembershipsAsync(new ListGroupMembershipsRequest
            { IdentityStoreId = identityStoreId, GroupId = groupId, NextToken = token });
            result.AddRange((page.GroupMemberships ?? [])
                .Select(m => m.MemberId?.UserId)
                .OfType<string>());
            token = page.NextToken;
        } while (token is not null);
        return result;
    }
}

Code explained line by line

  1. record Grant(AccountId, UserId, PermissionSet) — the normalised fact "this person can use this permission set in this account", whether they got it directly or through a group.
  2. SodRules.ToxicPairs — the bank's SoD matrix as data. Each pair carries a human-readable reason, which is what an auditor wants to see in the report.
  3. FindViolations — groups grants by (account, user), builds the set of permission sets held, and yields one message per toxic pair present. It is a pure function, so you can unit-test it without AWS (try it: create two Grant objects and assert one violation).
  4. CredentialProfileStoreChain / learn-mgmt — Identity Center is administered from the management account (or a delegated administrator), so the tool uses that profile. Use a read-only permission set for it.
  5. ListInstancesAsync — returns the Identity Center instance ARN and its IdentityStoreId (the directory where SCIM-provisioned users and groups live).
  6. ListPermissionSetsAsync helper — the first of four manual pagination loops. Each do … while (token is not null) loop follows NextToken until AWS stops returning one. ?? [] guards against SDK v4 returning null for empty lists.
  7. DescribePermissionSetAsync — converts an ARN such as …/ps-aaaabbbbccccdddd into the friendly name used in the toxic-pair table.
  8. ListAccountsForProvisionedPermissionSetAsync — only accounts where the permission set is actually provisioned, so we do not scan every account for every set.
  9. ListAccountAssignmentsAsync — who is assigned. PrincipalType is either USER or GROUP.
  10. ListGroupMembershipsAsync — expands a group into user IDs. MemberId is a union type; UserId is set for user members. Results are cached per group.
  11. Exit code 1 when violations exist — schedule it (for example as a Lambda or a pipeline job) and alert on failure. Keep the output as evidence for the periodic access review.

Security considerations

⚠ Learning shortcut — not for production

The lab runs the SoD checker from your laptop with a management-account profile. In production it runs on a schedule in the security-tooling account using a delegated-administrator role with read-only Identity Center permissions, writes its report to the log-archive bucket, and raises a finding in Security Hub when a violation is found.

⚠ Learning shortcut — not for production

The GitHub trust policy uses a public github.com repository subject. Production setups should also pin the token to your GitHub organisation using GitHub's customisable subject claims or the repository_owner_id claim where supported ⚠ VERIFY claim availability, protect the production environment with required reviewers who are not the author, and restrict deployments to the main branch.

  • The IdP is now your crown jewel. Whoever can add someone to aws-payments-developers in Entra can grant AWS access. Entra group management needs its own SoD, MFA and logging; include it in your threat model.
  • MFA happens in the IdP. With an external IdP, Identity Center's own MFA settings do not apply; enforce phishing-resistant MFA with Entra conditional access.
  • SCIM token hygiene. The SCIM bearer token can create users in Identity Center. Store it in a vault, limit who can read it, rotate before expiry, and alert on provisioning failures (otherwise leavers stop being removed).
  • Pipelines are privileged identities. The deployer role should have exactly what the CDK deployment needs (often the CDK bootstrap roles only), a 1-hour session, and the sub restricted to an approved environment.
  • Break-glass. Keep an emergency path that does not depend on Entra (for example, an IAM role assumable from a sealed management-account credential with hardware MFA). Alert on every use and review it.
  • Shared responsibility. AWS operates Identity Center and STS securely (security of the cloud). Designing the SoD matrix, keeping the IdP secure, reviewing access and proving it to auditors are Harbourline's responsibilities (security in the cloud). This design supports but does not by itself satisfy PCI DSS, UK GDPR or any supervisory expectation — your compliance and internal-audit functions must review it.

Banking use case

Harbourline's quarterly user access review used to be a spreadsheet exercise. Now:

  1. HR changes in Workday flow to Entra ID; Entra groups (aws-payments-developers, aws-crypto-custodians, …) drive SCIM provisioning into Identity Center within minutes.
  2. The SoD checker runs nightly. In week 3 it flags that an engineer moved from payments development to release management but was never removed from aws-payments-developers — a classic mover problem. The Entra group owner removes the membership and the next run is clean.
  3. For a production release, the developer opens a pull request, a second developer approves it, the change advisory board member approves the production environment in GitHub, and only then does GitHub obtain credentials for hl-payments-deployer via OIDC. CloudTrail shows AssumeRoleWithWebIdentity with the subject repo:harbourline/payments-api:environment:production; GitHub's deployment log shows who approved. Together they are the evidence trail internal audit samples.
  4. When the card scheme's assessor asks "who can change the encryption keys protecting card data?", the answer is the KeyAdministrator permission set, held by the two members of aws-crypto-custodians, who cannot decrypt — and the SCP shows nobody else can change key policies.

Common mistakes

  • Assigning permission sets to individual users → leavers keep access when the HR process only updates groups → assign groups only.
  • Using nested groups in Entra for AWS access → members of nested groups are not provisioned → use flat or dynamic groups for AWS assignments.
  • GitHub trust policy with sub = repo:org/* → any repo (and any branch) in the organisation can deploy to prod → scope to repository and environment.
  • Forgetting id-token: write in the workflow → Could not load credentials / no OIDC token → add the permission at job or workflow level.
  • Letting the pipeline role administer IAM freely → pipeline compromise equals account compromise → give it CDK deploy roles only, with boundaries on roles it creates.
  • One "Admin" permission set for everyone on the platform team → SoD impossible to demonstrate → split by duty as in the table.
  • No break-glass that works when Entra is down → incident response blocked during an IdP outage → test the break-glass path twice a year.

Troubleshooting

SymptomLikely causeFix
Entra sign-in works but the AWS access portal shows no accountsGroup not assigned to any account/permission set, or user not provisionedCheck Identity Center Users (Created by = SCIM) and assignments
User exists in Entra but not in Identity CenterProvisioning not started, user not in an assigned group, nested group, or SCIM errorEntra Provisioning logs; CloudTrail CreateUser errors in Identity Center
SCIM error "list attributes only allow single item"Multiple phone numbers or similar multi-valued attributesRemove duplicate values or attribute mappings
Not authorized to perform sts:AssumeRoleWithWebIdentitysub or aud in trust policy does not match the tokenPrint the token claims in the job (safely), compare with the trust policy exactly
IAM rejects the GitHub trust policy on savesub condition missing or only a wildcardSpecify org/repo (and environment or branch)
ABAC policy never matchesAttribute not enabled in Identity Center, or claim name/namespace wrongEnable Attributes for access control; claim https://aws.amazon.com/SAML/Attributes/AccessControl:Department
SoD checker returns AccessDeniedExceptionProfile is not in the management/delegated admin account or lacks identitystore:List*Use the correct account and a read-only permission set
SCP blocks the pipelineCDK uses the bootstrap cfn-exec role, not the role you allowedAdd the CDK role pattern to the exception list

Cost and cleanup

IAM Identity Center, IAM OIDC providers, STS, permission sets and the SoD checker's API calls have no charge. GitHub Actions minutes are free for public repositories and within the free allowance for private ones. AWS Directory Service (AD Connector or AWS Managed Microsoft AD) is billed hourly — do not create it in the lab; treat the AD option as design-only.

# Delete the GitHub deployer role and OIDC provider (workload account).
aws iam delete-role --role-name hl-m05-github-deployer --profile learn-sandbox
aws iam delete-open-id-connect-provider --profile learn-sandbox \
  --open-id-connect-provider-arn arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com

# Remove lab permission sets (management account): delete assignments first.
aws sso-admin delete-account-assignment --instance-arn "$INSTANCE_ARN" \
  --target-id 111122223333 --target-type AWS_ACCOUNT \
  --permission-set-arn arn:aws:sso:::permissionSet/ssoins-1111222233334444/ps-aaaabbbbccccdddd \
  --principal-type GROUP --principal-id 9a1b2c3d-1111-2222-3333-444455556666 --profile learn-mgmt
aws sso-admin delete-permission-set --instance-arn "$INSTANCE_ARN" \
  --permission-set-arn arn:aws:sso:::permissionSet/ssoins-1111222233334444/ps-aaaabbbbccccdddd --profile learn-mgmt

# Detach and delete the SoD SCP if you attached it to a test OU.
# aws organizations detach-policy --policy-id p-examplesod1 --target-id ou-abcd-sandbox1 --profile learn-mgmt
# aws organizations delete-policy --policy-id p-examplesod1 --profile learn-mgmt

# Confirm nothing tagged for the lab remains.
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab \
  --query 'ResourceTagMappingList[].ResourceARN' --profile learn-sandbox

Exercises

  • 🟢 Guided: Create the hl-m05-github-deployer role with the environment-scoped trust policy in your sandbox, create a public test repository with the workflow above and a production environment requiring your own review, and run it. Find the AssumeRoleWithWebIdentity event in CloudTrail and note the sub value.
  • 🟡 Challenge: Write xUnit tests for SodRules.FindViolations (no AWS needed): one test with no conflicts, one with a direct conflict, one where the conflict exists only across different accounts (which must not be reported). Then add a rule that a person holding BreakGlass in any account is always reported.
  • 🔴 Live problem: Internal audit writes: "In the last quarter, 11 production changes were deployed outside the pipeline. Explain how and fix it." You find that the platform team still has an AdministratorAccess permission set on the production accounts "for emergencies". Propose the target design, a migration plan that does not block real emergencies, and the evidence you will give audit next quarter.

Assignment

Produce a one-page SoD matrix for Harbourline's payments platform (roles × duties, with "allowed / forbidden / requires second person") and a permission-sets.tf or CDK stack that implements it. Include the SCP that enforces "only the pipeline deploys", the GitHub OIDC trust policy, and a short ACCESS-REVIEW.md describing how the SoD checker output is reviewed and retained.

Solutions

Knowledge check

Interview questions

  • "How do you give engineers access to 60 AWS accounts using our Entra ID?" — Identity Center in the management account (or delegated admin) with Entra as external IdP: SAML for sign-in, SCIM for provisioning, Entra groups mapped to permission sets per account, MFA via conditional access, ABAC for team scoping, all as code.
  • "How does your pipeline authenticate to AWS?" — OIDC federation: GitHub issues a short-lived JWT; an IAM role trusts GitHub's issuer, restricted by aud and sub (repository + protected environment); no stored keys; session one hour; least-privilege deploy permissions.
  • "Give an example of segregation of duties you have implemented in the cloud." — Developer, approver, pipeline, operator, key custodian, auditor and break-glass as separate permission sets; an SCP that only the pipeline role can deploy to prod; a KMS key policy separating admin from use; a nightly toxic-combination check; evidence from CloudTrail plus GitHub approvals.
  • "What happens to AWS access when Entra ID is down?" — New sign-ins fail; existing sessions continue until they expire. You need a tested break-glass path that does not depend on Entra, plus alerting on its use.

Certification practice

Completion checklist

  • I can explain SAML, OIDC and SCIM, and which one handles provisioning
  • I created a GitHub OIDC role scoped to a protected environment and found its CloudTrail event
  • I wrote down Harbourline's toxic permission-set pairs and why each is toxic
  • I understand which SCP statements enforce "only the pipeline deploys"
  • I ran the cleanup and confirmed no lab roles or permission sets remain

Key takeaways

  • Federate people through IAM Identity Center with the bank's IdP (SAML for sign-in, SCIM for provisioning); assign groups, never individuals.
  • Federate pipelines with OIDC, and bind the role to a protected environment so approval is a precondition for credentials.
  • Segregation of duties is a design: separate build, approve, deploy, operate, key custody, audit and break-glass — then enforce with SCPs and key policies and detect with automated reviews.
  • The IdP and Identity Center administration are now privileged systems; protect and audit them like production.
  • AWS provides the mechanisms; demonstrating effective SoD to auditors and regulators is the bank's responsibility.

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