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.
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
- Identity Center, MFA and STS — permission sets, AssumeRole, session tags
- Permission boundaries, SCPs, RCPs and resource policies
- IAM in depth
- Tools: AWS CLI v2 with the
learn-sandboxprofile and a management-account profile (learn-mgmt), .NET 10 SDK, a GitHub account (free) for the OIDC exercise. An Entra ID tenant is optional — the Entra steps are described so you can do them at work or in a free Microsoft developer tenant if you have one.
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
deployworkflow of repoharbourline/payments-apion branchmain". - 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
| Component | What it does | When to use it | Limitations and sharp edges |
|---|---|---|---|
| IAM Identity Center — external IdP | Uses Entra ID, Okta, etc. for sign-in (SAML 2.0) and SCIM for provisioning | The bank already has Entra ID with MFA and conditional access — the normal choice | One 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 Directory | Uses 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 AWS | Directory Service has hourly charges; network connectivity (VPN/Direct Connect) to domain controllers needed for AD Connector |
| IAM Identity Center directory | Users and groups stored in Identity Center itself | Labs, small organisations | A second set of identities to manage — avoid in a bank |
| IAM SAML identity provider | Per-account SAML trust directly to IAM roles | Legacy setups; special cases | You manage roles and SAML apps per account; Identity Center is preferred for people |
| IAM OIDC identity provider | Per-account trust for a JWT issuer (GitHub Actions, GitLab, Terraform Cloud, EKS) | Workloads and pipelines that need AWS credentials without keys | The 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 control | Passes IdP attributes as session tags (aws:PrincipalTag/…) | ABAC — one permission set serving many teams | Policies become data-dependent; test thoroughly and protect tags |
| Permission sets | Templates that become AWSReservedSSO_… roles in each assigned account | All human access | Session 1–12 hours; changes reprovision all assigned accounts |
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
| Entra ID enterprise app for SAML SSO | Entra ID gallery app AWS IAM Identity Center | One 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 scope | Permission set assigned to a group on an account | Assignments 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 federation | IAM 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 policies | Enforced in Entra before the SAML assertion is issued; AWS adds aws:SourceIp, aws:MultiFactorAuthPresent, SCPs | MFA for external-IdP users happens in the IdP, not in Identity Center |
| Entra ID dynamic groups by department | ABAC with AccessControl:Department → aws:PrincipalTag/Department | Tag-based policies, evaluated per request |
| Azure DevOps approvals and checks / branch policies | GitHub environment protection rules (required reviewers), CodePipeline manual approval | The 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 set | Assigned to (Entra group) | Accounts | Session | Can | Cannot |
|---|---|---|---|---|---|
PaymentsDeveloper | aws-payments-developers | payments-dev, payments-test | 8 h | Build and deploy in non-prod; create roles only with the app boundary | Anything in prod; touch KMS key policies |
PaymentsReadOnly | aws-payments-developers | payments-prod | 4 h | Read configuration, metrics, logs (masked) | Read data stores, secrets or decrypt; change anything |
PaymentsOperator | aws-payments-operations | payments-prod | 4 h | Restart/scale ECS services, run approved SSM Automation runbooks | Deploy code, change IAM, read secrets |
ReleaseApprover | aws-change-approvers | payments-prod (read only) | 1 h | Read change sets and pipeline state | Deploy; approve their own change (enforced in GitHub) |
KeyAdministrator | aws-crypto-custodians | security-tooling, payments-prod | 1 h | Create, rotate, disable, schedule deletion of keys; edit key policies | kms:Decrypt, kms:GenerateDataKey, read data |
SecurityAuditor | aws-internal-audit | all | 4 h | SecurityAudit + ViewOnlyAccess, read the log archive | Any write; any decrypt of customer data |
IdentityAdministrator | aws-identity-admins (2 people) | management | 1 h | Manage Identity Center assignments | Workload access; change SCPs (separate OrgPolicyAdministrator) |
BreakGlass | none (sealed procedure) | all | 1 h | Administrator | Use without alerting the SOC and a post-incident review |
Rules of thumb behind the table:
- Nobody deploys to production by hand. Only the pipeline role can.
- Key administrators cannot use keys; key users cannot administer them. This is enforced in the KMS key policy (see AWS KMS).
- 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.
- Auditors read, never write — and the log archive they read is in a separate account with Object Lock (see CloudTrail for banks).
- Toxic combinations are forbidden, for example
PaymentsDeveloperin prod, orKeyAdministrator+PaymentsOperatorfor 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, audiencests.amazonaws.com. - Role for GitHub: IAM → Roles → Create role → Web identity → provider
token.actions.githubusercontent.com, audiencests.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) orAssumeRoleWithSAML(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 textThe trust policy for the pipeline role:
{
"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:
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-identityInfrastructure as Code
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)
{
"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.
<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>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
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.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.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 twoGrantobjects and assert one violation).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.ListInstancesAsync— returns the Identity Center instance ARN and its IdentityStoreId (the directory where SCIM-provisioned users and groups live).ListPermissionSetsAsynchelper — the first of four manual pagination loops. Eachdo … while (token is not null)loop followsNextTokenuntil AWS stops returning one.?? []guards against SDK v4 returningnullfor empty lists.DescribePermissionSetAsync— converts an ARN such as…/ps-aaaabbbbccccddddinto the friendly name used in the toxic-pair table.ListAccountsForProvisionedPermissionSetAsync— only accounts where the permission set is actually provisioned, so we do not scan every account for every set.ListAccountAssignmentsAsync— who is assigned.PrincipalTypeis eitherUSERorGROUP.ListGroupMembershipsAsync— expands a group into user IDs.MemberIdis a union type;UserIdis set for user members. Results are cached per group.- Exit code
1when 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-developersin 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
subrestricted 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:
- HR changes in Workday flow to Entra ID; Entra groups (
aws-payments-developers,aws-crypto-custodians, …) drive SCIM provisioning into Identity Center within minutes. - 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. - For a production release, the developer opens a pull request, a second developer approves it, the change advisory board member approves the
productionenvironment in GitHub, and only then does GitHub obtain credentials forhl-payments-deployervia OIDC. CloudTrail showsAssumeRoleWithWebIdentitywith the subjectrepo:harbourline/payments-api:environment:production; GitHub's deployment log shows who approved. Together they are the evidence trail internal audit samples. - When the card scheme's assessor asks "who can change the encryption keys protecting card data?", the answer is the
KeyAdministratorpermission set, held by the two members ofaws-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: writein 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
| Symptom | Likely cause | Fix |
|---|---|---|
| Entra sign-in works but the AWS access portal shows no accounts | Group not assigned to any account/permission set, or user not provisioned | Check Identity Center Users (Created by = SCIM) and assignments |
| User exists in Entra but not in Identity Center | Provisioning not started, user not in an assigned group, nested group, or SCIM error | Entra Provisioning logs; CloudTrail CreateUser errors in Identity Center |
| SCIM error "list attributes only allow single item" | Multiple phone numbers or similar multi-valued attributes | Remove duplicate values or attribute mappings |
Not authorized to perform sts:AssumeRoleWithWebIdentity | sub or aud in trust policy does not match the token | Print the token claims in the job (safely), compare with the trust policy exactly |
| IAM rejects the GitHub trust policy on save | sub condition missing or only a wildcard | Specify org/repo (and environment or branch) |
| ABAC policy never matches | Attribute not enabled in Identity Center, or claim name/namespace wrong | Enable Attributes for access control; claim https://aws.amazon.com/SAML/Attributes/AccessControl:Department |
SoD checker returns AccessDeniedException | Profile 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 pipeline | CDK uses the bootstrap cfn-exec role, not the role you allowed | Add 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-sandboxExercises
- 🟢 Guided: Create the
hl-m05-github-deployerrole with the environment-scoped trust policy in your sandbox, create a public test repository with the workflow above and aproductionenvironment requiring your own review, and run it. Find theAssumeRoleWithWebIdentityevent in CloudTrail and note thesubvalue. - 🟡 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 holdingBreakGlassin 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
AdministratorAccesspermission 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
The job succeeds only after you approve the production environment. In CloudTrail (Event history, event name AssumeRoleWithWebIdentity), the event's userIdentity shows type: WebIdentityUser with the provider token.actions.githubusercontent.com, and the request parameters include the role ARN and session name gh-<run id>. The subject claim is repo:<you>/<repo>:environment:production. Why it matters: the AWS evidence (role assumed, when, by which repo and environment) links to the GitHub evidence (who approved), giving an end-to-end maker-checker trail without any stored secret.
using Harbourline.Security.SodChecker;
public class SodRulesTests
{
[Fact]
public void Reports_conflict_in_same_account()
{
var grants = new[]
{
new Grant("111122223333", "u-1", "PaymentsDeveloper"),
new Grant("111122223333", "u-1", "ReleaseApprover"),
};
Assert.Single(SodRules.FindViolations(grants));
}
[Fact]
public void Ignores_pairs_split_across_accounts()
{
var grants = new[]
{
new Grant("111122223333", "u-1", "PaymentsDeveloper"),
new Grant("444455556666", "u-1", "ReleaseApprover"),
};
Assert.Empty(SodRules.FindViolations(grants));
}
}For the break-glass rule, add a second method that returns every grant whose PermissionSet == "BreakGlass" regardless of pairs, and concatenate it with the pair violations. Why: break-glass should be assigned only during an incident, so any standing assignment is itself a finding. (Whether "developer in dev, approver in prod" is a violation is a policy decision — many banks treat any combination across the same system as toxic; document your choice.)
Target: remove standing AdministratorAccess from production; only the pipeline deploys (SCP OnlyPipelineDeploys); operators get PaymentsOperator with SSM Automation runbooks for routine actions; real emergencies use BreakGlass, which is assigned on request through an approved workflow (time-boxed, two approvers, SOC alerted by an EventBridge rule on its use). Migration: (1) run the SoD checker and CloudTrail queries to list who used the admin set and for what; (2) build runbooks for the top recurring "emergency" actions; (3) attach the SCP to one production account in monitor-by-CloudTrail mode via a test OU first; (4) remove the permission set; (5) run a break-glass drill. Evidence: CloudTrail showing deployments only by hl-payments-deployer, GitHub approval records, the SCP and its attachment history, the SoD checker reports, and break-glass usage tickets with post-incident reviews.
Knowledge check
Answer: SAML 2.0 handles authentication at sign-in: Entra signs an assertion saying who the user is (and optionally attributes). SCIM 2.0 handles provisioning: it creates, updates and deletes users and groups in Identity Center so that assignments can reference them. You need both for a fully automated joiner/mover/leaver process.
Answer: Because a job can only run in the production environment after the environment's protection rules (required reviewers, branch restrictions) pass. Binding the AWS role to environment:production makes the approval a precondition for getting credentials. A branch subject would let any workflow on that branch obtain credentials without approval.
Answer: Segregation of duties: the person controlling the key lifecycle should not also be able to read data protected by the key. Combining both would let one person decrypt customer data and then hide evidence by changing the key policy. Data access belongs to application roles; administration to custodians.
Answer: In Entra ID (through its MFA and conditional-access policies) before the SAML assertion is issued. Identity Center's built-in MFA settings apply only when Identity Center is the identity source.
Answer: (1) A direct user assignment in Identity Center that HR-driven group changes do not touch — prevent by assigning groups only. (2) Membership in a nested Entra group that SCIM does not process, or a stale group membership — prevent with flat groups, group owners attesting membership, and the automated SoD/access review.
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
audandsub(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
A bank's GitHub Actions workflows deploy to AWS using an IAM user access key stored as a repository secret. A security review requires removing long-term credentials and ensuring only approved production deployments can obtain credentials. Which solution meets these requirements?
A. Rotate the access key every 30 days using Secrets Manager.
B. Create an IAM OIDC identity provider for GitHub and a role whose trust policy requires token.actions.githubusercontent.com:aud = sts.amazonaws.com and token.actions.githubusercontent.com:sub = the repository's production environment; protect the environment with required reviewers.
C. Store the access key in AWS Systems Manager Parameter Store and fetch it during the workflow.
D. Create an IAM role that trusts token.actions.githubusercontent.com with sub = repo:*.
Answer: B. It removes long-term keys and binds credentials to the approved environment. A and C still use a long-term key. D lets any repository on GitHub assume the role (and IAM rejects a wildcard-only sub for GitHub).
A company uses Microsoft Entra ID as the external identity provider for IAM Identity Center. When employees leave, their AWS access must be removed automatically. What should the security engineer configure?
A. A Lambda function that deletes IAM users nightly.
B. SCIM automatic provisioning from Entra ID to IAM Identity Center, with AWS access granted only through group assignments.
C. Session duration of 1 hour on every permission set.
D. An SCP that denies access to users without an Employee tag.
Answer: B. SCIM deprovisions users and group memberships in Identity Center when they are removed in Entra, and group-only assignments mean no access remains. A is irrelevant (Identity Center users are not IAM users). C limits session length but does not remove access. D depends on tags that are not removed automatically and SCPs do not see Identity Center user attributes unless passed as session tags.
An auditor requires that the team that administers KMS keys protecting cardholder data cannot use those keys to decrypt data, and that this restriction cannot be bypassed by account administrators in member accounts. Which combination achieves this? (Choose TWO.)
A. A KMS key policy that grants key-administration actions to the KeyAdministrator role and cryptographic actions only to application roles.
B. An SCP on the OU that denies kms:Decrypt to the KeyAdministrator role pattern.
C. Enable automatic key rotation.
D. Use AWS managed keys instead of customer managed keys.
E. Store the keys in Secrets Manager.
Answer: A and B. The key policy separates admin from use; the SCP ensures a member-account administrator cannot grant kms:Decrypt to the key-admin role via IAM. C is good practice but unrelated to SoD. D removes the bank's control over key policies. E is not how KMS keys work.
A company has 3,000 employees in on-premises Active Directory and no cloud identity provider. It wants single sign-on to 25 AWS accounts using existing AD credentials, without synchronising password hashes to the cloud. What should a solutions architect recommend?
A. Create IAM users in each account with the same usernames as AD. B. Use IAM Identity Center with AD Connector to the on-premises Active Directory as the identity source. C. Use Amazon Cognito user pools with AD users imported. D. Configure an IAM SAML provider in each account pointing to the AD domain controllers.
Answer: B. AD Connector proxies authentication to on-premises AD without storing identities in AWS, and Identity Center provides multi-account SSO. A creates duplicate long-lived identities. C is for customer-facing apps. D requires a SAML IdP (AD domain controllers alone are not one) and per-account management.
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.
Permission boundaries, SCPs, RCPs and resource-based policies
Delegate IAM safely with permission boundaries, set organisation-wide guardrails with SCPs and RCPs, and use resource-based policies to build a data perimeter and controlled cross-account access.
Labs 5.1 and 5.2: IAM policy puzzles, permission boundaries and an offline policy linter
Predict allow or deny for ten IAM evaluation puzzles, confirm each with an offline evaluator and the IAM policy simulator, lint a deliberately bad policy, and design a permission boundary that lets a developer create roles without escalating privileges.