Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(iam): generate and read the Organizations access report (#5467)

Priamo Germosen4e769484df86
diff --git a/docs/services/iam.md b/docs/services/iam.md
index d96f10e2d3..a5beba9cf5 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -350,6 +350,8 @@ read; the comparison is driven entirely by the policy's own condition operator (
| GetServiceLastAccessedDetails | Returns the job's status and its service-access report. |
| GetServiceLastAccessedDetailsWithEntities | Returns the job's status and the entities that used a given service. |
| ListPoliciesGrantingServiceAccess | Lists the policies that let an IAM identity access each requested service. |
+| GenerateOrganizationsAccessReport | Starts a report of the services the SCPs along an Organizations entity path leave reachable, and returns its job ID. |
+| GetOrganizationsAccessReport | Returns the job's status and its report. |
Floci does not record service access. Nothing populates a principal's usage history, and
`GetAccessKeyLastUsed` already answers with AWS's documented "never used" shape rather than
@@ -420,6 +422,73 @@ resource-based policies, ACLs, Organizations policies and trust policies are not
Resources and conditions are not evaluated either: the question is which policies could grant the
service at all, not whether one specific call would be authorized.
+The Organizations access report is the same job shape over a different question. Instead of one
+entity's permissions policies it reports the services the service control policies along an
+Organizations entity path leave reachable, and it is answered from Floci's own Organizations tree:
+the entity path names the organization, its root and the OUs or account below, and the SCPs attached
+to each of those are read and evaluated. Only SCP logic applies, which the reference is explicit
+about, so identity policies, resource policies, ACLs, permissions boundaries and trust policies play
+no part. The entity path has to be a path the organization actually has: the segments below the root
+name a chain of parent and child, so the path is held to the one Organizations reports for its last
+node, and a path assembled from two branches, or one that skips an OU, fails the job rather than
+reporting the policies of a chain that does not exist.
+
+Attached SCPs are a union within one level and the levels are intersected, so a service survives only
+where every level allows it. That question cannot be answered a namespace at a time, because a
+service is reachable only while some action in it survives the whole chain: two levels allowing
+single disjoint actions, `s3:GetObject` under `s3:PutObject`, leave no S3 action at all, and a `Deny`
+on the one action a level allows leaves none either. What a namespace-wide reading got right stays
+right: an SCP denying `s3:DeleteBucket` alone keeps S3 on the list, because every other S3 action is
+still reachable, and a `Deny` that carries a `Condition` or names particular resources closes nothing
+at all, since the region-restricting deny on `*` that most organizations carry, and a deny scoped to
+one bucket, both leave the service reachable by every request they do not cover. The survivors are
+found by probing the chain with the actions the policies themselves name plus one stand-in action per
+wildcard, which is exact for the patterns policies are written with; a wildcard that is not a
+trailing one, as in `s3:*Object`, cannot be probed that way and leaves the service on the list rather
+than off it.
+
+The management account is not limited by SCPs, so its report lists every service and an
+`OrganizationsPolicyId` passed with it is ignored, as the reference says. Passing that ID otherwise
+narrows the report to the one SCP named, and it has to name one: Organizations keeps tag, backup,
+chatbot and opt-out policies in the same ID space, none of them carries statements, and evaluating
+one as a ceiling would read as a level that constrains nothing and report every service there is.
+
+Every service in the report is one principals are allowed but never reached, since Floci records no
+access, and that is the shape the reference's own example gives such a service: a namespace and a
+zero count, with no region, entity path or last-authenticated time. `NumberOfServicesNotAccessed`
+therefore equals `NumberOfServicesAccessible`. `ServiceName` carries a display name
+("Amazon S3") that Floci has no mapping for, so the namespace stands in for it, as on the
+last-accessed reader. `SortKey` is validated against its four values; the namespace keys sort the
+list and the two time keys leave it in namespace order, because ordering on a timestamp no entry
+carries would be ordering on nothing.
+
+A caller who is not the management account gets `AccessDenied` 403. Neither operation models a code
+for that, but a per-action error list is additive: the reference's common error types "that this AWS
+service may return" apply to every action and include the 403 permission denial, and the IAM user
+guide names the code for a denied IAM action outright, in the `AddRoleToInstanceProfile`
+troubleshooting entry. The common error page spells it `AccessDeniedException` while the user guide
+and the rest of Floci's IAM and STS surface spell it `AccessDenied`; the latter is used here, for
+consistency with the surface a caller is already on.
+
+Three things about this pair are inferences, and they are the same inference three times. The
+generator models no error for an entity path that is well-formed but resolves to nothing, so a path
+naming another organization, an entity outside this one, or a chain the organization does not have,
+produces a `FAILED` job carrying `ErrorDetails` instead. Nor does it model one for the prerequisite
+the reference states, that SCPs be enabled for the organization root, so an organization without them
+produces a `FAILED` job too, carrying `PolicyTypeNotEnabled`. Nor one for an `OrganizationsPolicyId`
+that names a policy of some other type, which fails the job carrying Organizations'
+`InvalidInputException`. All three are read off the shape of the API rather than off a sentence: AWS
+publishes both `FAILED` and `ErrorDetails` on this reader, for failures the generator does not
+report synchronously, and the alternatives are all worse. Letting Organizations' own error escape
+unchanged would put another service's code on an IAM operation, a `COMPLETED` job with an empty list
+cannot be told apart from an organization that reaches no services, and `ValidationError` is for a
+shape violation, which a resolvable-looking path, a disabled policy type and an existing policy of
+the wrong type are not.
+
+The generator's only modeled error, `ReportGenerationLimitExceeded`, reports concurrent generations
+for the account and stays unreachable here: a job is complete the moment it is created, so two can
+never overlap.
+
### Multi-Factor Authentication
| Action | Description |
@@ -1065,9 +1134,13 @@ format of each type. `make iam-action-resources-check` gates its shape offline o
request and `make iam-action-resources-verify` checks every claim in it against AWS weekly, so a
type that drifts from what AWS publishes fails in CI rather than authorizing against the wrong
resource. What stays in Java is the half that is Floci's: the request parameter each type's name
-arrives in, the creates, the actions whose request carries an ARN, and the resource types that
-belong only to actions Floci does not dispatch. `IamActionResourcesTest` checks the one against
-the other, so a regeneration that introduces a resource type nothing resolves fails a test naming
+arrives in, the creates, the actions whose request carries an ARN, the four whose request names
+the resource some other way, and the resource types that belong only to actions Floci does not
+dispatch. `GenerateOrganizationsAccessReport` is one of the four: the reference spells its type as
+`access-report/${EntityPath}`, so the Organizations entity path goes into the ARN whole, its
+slashes being the organization's tree rather than an IAM path. `IamActionResourcesTest` checks the
+one against the other, so a regeneration that introduces a resource type nothing resolves fails a
+test naming
it rather than quietly putting that action back on `*`.
The nineteen user actions whose `UserName` the model marks optional, `GetUser`, `ListAccessKeys` and
diff --git a/docs/services/index.md b/docs/services/index.md
index 69467179d3..c5bd2a89d1 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -22,7 +22,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 79 |
| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane |
-| [IAM](iam.md) | `POST /` with `Action=` param | Query | 164 |
+| [IAM](iam.md) | `POST /` with `Action=` param | Query | 166 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 |
| [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 |
| [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 |
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index e785493afe..bc45926c37 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -113,6 +113,7 @@ public class AwsQueryController {
"TagSAMLProvider", "UntagSAMLProvider", "ListSAMLProviderTags",
"GenerateServiceLastAccessedDetails", "GetServiceLastAccessedDetails",
"GetServiceLastAccessedDetailsWithEntities", "ListPoliciesGrantingServiceAccess",
+ "GenerateOrganizationsAccessReport", "GetOrganizationsAccessReport",
"UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",
"DeleteServerCertificate", "ListServerCertificates",
"TagServerCertificate", "UntagServerCertificate", "ListServerCertificateTags",
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamJobStore.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamJobStore.java
new file mode 100644
index 0000000000..11a99055f6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamJobStore.java
@@ -0,0 +1,51 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+
+import java.util.Optional;
+import java.util.function.Function;
+
+/**
+ * The job registry IAM's report generators keep: Access Advisor's service last accessed jobs and
+ * the Organizations access reports.
+ *
+ * <p>Both hand the caller a job id, store the report the job produced rather than recomputing it,
+ * and answer {@code NoSuchEntity} for an id they do not hold, so the reading, the writing and the
+ * refusal are the same for both and only what a job carries differs. Jobs are scoped to the
+ * account that generated them, so one account's id is never answerable by another.
+ */
+final class IamJobStore<T> {
+
+ private final StorageBackend<String, T> jobs;
+ private final Function<T, String> jobId;
+
+ IamJobStore(StorageBackend<String, T> jobs, Function<T, String> jobId) {
+ this.jobs = jobs;
+ this.jobId = jobId;
+ }
+
+ T get(String accountId, String id) {
+ return find(accountId, id).orElseThrow(() -> new AwsException("NoSuchEntity",
+ "The job ID " + id + " cannot be found.", 404));
+ }
+
+ Optional<T> find(String accountId, String id) {
+ if (id == null || id.isBlank()) {
+ return Optional.empty();
+ }
+ if (jobs instanceof AccountAwareStorageBackend<T> aware) {
+ return aware.getForAccount(accountId, id);
+ }
+ return jobs.get(id);
+ }
+
+ void put(String accountId, T job) {
+ if (jobs instanceof AccountAwareStorageBackend<T> aware) {
+ aware.putForAccount(accountId, jobId.apply(job), job);
+ } else {
+ jobs.put(jobId.apply(job), job);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
index 8401c30d68..56a2e4c792 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
@@ -22,6 +22,7 @@ import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -59,6 +60,14 @@ public class IamPolicyEvaluator {
private static final Pattern ROOT_PRINCIPAL_ARN =
Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::\\d{12}:root");
+ /**
+ * The verb of the stand-in action a wildcard is probed with in
+ * {@link #servicesAllowedByScpLevels}. Any string no real action spells out will do, since it
+ * stands for "some other action this pattern covers". Lowercase, because action patterns are
+ * lowercased at parse time and matched case-sensitively from there on.
+ */
+ private static final String ANY_ACTION = "flociprobedaction";
+
public enum Decision { ALLOW, DENY }
public enum ResourcePolicyDecision {
@@ -524,6 +533,194 @@ public class IamPolicyEvaluator {
return false;
}
+ /**
+ * The service namespaces an SCP chain leaves reachable, backing the service list in
+ * {@code GetOrganizationsAccessReport}.
+ *
+ * <p>Level conventions are {@link #scpAllows}'s. A {@code null} chain means SCPs do not apply
+ * and every published namespace is reachable, which is the management account's case. A level
+ * with no document constrains nothing, since AWS keeps FullAWSAccess attached to every target,
+ * and a level carrying a document that fails to parse leaves nothing reachable, because the
+ * ceiling cannot tell what an unreadable guardrail would have said.
+ *
+ * <p>Attached SCPs are a union within a level and the levels are intersected. The question is
+ * service-level, but it cannot be answered a namespace at a time: a service is reachable only
+ * while some action in it survives the whole chain. Two levels allowing single disjoint
+ * actions, {@code s3:GetObject} under {@code s3:PutObject}, leave no S3 action at all, and a
+ * {@code Deny} on the one action a level allows leaves none either, so neither reports S3.
+ * What a namespace-wide reading got right stays right: an SCP denying {@code s3:DeleteBucket}
+ * alone keeps S3 on the list, because every other S3 action is still reachable.
+ *
+ * <p>This is not {@link #scpAllows} asked once per namespace. That question needs a concrete
+ * action, and a request action of {@code s3:*} would not match a statement naming
+ * {@code s3:GetObject}, because a pattern globs against a request value and never the other
+ * way round. The survivors are found by probing instead, with the actions the policies
+ * themselves name and one stand-in action per wildcard.
+ */
+ public List<String> servicesAllowedByScpLevels(List<List<String>> scpLevels) {
+ if (scpLevels == null) {
+ return List.copyOf(new TreeSet<>(AwsServiceNamespaces.all()));
+ }
+ Set<String> reachable = null;
+ List<List<PolicyStatement>> allowLevels = new ArrayList<>();
+ List<PolicyStatement> denials = new ArrayList<>();
+ for (List<String> level : scpLevels) {
+ ParsedDocuments parsed = parseAllTracked(level);
+ if (parsed.anyFailed()) {
+ return List.of();
+ }
+ if (parsed.statements().isEmpty()) {
+ continue;
+ }
+ Set<String> levelAllows = new TreeSet<>(servicesGrantedBy(level));
+ if (reachable == null) {
+ reachable = levelAllows;
+ } else {
+ reachable.retainAll(levelAllows);
+ }
+ List<PolicyStatement> allows = new ArrayList<>();
+ for (PolicyStatement stmt : parsed.statements()) {
+ if (stmt.isDeny()) {
+ denials.add(stmt);
+ } else {
+ allows.add(stmt);
+ }
+ }
+ allowLevels.add(allows);
+ }
+ if (reachable == null) {
+ return List.copyOf(new TreeSet<>(AwsServiceNamespaces.all()));
+ }
+ // The namespace pass above is the cheap half of the answer and only ever too generous, so
+ // what survives it is then asked the question that needs an action.
+ reachable.removeIf(namespace -> !anyActionSurvives(allowLevels, denials, namespace));
+ return List.copyOf(reachable);
+ }
+
+ /**
+ * Whether any action in the namespace is allowed by every level and denied by none.
+ *
+ * <p>The actions worth asking about are the ones the policies name, plus a stand-in for each
+ * wildcard: {@code s3:Get*} is probed as an action starting with {@code Get} that nothing else
+ * spells out, which is what makes a deny on {@code s3:GetObject} leave the service reachable
+ * while a deny on {@code s3:Get*} does not. A pattern whose wildcard is not its last character
+ * cannot be probed this way, since the stand-in for {@code s3:*Object} misses the
+ * {@code s3:GetObject} that {@code s3:Get*} would allow. Such a pattern leaves the namespace
+ * on the list rather than off it, keeping the imprecision on the side the namespace pass was
+ * already on.
+ */
+ private boolean anyActionSurvives(List<List<PolicyStatement>> allowLevels,
+ List<PolicyStatement> denials, String serviceNamespace) {
+ Set<String> probes = new LinkedHashSet<>();
+ probes.add(serviceNamespace + ":" + ANY_ACTION);
+ boolean decidable = true;
+ for (List<PolicyStatement> level : allowLevels) {
+ for (PolicyStatement stmt : level) {
+ decidable = collectProbes(stmt.getActions(), serviceNamespace, probes) && decidable;
+ decidable = collectProbes(stmt.getNotActions(), serviceNamespace, probes) && decidable;
+ }
+ }
+ for (PolicyStatement stmt : denials) {
+ decidable = collectProbes(stmt.getActions(), serviceNamespace, probes) && decidable;
+ decidable = collectProbes(stmt.getNotActions(), serviceNamespace, probes) && decidable;
+ }
+ for (String action : probes) {
+ if (allowedByEveryLevel(allowLevels, action) && !deniedByAny(denials, action)) {
+ return true;
+ }
+ }
+ return !decidable;
+ }
+
+ /**
+ * Adds one probe action per pattern that reaches the namespace, and reports whether every
+ * pattern seen was one a probe decides exactly.
+ */
+ private static boolean collectProbes(List<String> patterns, String serviceNamespace,
+ Set<String> probes) {
+ if (patterns == null) {
+ return true;
+ }
+ boolean decidable = true;
+ for (String pattern : patterns) {
+ if (!actionPatternReaches(pattern, serviceNamespace)) {
+ continue;
+ }
+ int colon = pattern.indexOf(':');
+ String verb = colon < 0 ? "*" : pattern.substring(colon + 1);
+ int star = verb.indexOf('*');
+ if (verb.indexOf('?') >= 0 || (star >= 0 && star != verb.length() - 1)) {
+ decidable = false;
+ }
+ probes.add(serviceNamespace + ":" + verb.replace("*", ANY_ACTION).replace("?", "a"));
+ }
+ return decidable;
+ }
+
+ /** Whether one action clears the ceiling at every level, each level being a union. */
+ private boolean allowedByEveryLevel(List<List<PolicyStatement>> allowLevels, String action) {
+ for (List<PolicyStatement> level : allowLevels) {
+ boolean allowed = false;
+ for (PolicyStatement stmt : level) {
+ if (permits(stmt, action)) {
+ allowed = true;
+ break;
+ }
+ }
+ if (!allowed) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Whether an {@code Allow} covers the action. Resources and conditions are left out of the
+ * allow side, as everywhere else in this answer: narrowing a grant to one bucket still leaves
+ * the service reachable.
+ */
+ private boolean permits(PolicyStatement stmt, String action) {
+ if (stmt.getNotActions() != null) {
+ return !matchesAny(stmt.getNotActions(), action);
+ }
+ return stmt.getActions() != null && matchesAny(stmt.getActions(), action);
+ }
+
+ /**
+ * Whether a {@code Deny} that bites on every request covers the action. A deny carrying a
+ * {@code Condition}, or scoped to particular resources, is not one of those: the
+ * region-restricting {@code Deny} on {@code *} that most organizations carry would otherwise
+ * empty the report, and a deny on one bucket would drop S3 while every other bucket is still
+ * there.
+ */
+ private boolean deniedByAny(List<PolicyStatement> denials, String action) {
+ for (PolicyStatement stmt : denials) {
+ if (!deniesEveryRequest(stmt)) {
+ continue;
+ }
+ if (stmt.getNotActions() != null) {
+ if (!matchesAny(stmt.getNotActions(), action)) {
+ return true;
+ }
+ } else if (stmt.getActions() != null && matchesAny(stmt.getActions(), action)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** Whether a {@code Deny} applies to every request, rather than to some of them. */
+ private static boolean deniesEveryRequest(PolicyStatement stmt) {
+ if (stmt.getConditions() != null && !stmt.getConditions().isEmpty()) {
+ return false;
+ }
+ if (stmt.getNotResources() != null && !stmt.getNotResources().isEmpty()) {
+ return false;
+ }
+ List<String> resources = stmt.getResources();
+ return resources == null || resources.isEmpty() || resources.contains("*");
+ }
+
/** Appends the key name inside every {@code ${key}} policy variable found in {@code values}. */
private void collectPolicyVariableKeys(List<String> values, List<String> keys) {
if (values == null) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
index 09b4514b5a..5c3d200f43 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import io.github.hectorvent.floci.services.iam.model.LoginProfile;
import io.github.hectorvent.floci.services.iam.model.OpenIDConnectProvider;
+import io.github.hectorvent.floci.services.iam.model.OrganizationsAccessReportJob;
import io.github.hectorvent.floci.services.iam.model.OutboundWebIdentityFederation;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
@@ -35,6 +36,7 @@ import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Base64;
+import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
@@ -58,6 +60,10 @@ public class IamQueryHandler {
/** {@code MaxItems} on the last-accessed readers: "defaults to 100", valid range 1 to 1000. */
private static final int DEFAULT_MAX_ITEMS = 100;
private static final int MAX_MAX_ITEMS = 1000;
+ /** {@code sortKeyType} on {@code GetOrganizationsAccessReport}. */
+ private static final Set<String> SORT_KEYS = Set.of("SERVICE_NAMESPACE_ASCENDING",
+ "SERVICE_NAMESPACE_DESCENDING", "LAST_AUTHENTICATED_TIME_ASCENDING",
+ "LAST_AUTHENTICATED_TIME_DESCENDING");
/** {@code serviceNamespaceListType}: minimum 1 item, maximum 200. */
private static final int MAX_SERVICE_NAMESPACES = 200;
private static final int MAX_TAG_LIST_MEMBERS = 50;
@@ -71,6 +77,7 @@ public class IamQueryHandler {
private final AccountResolver accountResolver;
private final SAMLProviderService samlProviderService;
private final ServiceLastAccessedService serviceLastAccessedService;
+ private final OrganizationsAccessReportService organizationsAccessReportService;
private final RegionResolver regionResolver;
private final Instance<ServerCertificateReferenceProvider> serverCertificateReferenceProviders;
@@ -78,6 +85,7 @@ public class IamQueryHandler {
public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator,
AccountResolver accountResolver, SAMLProviderService samlProviderService,
ServiceLastAccessedService serviceLastAccessedService,
+ OrganizationsAccessReportService organizationsAccessReportService,
RegionResolver regionResolver,
Instance<ServerCertificateReferenceProvider> serverCertificateReferenceProviders) {
this.iamService = iamService;
@@ -85,6 +93,7 @@ public class IamQueryHandler {
this.accountResolver = accountResolver;
this.samlProviderService = samlProviderService;
this.serviceLastAccessedService = serviceLastAccessedService;
+ this.organizationsAccessReportService = organizationsAccessReportService;
this.regionResolver = regionResolver;
this.serverCertificateReferenceProviders = serverCertificateReferenceProviders;
}
@@ -301,6 +310,10 @@ public class IamQueryHandler {
case "GetServiceLastAccessedDetails" -> handleGetServiceLastAccessedDetails(params, authorization);
case "GetServiceLastAccessedDetailsWithEntities" ->
handleGetServiceLastAccessedDetailsWithEntities(params, authorization);
+ case "GenerateOrganizationsAccessReport" ->
+ handleGenerateOrganizationsAccessReport(params, authorization);
+ case "GetOrganizationsAccessReport" ->
+ handleGetOrganizationsAccessReport(params, authorization);
case "ListPoliciesGrantingServiceAccess" -> handleListPoliciesGrantingServiceAccess(params, authorization);
default -> AwsQueryResponse.error("UnsupportedOperation",
@@ -2186,6 +2199,115 @@ public class IamQueryHandler {
xml.build())).build();
}
+ /**
+ * Generates the Organizations access report now and returns its job id, mirroring the Access
+ * Advisor generator above. The report is the services the SCPs along the entity path leave
+ * reachable; the reference is explicit that service last accessed data "only applies SCP
+ * logic", so no identity policy, resource policy or permissions boundary enters it.
+ *
+ * <p>{@code ReportGenerationLimitExceeded} is the operation's only modeled error and stays
+ * unreachable here: it reports concurrent generations for the account, and a Floci job is
+ * complete the moment it is created, so two can never overlap.
+ */
+ private Response handleGenerateOrganizationsAccessReport(MultivaluedMap<String, String> params,
+ String authorization) {
+ OrganizationsAccessReportJob job = organizationsAccessReportService.generate(
+ accountResolver.resolve(authorization), requireParam(params, "EntityPath"),
+ params.getFirst("OrganizationsPolicyId"));
+ return Response.ok(AwsQueryResponse.envelope("GenerateOrganizationsAccessReport",
+ AwsNamespaces.IAM,
+ new XmlBuilder().elem("JobId", job.getJobId()).build())).build();
+ }
+
+ /**
+ * Retrieves a generated report. AWS lists a service account principals are allowed to reach
+ * even when it was never used, and its own example gives such a service as a namespace and a
+ * zero count with no region, entity path or last-authenticated time. Floci records no access,
+ * so every entry takes that shape and {@code NumberOfServicesNotAccessed} equals
+ * {@code NumberOfServicesAccessible}.
+ *
+ * <p>A job that failed carries {@code ErrorDetails} and no report, which is where an entity
+ * path naming something outside the organization lands, the operation publishing no
+ * synchronous error for one.
+ */
+ private Response handleGetOrganizationsAccessReport(MultivaluedMap<String, String> params,
+ String authorization) {
+ String jobId = requireParam(params, "JobId");
+ // Read before the lookup, because a value outside the enum is a bad request whether or not
+ // the job exists: validating it after would answer NoSuchEntity for a request AWS rejects.
+ String sortKey = validatedSortKey(params);
+ OrganizationsAccessReportJob job = organizationsAccessReportService.get(
+ accountResolver.resolve(authorization), jobId);
+ XmlBuilder xml = new XmlBuilder()
+ .elem("JobStatus", job.getJobStatus())
+ .elem("JobCreationDate", isoDate(job.getJobCreationDate()))
+ .elem("JobCompletionDate", isoDate(job.getJobCompletionDate()));
+ if (job.getErrorCode() != null) {
+ return Response.ok(AwsQueryResponse.envelope("GetOrganizationsAccessReport",
+ AwsNamespaces.IAM,
+ xml.elem("IsTruncated", false)
+ .start("ErrorDetails")
+ .elem("Message", job.getErrorMessage())
+ .elem("Code", job.getErrorCode())
+ .end("ErrorDetails")
+ .build())).build();
+ }
+ List<String> namespaces = sortedByKey(job.getServiceNamespaces(), sortKey);
+ Page<String> page = paginate(namespaces, params);
+ xml.elem("NumberOfServicesAccessible", namespaces.size())
+ .elem("NumberOfServicesNotAccessed", namespaces.size())
+ .start("AccessDetails");
+ for (String namespace : page.items()) {
+ // ServiceName carries a display name ("Amazon S3") that Floci has no mapping for, so
+ // the namespace stands in for it, as it does on the last-accessed reader.
+ xml.start("member")
+ .elem("ServiceName", namespace)
+ .elem("ServiceNamespace", namespace)
+ .elem("TotalAuthenticatedEntities", 0)
+ .end("member");
+ }
+ xml.end("AccessDetails").elem("IsTruncated", page.truncated());
+ if (page.marker() != null) {
+ xml.elem("Marker", page.marker());
+ }
+ return Response.ok(AwsQueryResponse.envelope("GetOrganizationsAccessReport",
+ AwsNamespaces.IAM, xml.build())).build();
+ }
+
+ /**
+ * {@code SortKey} if the request carries one the enum permits, null if it carries none. A
+ * request that carries the member is held to the enum whatever it carries: an empty value is
+ * not one of the four, and reading it as an absent member would answer a default-ordered
+ * report to a request AWS rejects.
+ */
+ private static String validatedSortKey(MultivaluedMap<String, String> params) {
+ String sortKey = params.getFirst("SortKey");
+ if (sortKey == null) {
+ return null;
+ }
+ if (!SORT_KEYS.contains(sortKey)) {
+ throw validationError(sortKey, "sortKey", "Member must satisfy enum value set: "
+ + "[SERVICE_NAMESPACE_ASCENDING, SERVICE_NAMESPACE_DESCENDING, "
+ + "LAST_AUTHENTICATED_TIME_ASCENDING, LAST_AUTHENTICATED_TIME_DESCENDING]");
+ }
+ return sortKey;
+ }
+
+ /**
+ * Applies {@code SortKey}. The namespace keys sort the list the reference says they do, and
+ * the two time keys leave it in namespace order: sorting by a last-authenticated time no
+ * entry carries would be ordering on nothing, and the reference's default is the namespace
+ * anyway.
+ */
+ private static List<String> sortedByKey(List<String> namespaces, String sortKey) {
+ if (!"SERVICE_NAMESPACE_DESCENDING".equals(sortKey)) {
+ return namespaces;
+ }
+ List<String> descending = new ArrayList<>(namespaces);
+ descending.sort(Comparator.reverseOrder());
+ return descending;
+ }
+
/**
* Lists the entities that could have reached the service through the reported ARN's
* permissions, which AWS derives from policy content rather than from usage: a group report
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportService.java b/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportService.java
new file mode 100644
index 0000000000..52d34dbf24
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportService.java
@@ -0,0 +1,308 @@
+package io.github.hectorvent.floci.services.iam;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.iam.model.OrganizationsAccessReportJob;
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import io.github.hectorvent.floci.services.organizations.model.Organization;
+import io.github.hectorvent.floci.services.organizations.model.OrganizationPolicy;
+import io.github.hectorvent.floci.services.organizations.model.PolicyTypeSummary;
+import io.github.hectorvent.floci.services.organizations.model.Root;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+/**
+ * The report registry behind {@code GenerateOrganizationsAccessReport} and
+ * {@code GetOrganizationsAccessReport}.
+ *
+ * <p>The report answers an Organizations question with IAM's policy logic, so the entity path and
+ * the SCPs are read from {@link OrganizationsService} through its own public API and the service
+ * list is computed by {@link IamPolicyEvaluator#servicesAllowedByScpLevels}. Only SCP logic
+ * applies, which the reference is explicit about: identity-based policies, resource policies,
+ * permissions boundaries and trust policies are all excluded from this data.
+ *
+ * <p>Floci records no service access, so every service in a report is one principals are allowed
+ * but never used, which is the shape the reference's own example gives such a service: a namespace
+ * and a zero count, with no region, entity path or last-authenticated time.
+ */
+@ApplicationScoped
+public class OrganizationsAccessReportService {
+
+ private static final String SERVICE_CONTROL_POLICY = "SERVICE_CONTROL_POLICY";
+ private static final String ENABLED = "ENABLED";
+ /** What Organizations answers a caller whose account belongs to no organization. */
+ private static final String NOT_IN_ORGANIZATION = "AWSOrganizationsNotInUseException";
+
+ /** {@code organizationsEntityPathType}: an organization id, a root id, then the path below it. */
+ private static final Pattern ENTITY_PATH =
+ Pattern.compile("^o-[0-9a-z]{10,32}\\/r-[0-9a-z]{4,32}[0-9a-z-\\/]*");
+ private static final int ENTITY_PATH_MIN = 19;
+ private static final int ENTITY_PATH_MAX = 427;
+ /** {@code organizationsPolicyIdType}. */
+ private static final Pattern POLICY_ID = Pattern.compile("^p-[0-9a-zA-Z_]{8,128}$");
+
+ private final IamJobStore<OrganizationsAccessReportJob> jobs;
+ private final OrganizationsService organizationsService;
+ private final IamPolicyEvaluator policyEvaluator;
+ private final Clock clock;
+
+ @Inject
+ public OrganizationsAccessReportService(StorageFactory storageFactory,
+ OrganizationsService organizationsService,
+ IamPolicyEvaluator policyEvaluator, Clock clock) {
+ this(storageFactory.create("iam", "iam-organizations-access-report-jobs.json",
+ new TypeReference<>() {}), organizationsService, policyEvaluator, clock);
+ }
+
+ OrganizationsAccessReportService(StorageBackend<String, OrganizationsAccessReportJob> jobs,
+ OrganizationsService organizationsService,
+ IamPolicyEvaluator policyEvaluator, Clock clock) {
+ this.jobs = new IamJobStore<>(jobs, OrganizationsAccessReportJob::getJobId);
+ this.organizationsService = organizationsService;
+ this.policyEvaluator = policyEvaluator;
+ this.clock = clock;
+ }
+
+ /**
+ * Generates the report now and stores it with the job, the way the Access Advisor jobs do:
+ * AWS fixes a report at generation time and the reader only retrieves it, so there is no work
+ * left to defer and the creation and completion timestamps are the same instant.
+ *
+ * <p>Only the caller's own standing is answered synchronously. The reference models no error
+ * on this operation for an entity path that names nothing, and gives the reader a
+ * {@code FAILED} status with {@code ErrorDetails} instead, so anything about the state of the
+ * organization lands there rather than becoming an error code AWS does not publish.
+ */
+ public OrganizationsAccessReportJob generate(String callerAccountId, String entityPath,
+ String organizationsPolicyId) {
+ validateEntityPath(entityPath);
+ validatePolicyId(organizationsPolicyId);
+ Organization organization = requireManagementAccount(callerAccountId);
+
+ List<String> segments = List.of(entityPath.split("/"));
+ if (!segments.get(0).equals(organization.getId())) {
+ return failed(callerAccountId, entityPath, organizationsPolicyId, "InvalidEntityPath",
+ "The organization " + segments.get(0) + " is not the caller's organization.");
+ }
+ Optional<Root> root = findRoot(callerAccountId, segments.get(1));
+ if (root.isEmpty()) {
+ return failed(callerAccountId, entityPath, organizationsPolicyId, "InvalidEntityPath",
+ "The organization root " + segments.get(1) + " cannot be found.");
+ }
+ if (!hasServiceControlPoliciesEnabled(root.get())) {
+ return failed(callerAccountId, entityPath, organizationsPolicyId,
+ "PolicyTypeNotEnabled",
+ "Service control policies are not enabled for the organization root "
+ + root.get().getId() + ".");
+ }
+ try {
+ requirePathInTree(callerAccountId, entityPath, segments);
+ return completed(callerAccountId, entityPath, organizationsPolicyId,
+ servicesFor(organization, segments, organizationsPolicyId));
+ } catch (AwsException e) {
+ // Organizations answers its own codes for an entity it does not hold, and they are not
+ // errors this operation publishes, so the job carries the reason instead.
+ return failed(callerAccountId, entityPath, organizationsPolicyId, e.getErrorCode(),
+ e.getMessage());
+ }
+ }
+
+ public OrganizationsAccessReportJob get(String callerAccountId, String jobId) {
+ requireManagementAccount(callerAccountId);
+ return jobs.get(callerAccountId, jobId);
+ }
+
+ /**
+ * The services the SCPs along the path leave reachable. The management account is not limited
+ * by SCPs, so its report lists every service and the reference says an
+ * {@code OrganizationsPolicyId} passed with it "is ignored". A policy id otherwise narrows the
+ * report to that one SCP, and without one the whole chain applies, level by level.
+ */
+ private List<String> servicesFor(Organization organization, List<String> segments,
+ String organizationsPolicyId) {
+ String callerAccountId = organization.getMasterAccountId();
+ if (segments.get(segments.size() - 1).equals(callerAccountId)) {
+ return policyEvaluator.servicesAllowedByScpLevels(null);
+ }
+ if (organizationsPolicyId != null) {
+ OrganizationPolicy policy =
+ organizationsService.describePolicy(callerAccountId, organizationsPolicyId);
+ if (!SERVICE_CONTROL_POLICY.equals(policy.getType())) {
+ // Organizations holds tag, backup, chatbot and opt-out policies under the same id
+ // space, and none of them carries statements. Evaluating one as a ceiling would
+ // read as a level that constrains nothing and report every service there is.
+ throw new AwsException("InvalidInputException", "The policy "
+ + organizationsPolicyId + " is a " + policy.getType()
+ + ", not a service control policy.", 400);
+ }
+ return policyEvaluator.servicesAllowedByScpLevels(
+ List.of(List.of(policy.getContent() == null ? "" : policy.getContent())));
+ }
+ List<List<String>> levels = new ArrayList<>();
+ for (String node : segments.subList(1, segments.size())) {
+ // Each node is resolved by the listing itself: Organizations answers
+ // TargetNotFoundException for one it does not hold, which fails the job.
+ List<String> documents = new ArrayList<>();
+ for (OrganizationPolicy policy : organizationsService
+ .listPoliciesForTarget(callerAccountId, node, SERVICE_CONTROL_POLICY)) {
+ if (policy.getContent() != null) {
+ documents.add(policy.getContent());
+ }
+ }
+ levels.add(documents);
+ }
+ return policyEvaluator.servicesAllowedByScpLevels(levels);
+ }
+
+ /**
+ * Holds the entity path to a path the organization actually has. The segments below the root
+ * name a chain of parent and child, so each one is resolved together with the one above it:
+ * Organizations reports the path of any node it holds, and the request has to spell that same
+ * path. Resolving the segments one at a time would accept a path assembled from two branches,
+ * or one whose intervening OU does not exist at all, and report the policies of a chain the
+ * organization does not have.
+ */
+ private void requirePathInTree(String callerAccountId, String entityPath,
+ List<String> segments) {
+ String node = segments.get(segments.size() - 1);
+ // Throws the Organizations code for a node it does not hold, which fails the job.
+ String actual = organizationsService.organizationPath(callerAccountId, node);
+ if (!trimTrailingSlash(actual).equals(trimTrailingSlash(entityPath))) {
+ throw new AwsException("InvalidEntityPath", "The entity path " + entityPath
+ + " is not a path in the organization. " + node + " is at " + actual + ".",
+ 400);
+ }
+ }
+
+ private static String trimTrailingSlash(String path) {
+ return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
+ }
+
+ private Optional<Root> findRoot(String callerAccountId, String rootId) {
+ return organizationsService.listRoots(callerAccountId).stream()
+ .filter(candidate -> rootId.equals(candidate.getId()))
+ .findFirst();
+ }
+
+ private boolean hasServiceControlPoliciesEnabled(Root root) {
+ for (PolicyTypeSummary policyType : root.getPolicyTypes()) {
+ if (SERVICE_CONTROL_POLICY.equals(policyType.getType())
+ && ENABLED.equals(policyType.getStatus())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Both operations document that the caller must be signed in to the management account.
+ * Neither models a code for a caller who is not, but a per-action error list is additive: the
+ * reference's common error types apply to every action and carry the 403 permission denial,
+ * and the user guide names the code for a denied IAM action in its
+ * {@code AddRoleToInstanceProfile} entry. The common error page spells it
+ * {@code AccessDeniedException}; the user guide and the rest of this service's surface spell
+ * it {@code AccessDenied}, which is what a caller here is already seeing elsewhere.
+ */
+ private Organization requireManagementAccount(String callerAccountId) {
+ Organization organization;
+ try {
+ organization = organizationsService.describeOrganization(callerAccountId);
+ } catch (AwsException e) {
+ if (!NOT_IN_ORGANIZATION.equals(e.getErrorCode())) {
+ // Only the account-has-no-organization answer means anything about the caller's
+ // standing. Anything else is a failure of the read itself, and reporting it as a
+ // permission problem would send the caller after the wrong thing.
+ throw e;
+ }
+ // An account in no organization is not a management account either, and
+ // AWSOrganizationsNotInUse is an Organizations code this operation does not publish.
+ throw managementAccountOnly();
+ }
+ if (!callerAccountId.equals(organization.getMasterAccountId())) {
+ throw managementAccountOnly();
+ }
+ return organization;
+ }
+
+ private static AwsException managementAccountOnly() {
+ return new AwsException("AccessDenied",
+ "This operation can be performed only by the management account of the "
+ + "organization.", 403);
+ }
+
+ /**
+ * The constraint AWS names is the one that failed, not whichever one the check happens to end
+ * on: a path over the maximum length is a length violation and reads as one, as every other
+ * validated IAM member does.
+ */
+ private static void validateEntityPath(String entityPath) {
+ String constraint;
+ if (entityPath == null) {
+ constraint = "Member must not be null";
+ } else if (entityPath.length() < ENTITY_PATH_MIN) {
+ constraint = "Member must have length greater than or equal to " + ENTITY_PATH_MIN;
+ } else if (entityPath.length() > ENTITY_PATH_MAX) {
+ constraint = "Member must have length less than or equal to " + ENTITY_PATH_MAX;
+ } else if (!ENTITY_PATH.matcher(entityPath).matches()) {
+ constraint = "Member must satisfy regular expression pattern: " + ENTITY_PATH.pattern();
+ } else {
+ return;
+ }
+ throw validationError(entityPath, "entityPath", constraint);
+ }
+
+ /**
+ * {@code OrganizationsPolicyId} is optional, so an absent one is no error. A request that
+ * carries the member is held to the pattern whatever it carries, since an empty value is a
+ * malformed id rather than a way of leaving the member out.
+ */
+ private static void validatePolicyId(String organizationsPolicyId) {
+ if (organizationsPolicyId != null
+ && !POLICY_ID.matcher(organizationsPolicyId).matches()) {
+ throw validationError(organizationsPolicyId, "organizationsPolicyId",
+ "Member must satisfy regular expression pattern: " + POLICY_ID.pattern());
+ }
+ }
+
+ /** AWS's shape-violation message: an unquoted null, a quoted value, and what it failed. */
+ private static AwsException validationError(String value, String at, String constraint) {
+ return new AwsException("ValidationError", "1 validation error detected: Value "
+ + (value == null ? "null" : "'" + value + "'") + " at '" + at
+ + "' failed to satisfy constraint: " + constraint, 400);
+ }
+
+ private OrganizationsAccessReportJob completed(String callerAccountId, String entityPath,
+ String organizationsPolicyId,
+ List<String> serviceNamespaces) {
+ Instant now = clock.instant();
+ // jobIDType is min 36 / max 36, which is exactly a UUID string.
+ OrganizationsAccessReportJob job = new OrganizationsAccessReportJob(
+ UUID.randomUUID().toString(), entityPath, organizationsPolicyId, "COMPLETED",
+ now, now, serviceNamespaces);
+ jobs.put(callerAccountId, job);
+ return job;
+ }
+
+ private OrganizationsAccessReportJob failed(String callerAccountId, String entityPath,
+ String organizationsPolicyId, String code,
+ String message) {
+ Instant now = clock.instant();
+ OrganizationsAccessReportJob job = new OrganizationsAccessReportJob(
+ UUID.randomUUID().toString(), entityPath, organizationsPolicyId, "FAILED",
+ now, now, List.of());
+ job.setErrorCode(code);
+ job.setErrorMessage(message);
+ jobs.put(callerAccountId, job);
+ return job;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
index 7e7e579af3..c408850bdd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
@@ -165,7 +165,6 @@ public class ResourceArnBuilder {
* exists to close.
*/
static final Map<String, String> UNRESOLVED_TYPES = Map.of(
- "access-report", "GenerateOrganizationsAccessReport is not dispatched",
"delegation-request", "the delegation request family is not dispatched",
"role-template", "GetRoleTemplateVersion is not dispatched");
@@ -183,10 +182,12 @@ public class ResourceArnBuilder {
static final Map<String, String> IAM_ARN_PARAMETERS = iamArnParameters();
/**
- * The actions resolved by a branch of their own in {@link #buildIamArns}, because the request
- * identifies the resource without naming it: a service principal for
- * {@code CreateServiceLinkedRole}, an access key id for {@code GetAccessKeyLastUsed}, and a
- * deletion task id for {@code GetServiceLinkedRoleDeletionStatus}.
+ * The actions resolved by a branch of their own in {@link #buildIamArns}, because what the
+ * request carries is not an IAM entity's name: a service principal for
+ * {@code CreateServiceLinkedRole}, an access key id for {@code GetAccessKeyLastUsed}, a
+ * deletion task id for {@code GetServiceLinkedRoleDeletionStatus}, and an Organizations
+ * entity path for {@code GenerateOrganizationsAccessReport}, whose resource lives in another
+ * service's tree.
*
* <p>The resolver is the value rather than a branch elsewhere, so this cannot become a list
* that says an action is handled while the dispatch has nothing for it. The keys are also what
@@ -197,7 +198,9 @@ public class ResourceArnBuilder {
"CreateServiceLinkedRole", ResourceArnBuilder::serviceLinkedRoleArn,
"GetAccessKeyLastUsed",
(self, ctx, region, accountId) -> self.accessKeyOwnerArn(ctx, accountId),
- "GetServiceLinkedRoleDeletionStatus", ResourceArnBuilder::deletionTaskRoleArn);
+ "GetServiceLinkedRoleDeletionStatus", ResourceArnBuilder::deletionTaskRoleArn,
+ "GenerateOrganizationsAccessReport",
+ ResourceArnBuilder::organizationsAccessReportArn);
/** How one of {@link #DERIVED_RESOLVERS} reads its resource out of the request. */
interface DerivedResolver {
@@ -466,6 +469,22 @@ public class ResourceArnBuilder {
.orElse(List.of("*"));
}
+ /**
+ * The report {@code GenerateOrganizationsAccessReport} would produce. The reference spells the
+ * type as {@code access-report/${EntityPath}}, so the resource is the Organizations entity
+ * path the request carries and there is no IAM {@code Path} to read: the slashes inside it are
+ * the organization's own tree, not an IAM path.
+ */
+ private List<String> organizationsAccessReportArn(ContainerRequestContext ctx, String region,
+ String accountId) {
+ String entityPath = RequestBodyReader.formField(ctx, "EntityPath");
+ if (entityPath == null || entityPath.isBlank()) {
+ return List.of("*");
+ }
+ return List.of(AwsArnUtils.Arn.global(AwsRegions.partitionFor(region), "iam", accountId,
+ "access-report/" + entityPath).toString());
+ }
+
/** A request's Path as it appears in an ARN: slash-delimited, defaulting to a bare slash. */
private static String normalizeArnPath(String path) {
if (path == null || path.isBlank()) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.java b/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.java
index 670c40dd25..35982118ad 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.java
@@ -2,7 +2,6 @@ package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
-import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedEntity;
@@ -37,7 +36,7 @@ public class ServiceLastAccessedService {
private static final Set<String> GRANULARITIES = Set.of("SERVICE_LEVEL", "ACTION_LEVEL");
private static final String DEFAULT_GRANULARITY = "SERVICE_LEVEL";
- private final StorageBackend<String, ServiceLastAccessedJob> jobs;
+ private final IamJobStore<ServiceLastAccessedJob> jobs;
@Inject
public ServiceLastAccessedService(StorageFactory storageFactory) {
@@ -45,7 +44,7 @@ public class ServiceLastAccessedService {
}
ServiceLastAccessedService(StorageBackend<String, ServiceLastAccessedJob> jobs) {
- this.jobs = jobs;
+ this.jobs = new IamJobStore<>(jobs, ServiceLastAccessedJob::getJobId);
}
/**
@@ -68,30 +67,15 @@ public class ServiceLastAccessedService {
ServiceLastAccessedJob job = new ServiceLastAccessedJob(UUID.randomUUID().toString(), arn,
granularity == null ? DEFAULT_GRANULARITY : granularity, now, now,
serviceNamespaces, entities);
- putForAccount(accountId, job);
+ jobs.put(accountId, job);
return job;
}
public ServiceLastAccessedJob get(String accountId, String jobId) {
- return find(accountId, jobId).orElseThrow(() -> new AwsException("NoSuchEntity",
- "The job ID " + jobId + " cannot be found.", 404));
+ return jobs.get(accountId, jobId);
}
public Optional<ServiceLastAccessedJob> find(String accountId, String jobId) {
- if (jobId == null || jobId.isBlank()) {
- return Optional.empty();
- }
- if (jobs instanceof AccountAwareStorageBackend<ServiceLastAccessedJob> aware) {
- return aware.getForAccount(accountId, jobId);
- }
- return jobs.get(jobId);
- }
-
- private void putForAccount(String accountId, ServiceLastAccessedJob job) {
- if (jobs instanceof AccountAwareStorageBackend<ServiceLastAccessedJob> aware) {
- aware.putForAccount(accountId, job.getJobId(), job);
- } else {
- jobs.put(job.getJobId(), job);
- }
+ return jobs.find(accountId, jobId);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/OrganizationsAccessReportJob.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/OrganizationsAccessReportJob.java
new file mode 100644
index 0000000000..568e345063
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/OrganizationsAccessReportJob.java
@@ -0,0 +1,92 @@
+package io.github.hectorvent.floci.services.iam.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * One Organizations access report created by {@code GenerateOrganizationsAccessReport}, together
+ * with the report it produced.
+ *
+ * <p>As with {@link ServiceLastAccessedJob}, AWS fixes a report at generation time and
+ * {@code GetOrganizationsAccessReport} only retrieves it, so the service list is captured here
+ * rather than recomputed on read: attaching an SCP afterwards does not change what an already
+ * completed job returns.
+ *
+ * <p>A job carries its own status because this report has a failure the other one does not. The
+ * generator models no error for an entity path that is well-formed but resolves to nothing, while
+ * the reader publishes both a {@code FAILED} status and {@code ErrorDetails}, so that is where a
+ * path naming an entity outside the organization lands. Which fields carry it is read off the
+ * shape of the API rather than off a sentence, so it is an inference, and the alternatives are
+ * worse: another service's error code on an IAM operation, or a completed report that cannot be
+ * told apart from an organization reaching no services.
+ */
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class OrganizationsAccessReportJob {
+
+ private String jobId;
+ private String entityPath;
+ private String organizationsPolicyId;
+ private String jobStatus;
+ private Instant jobCreationDate;
+ private Instant jobCompletionDate;
+ private List<String> serviceNamespaces = new ArrayList<>();
+ private String errorCode;
+ private String errorMessage;
+
+ public OrganizationsAccessReportJob() {}
+
+ public OrganizationsAccessReportJob(String jobId, String entityPath,
+ String organizationsPolicyId, String jobStatus,
+ Instant jobCreationDate, Instant jobCompletionDate,
+ List<String> serviceNamespaces) {
+ this.jobId = jobId;
+ this.entityPath = entityPath;
+ this.organizationsPolicyId = organizationsPolicyId;
+ this.jobStatus = jobStatus;
+ this.jobCreationDate = jobCreationDate;
+ this.jobCompletionDate = jobCompletionDate;
+ setServiceNamespaces(serviceNamespaces);
+ }
+
+ public String getJobId() { return jobId; }
+ public void setJobId(String jobId) { this.jobId = jobId; }
+
+ public String getEntityPath() { return entityPath; }
+ public void setEntityPath(String entityPath) { this.entityPath = entityPath; }
+
+ public String getOrganizationsPolicyId() { return organizationsPolicyId; }
+
+ public void setOrganizationsPolicyId(String organizationsPolicyId) {
+ this.organizationsPolicyId = organizationsPolicyId;
+ }
+
+ public String getJobStatus() { return jobStatus; }
+ public void setJobStatus(String jobStatus) { this.jobStatus = jobStatus; }
+
+ public Instant getJobCreationDate() { return jobCreationDate; }
+ public void setJobCreationDate(Instant jobCreationDate) { this.jobCreationDate = jobCreationDate; }
+
+ public Instant getJobCompletionDate() { return jobCompletionDate; }
+
+ public void setJobCompletionDate(Instant jobCompletionDate) {
+ this.jobCompletionDate = jobCompletionDate;
+ }
+
+ public List<String> getServiceNamespaces() { return serviceNamespaces; }
+
+ public void setServiceNamespaces(List<String> serviceNamespaces) {
+ this.serviceNamespaces = serviceNamespaces == null
+ ? new ArrayList<>() : new ArrayList<>(serviceNamespaces);
+ }
+
+ public String getErrorCode() { return errorCode; }
+ public void setErrorCode(String errorCode) { this.errorCode = errorCode; }
+
+ public String getErrorMessage() { return errorMessage; }
+ public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionResourcesTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionResourcesTest.java
index 220eddb272..503124502f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamActionResourcesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamActionResourcesTest.java
@@ -141,8 +141,10 @@ class IamActionResourcesTest {
"user", "role", "group", "instance-profile", "server-certificate",
// Named by an ARN the request carries, or minted by a create.
"policy", "mfa", "sms-mfa", "saml-provider", "oidc-provider",
+ // Named by a parameter that is not an IAM entity name.
+ "access-report",
// Only on actions the handler does not dispatch.
- "access-report", "delegation-request", "role-template"),
+ "delegation-request", "role-template"),
inUse,
"AWS has changed which resource types IAM actions are authorized against; "
+ "teach ResourceArnBuilder the new one or list it as unresolved");
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
index f1ed6fa25b..b197d27162 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsServiceNamespaces;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
@@ -1088,4 +1089,186 @@ class IamPolicyEvaluatorTest {
assertEquals(List.of("aws:PrincipalArn"), keys);
}
+
+ @Test
+ void anAbsentScpChainLeavesEveryServiceReachable() {
+ // The management account's case: the reference says it "is not limited by SCPs", so its
+ // report lists every service.
+ assertEquals(AwsServiceNamespaces.all().size(),
+ evaluator.servicesAllowedByScpLevels(null).size());
+ }
+
+ @Test
+ void aLevelAllowingEverythingLeavesEveryServiceReachable() {
+ assertEquals(AwsServiceNamespaces.all().size(),
+ evaluator.servicesAllowedByScpLevels(List.of(List.of(ALLOW_ALL))).size());
+ }
+
+ @Test
+ void theLevelsAreIntersectedAndTheAttachedPoliciesWithinOneAreNot() {
+ // FullAWSAccess at the root, S3 only at the OU: the OU's ceiling wins.
+ assertEquals(List.of("s3"),
+ evaluator.servicesAllowedByScpLevels(
+ List.of(List.of(ALLOW_ALL), List.of(ALLOW_S3_ONLY))));
+ // Two policies attached at one level are a union, so both services survive a root that
+ // allows everything.
+ assertEquals(List.of("dynamodb", "s3"),
+ evaluator.servicesAllowedByScpLevels(List.of(List.of(ALLOW_ALL),
+ List.of(ALLOW_S3_ONLY, allowOnly("dynamodb")))));
+ }
+
+ @Test
+ void levelsThatCannotOverlapLeaveNothingReachable() {
+ assertEquals(List.of(), evaluator.servicesAllowedByScpLevels(
+ List.of(List.of(ALLOW_S3_ONLY), List.of(allowOnly("dynamodb")))));
+ }
+
+ @Test
+ void aDenyDropsAServiceOnlyWhenItClosesTheWholeNamespace() {
+ // DENY_S3 denies s3:*, so S3 goes.
+ assertFalse(evaluator.servicesAllowedByScpLevels(List.of(List.of(DENY_S3))).contains("s3"));
+ // One action is not the service: a principal can still reach S3 through everything else.
+ String denyOneAction =
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"s3:DeleteBucket\","
+ + "\"Resource\":\"*\"}]}";
+ assertTrue(evaluator.servicesAllowedByScpLevels(List.of(List.of(denyOneAction)))
+ .contains("s3"));
+ }
+
+ @Test
+ void aConditionalDenyLeavesEveryServiceReachable() {
+ // The region guardrail most organizations carry. It bites only outside one region, so
+ // every service is still reachable inside it, and treating it as a total deny would report
+ // an organization that reaches nothing at all.
+ String denyOutsideOneRegion =
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"*\",\"Resource\":\"*\","
+ + "\"Condition\":{\"StringNotEquals\":"
+ + "{\"aws:RequestedRegion\":\"us-east-1\"}}}]}";
+
+ assertEquals(AwsServiceNamespaces.all().size(),
+ evaluator.servicesAllowedByScpLevels(List.of(List.of(denyOutsideOneRegion)))
+ .size());
+ }
+
+ @Test
+ void aDenyScopedToOneResourceLeavesTheServiceReachable() {
+ // Denying s3:* on one bucket does not put S3 out of reach: every other bucket is still
+ // there, which is the same reading that keeps a service denied one action on the list.
+ String denyOneBucket =
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"s3:*\","
+ + "\"Resource\":\"arn:aws:s3:::locked-bucket/*\"}]}";
+
+ assertTrue(evaluator.servicesAllowedByScpLevels(List.of(List.of(denyOneBucket)))
+ .contains("s3"));
+ }
+
+ @Test
+ void aNotActionDenyIsTheAllowListIdiomItIsWrittenAs() {
+ // The common SCP shape: allow everything, then deny everything that is not S3.
+ String denyAllButS3 =
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"NotAction\":\"s3:*\","
+ + "\"Resource\":\"*\"}]}";
+
+ assertEquals(List.of("s3"),
+ evaluator.servicesAllowedByScpLevels(List.of(List.of(denyAllButS3))));
+ }
+
+ @Test
+ void levelsAllowingDisjointSingleActionsLeaveNothingReachable() {
+ // Both levels allow an S3 action, so a namespace-at-a-time reading intersects S3 with S3
+ // and keeps it, although no one action clears both ceilings.
+ assertFalse(evaluator.servicesAllowedByScpLevels(
+ List.of(List.of(allowOnlyAction("s3:GetObject")),
+ List.of(allowOnlyAction("s3:PutObject"))))
+ .contains("s3"));
+ // The same two levels where the actions do overlap keep it.
+ assertTrue(evaluator.servicesAllowedByScpLevels(
+ List.of(List.of(allowOnlyAction("s3:Get*")),
+ List.of(allowOnlyAction("s3:GetObject"))))
+ .contains("s3"));
+ }
+
+ @Test
+ void aDenyOnTheOnlyAllowedActionDropsTheService() {
+ // The deny closes nothing like the whole namespace, but it closes everything the level
+ // allowed, which leaves no S3 action to reach.
+ String allowAndDenyOneAction =
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\","
+ + "\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"s3:GetObject\","
+ + "\"Resource\":\"*\"}]}";
+
+ assertFalse(evaluator.servicesAllowedByScpLevels(List.of(List.of(allowAndDenyOneAction)))
+ .contains("s3"));
+ }
+
+ @Test
+ void aDenyOnAWiderPatternThanTheAllowDropsTheService() {
+ String allowOneDenyThePrefix =
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\","
+ + "\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"s3:Get*\","
+ + "\"Resource\":\"*\"}]}";
+
+ assertFalse(evaluator.servicesAllowedByScpLevels(List.of(List.of(allowOneDenyThePrefix)))
+ .contains("s3"));
+ // Narrower the other way round: the deny takes GetObject and the allow keeps the rest of
+ // the prefix, so the service stays.
+ String allowThePrefixDenyOne =
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"s3:Get*\","
+ + "\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"s3:GetObject\","
+ + "\"Resource\":\"*\"}]}";
+
+ assertTrue(evaluator.servicesAllowedByScpLevels(List.of(List.of(allowThePrefixDenyOne)))
+ .contains("s3"));
+ }
+
+ @Test
+ void aWildcardThatIsNotATrailingOneKeepsTheServiceOnTheList() {
+ // The documented limit of the probes: s3:*Object and s3:Get* do overlap, at s3:GetObject,
+ // but no stand-in action shows it. The service stays on the list rather than coming off
+ // it, which is the side the namespace reading was already on.
+ assertTrue(evaluator.servicesAllowedByScpLevels(
+ List.of(List.of(allowOnlyAction("s3:Get*")),
+ List.of(allowOnlyAction("s3:*Object"))))
+ .contains("s3"));
+ }
+
+ @Test
+ void anUnreadableGuardrailLeavesNothingReachable() {
+ // The same judgement scpAllows makes: the ceiling cannot tell what the document said, and
+ // reporting every service would be the permissive answer.
+ assertEquals(List.of(),
+ evaluator.servicesAllowedByScpLevels(List.of(List.of(ALLOW_ALL, MALFORMED))));
+ }
+
+ @Test
+ void aLevelWithNoPolicyConstrainsNothing() {
+ // AWS keeps FullAWSAccess attached to every target, so a bare level is not a level that
+ // denies: it is one that has nothing to say.
+ assertEquals(List.of("s3"), evaluator.servicesAllowedByScpLevels(
+ List.of(List.of(), List.of(ALLOW_S3_ONLY))));
+ }
+
+ private static String allowOnlyAction(String action) {
+ return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Action\":\"" + action + "\",\"Resource\":\"*\"}]}";
+ }
+
+ private static String allowOnly(String namespace) {
+ return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Action\":\"" + namespace + ":*\",\"Resource\":\"*\"}]}";
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java
index 92078a4808..5884d6ffc0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamQueryHandlerTest.java
@@ -61,7 +61,7 @@ class IamQueryHandlerTest {
"fabricated-key", null, Map.of())).thenReturn(certificate);
when(service.getServerCertificate(CERTIFICATE_NAME)).thenReturn(certificate);
when(service.listServerCertificates(null)).thenReturn(List.of(certificate));
- IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null);
+ IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ServerCertificateName", CERTIFICATE_NAME);
@@ -90,7 +90,7 @@ class IamQueryHandlerTest {
IamService service = mock(IamService.class);
when(service.createRole(ROLE_NAME, "/", "{}", null, 3600, Map.of(), null)).thenReturn(role);
when(service.getValidatedRole(ROLE_NAME)).thenReturn(role);
- IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null);
+ IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null);
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("RoleName", ROLE_NAME);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportIntegrationTest.java
new file mode 100644
index 0000000000..41f042dc76
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportIntegrationTest.java
@@ -0,0 +1,463 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.testing.PartitionCleanup;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.path.xml.XmlPath;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.util.List;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The Organizations access report end to end, over a real organization built through the
+ * Organizations API.
+ *
+ * <p>Runs as its own management account so it never contends with the other Organizations suites
+ * for one, and each test deletes the organization it built, the Quarkus instance being shared.
+ *
+ * <p>Floci records no service access, so every service in a report is one principals are allowed
+ * but never reached. That is the shape the reference's own example gives such a service: a
+ * namespace and a zero count, with no region, entity path or last-authenticated time.
+ */
+@QuarkusTest
+class OrganizationsAccessReportIntegrationTest {
+
+ private static final String MANAGEMENT_ACCOUNT = "555555555555";
+ private static final String MEMBER_ACCOUNT = "555555555556";
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String TARGET_PREFIX = "AWSOrganizationsV20161128.";
+ /** The allow-list idiom an SCP is actually written as: allow all, then deny all but one. */
+ private static final String DENY_ALL_BUT_S3 =
+ "{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":["
+ + "{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"*\\\",\\\"Resource\\\":\\\"*\\\"},"
+ + "{\\\"Effect\\\":\\\"Deny\\\",\\\"NotAction\\\":\\\"s3:*\\\","
+ + "\\\"Resource\\\":\\\"*\\\"}]}";
+ private static final String ALLOW_S3_ONLY =
+ "{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\","
+ + "\\\"Action\\\":\\\"s3:*\\\",\\\"Resource\\\":\\\"*\\\"}]}";
+
+ @RegisterExtension
+ final PartitionCleanup cleanup = new PartitionCleanup();
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ private static String authorization(String accountId, String service) {
+ return "AWS4-HMAC-SHA256 Credential=" + accountId
+ + "/20261010/us-east-1/" + service + "/aws4_request, SignedHeaders=host, "
+ + "Signature=abc";
+ }
+
+ private static RequestSpecification organizations(String accountId, String action, String body) {
+ return given()
+ .header("Authorization", authorization(accountId, "organizations"))
+ .header("X-Amz-Target", TARGET_PREFIX + action)
+ .contentType(CONTENT_TYPE)
+ .body(body);
+ }
+
+ private static RequestSpecification iam(String accountId, String action) {
+ return given().header("Authorization", authorization(accountId, "iam"))
+ .formParam("Action", action);
+ }
+
+ /** Creates the organization with SCPs enabled on its root, and returns its entity path. */
+ private String organizationWithScpsEnabled() {
+ return organization(true);
+ }
+
+ /** The same organization with the prerequisite left off: SCPs never enabled on the root. */
+ private String organizationWithoutScpsEnabled() {
+ return organization(false);
+ }
+
+ private String organization(boolean enableServiceControlPolicies) {
+ cleanup.register(() -> organizations(MANAGEMENT_ACCOUNT, "DeleteOrganization", "{}")
+ .when().post("/").then().statusCode(200));
+ String organizationId = organizations(MANAGEMENT_ACCOUNT, "CreateOrganization",
+ "{\"FeatureSet\":\"ALL\"}")
+ .when().post("/").then().statusCode(200)
+ .extract().jsonPath().getString("Organization.Id");
+ String rootId = organizations(MANAGEMENT_ACCOUNT, "ListRoots", "{}")
+ .when().post("/").then().statusCode(200)
+ .extract().jsonPath().getString("Roots[0].Id");
+ if (enableServiceControlPolicies) {
+ organizations(MANAGEMENT_ACCOUNT, "EnablePolicyType",
+ "{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"SERVICE_CONTROL_POLICY\"}")
+ .when().post("/").then().statusCode(200);
+ }
+ return organizationId + "/" + rootId;
+ }
+
+ private void attach(String policyId, String targetId) {
+ organizations(MANAGEMENT_ACCOUNT, "AttachPolicy",
+ "{\"PolicyId\":\"" + policyId + "\",\"TargetId\":\"" + targetId + "\"}")
+ .when().post("/").then().statusCode(200);
+ }
+
+ private String createOrganizationalUnit(String name, String parentId) {
+ String ouId = organizations(MANAGEMENT_ACCOUNT, "CreateOrganizationalUnit",
+ "{\"Name\":\"" + name + "\",\"ParentId\":\"" + parentId + "\"}")
+ .when().post("/").then().statusCode(200)
+ .extract().jsonPath().getString("OrganizationalUnit.Id");
+ // Registered after the organization's own undo so it runs before it: Organizations
+ // refuses to delete an organization that still holds an OU, and the leftover would then
+ // fail the next test's CreateOrganization rather than this one.
+ cleanup.register(() -> organizations(MANAGEMENT_ACCOUNT, "DeleteOrganizationalUnit",
+ "{\"OrganizationalUnitId\":\"" + ouId + "\"}")
+ .when().post("/").then().statusCode(200));
+ return ouId;
+ }
+
+ /** The allow-list idiom over several namespaces: allow everything, then deny all but these. */
+ private static String denyAllBut(String... namespaces) {
+ StringBuilder notActions = new StringBuilder();
+ for (String namespace : namespaces) {
+ notActions.append(notActions.isEmpty() ? "" : ",")
+ .append("\\\"").append(namespace).append(":*\\\"");
+ }
+ return "{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":["
+ + "{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"*\\\","
+ + "\\\"Resource\\\":\\\"*\\\"},"
+ + "{\\\"Effect\\\":\\\"Deny\\\",\\\"NotAction\\\":[" + notActions
+ + "],\\\"Resource\\\":\\\"*\\\"}]}";
+ }
+
+ private String createScp(String name, String content) {
+ return organizations(MANAGEMENT_ACCOUNT, "CreatePolicy",
+ "{\"Content\":\"" + content + "\",\"Description\":\"" + name + "\","
+ + "\"Name\":\"" + name + "\",\"Type\":\"SERVICE_CONTROL_POLICY\"}")
+ .when().post("/").then().statusCode(200)
+ .extract().jsonPath().getString("Policy.PolicySummary.Id");
+ }
+
+ private String generate(String entityPath, String policyId) {
+ RequestSpecification request = iam(MANAGEMENT_ACCOUNT, "GenerateOrganizationsAccessReport")
+ .formParam("EntityPath", entityPath);
+ if (policyId != null) {
+ request = request.formParam("OrganizationsPolicyId", policyId);
+ }
+ return request.when().post("/").then().statusCode(200)
+ .extract().path("GenerateOrganizationsAccessReportResponse."
+ + "GenerateOrganizationsAccessReportResult.JobId");
+ }
+
+ private XmlPath report(String jobId, String... extraParams) {
+ RequestSpecification request = iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")
+ .formParam("JobId", jobId);
+ for (int i = 0; i < extraParams.length; i += 2) {
+ request = request.formParam(extraParams[i], extraParams[i + 1]);
+ }
+ return request.when().post("/").then().statusCode(200).extract().xmlPath();
+ }
+
+ private static String result(String field) {
+ return "GetOrganizationsAccessReportResponse.GetOrganizationsAccessReportResult." + field;
+ }
+
+ @Test
+ void aJobIdIsTheModeledLengthAndTheReportReadsBackCompleted() {
+ String entityPath = organizationWithScpsEnabled();
+
+ String jobId = generate(entityPath, null);
+
+ // jobIDType is min 36 / max 36, so a client buffer sized to the model must fit it exactly.
+ assertEquals(36, jobId.length(), "expected a 36-character job id, got: " + jobId);
+ XmlPath report = report(jobId);
+ assertEquals("COMPLETED", report.getString(result("JobStatus")));
+ assertFalse(report.getString(result("JobCreationDate")).isBlank());
+ assertFalse(report.getString(result("JobCompletionDate")).isBlank());
+ }
+
+ @Test
+ void aServiceNobodyReachedCarriesAZeroCountAndNoAttemptDetails() {
+ String jobId = generate(organizationWithScpsEnabled(), null);
+
+ XmlPath report = report(jobId, "MaxItems", "1");
+
+ assertEquals("0", report.getString(result("AccessDetails.member[0]"
+ + ".TotalAuthenticatedEntities")));
+ assertFalse(report.getString(result("AccessDetails.member[0].ServiceNamespace")).isBlank());
+ // The reference's own example omits all three for a service with no attempt.
+ assertTrue(report.getString(result("AccessDetails.member[0].LastAuthenticatedTime")) == null
+ || report.getString(result("AccessDetails.member[0]"
+ + ".LastAuthenticatedTime")).isBlank());
+ assertTrue(report.getString(result("AccessDetails.member[0].Region")) == null
+ || report.getString(result("AccessDetails.member[0].Region")).isBlank());
+ assertTrue(report.getString(result("AccessDetails.member[0].EntityPath")) == null
+ || report.getString(result("AccessDetails.member[0].EntityPath")).isBlank());
+ }
+
+ @Test
+ void theCountsAreTheWholeReportAndEveryServiceIsOneNobodyUsed() {
+ String jobId = generate(organizationWithScpsEnabled(), null);
+
+ XmlPath report = report(jobId);
+
+ String accessible = report.getString(result("NumberOfServicesAccessible"));
+ assertEquals(accessible, report.getString(result("NumberOfServicesNotAccessed")));
+ assertTrue(Integer.parseInt(accessible) > 100, "expected the full namespace catalog, got "
+ + accessible);
+ }
+
+ @Test
+ void aPolicyIdNarrowsTheReportToThatPolicy() {
+ String entityPath = organizationWithScpsEnabled();
+ String policyId = createScp("S3Only", ALLOW_S3_ONLY);
+
+ XmlPath report = report(generate(entityPath, policyId));
+
+ assertEquals("1", report.getString(result("NumberOfServicesAccessible")));
+ assertEquals("s3", report.getString(result("AccessDetails.member.ServiceNamespace")));
+ }
+
+ @Test
+ void anScpOnTheRootNarrowsTheReportToWhatItLeaves() {
+ // The one test that fails if the report does not read the SCPs off the organization tree:
+ // with only FullAWSAccess attached every service is reachable either way, so the ceiling
+ // has to come from a policy this test attached.
+ String entityPath = organizationWithScpsEnabled();
+ attach(createScp("S3Ceiling", DENY_ALL_BUT_S3),
+ entityPath.substring(entityPath.indexOf('/') + 1));
+
+ XmlPath report = report(generate(entityPath, null));
+
+ assertEquals("1", report.getString(result("NumberOfServicesAccessible")));
+ assertEquals("s3", report.getString(result("AccessDetails.member.ServiceNamespace")));
+ }
+
+ @Test
+ void theReportIsPaginatedAndSortable() {
+ String jobId = generate(organizationWithScpsEnabled(), null);
+
+ XmlPath firstPage = report(jobId, "MaxItems", "2");
+ assertEquals("true", firstPage.getString(result("IsTruncated")));
+ List<String> ascending = firstPage.getList(result("AccessDetails.member.ServiceNamespace"));
+ assertEquals(2, ascending.size());
+ assertTrue(ascending.get(0).compareTo(ascending.get(1)) < 0, ascending.toString());
+
+ List<String> descending = report(jobId, "MaxItems", "2",
+ "SortKey", "SERVICE_NAMESPACE_DESCENDING")
+ .getList(result("AccessDetails.member.ServiceNamespace"));
+ assertTrue(descending.get(0).compareTo(descending.get(1)) > 0, descending.toString());
+
+ String marker = firstPage.getString(result("Marker"));
+ assertFalse(marker.isBlank());
+ List<String> secondPage = report(jobId, "MaxItems", "2", "Marker", marker)
+ .getList(result("AccessDetails.member.ServiceNamespace"));
+ assertFalse(secondPage.contains(ascending.get(0)), secondPage.toString());
+ }
+
+ @Test
+ void aSortKeyOutsideTheEnumIsRejected() {
+ String jobId = generate(organizationWithScpsEnabled(), null);
+
+ iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")
+ .formParam("JobId", jobId)
+ .formParam("SortKey", "SERVICE_NAMESPACE")
+ .when().post("/").then().statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+ }
+
+ @Test
+ void onlyTheManagementAccountCanReadOrGenerateAReport() {
+ String entityPath = organizationWithScpsEnabled();
+ String jobId = generate(entityPath, null);
+
+ iam(MEMBER_ACCOUNT, "GenerateOrganizationsAccessReport")
+ .formParam("EntityPath", entityPath)
+ .when().post("/").then().statusCode(403)
+ .body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
+
+ iam(MEMBER_ACCOUNT, "GetOrganizationsAccessReport")
+ .formParam("JobId", jobId)
+ .when().post("/").then().statusCode(403)
+ .body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
+ }
+
+ @Test
+ void anEntityPathTheModelRejectsIsAValidationError() {
+ organizationWithScpsEnabled();
+
+ iam(MANAGEMENT_ACCOUNT, "GenerateOrganizationsAccessReport")
+ .formParam("EntityPath", "o-a1b2c3d4e5")
+ .when().post("/").then().statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+ }
+
+ @Test
+ void anEntityPathNamingAnotherOrganizationFailsTheJobRatherThanTheCall() {
+ organizationWithScpsEnabled();
+
+ String jobId = generate("o-zzzzzzzzzz/r-zzzz", null);
+
+ XmlPath report = report(jobId);
+ assertEquals("FAILED", report.getString(result("JobStatus")));
+ assertEquals("InvalidEntityPath", report.getString(result("ErrorDetails.Code")));
+ assertFalse(report.getString(result("ErrorDetails.Message")).isBlank());
+ }
+
+ @Test
+ void anUnknownJobIdIsNoSuchEntity() {
+ organizationWithScpsEnabled();
+
+ iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")
+ .formParam("JobId", "00000000-0000-0000-0000-000000000000")
+ .when().post("/").then().statusCode(404)
+ .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
+ }
+
+ @Test
+ void anOuPathIntersectsTheRootCeilingWithTheOneBelowIt() {
+ // The only test that drives more than one level. The root leaves S3 and DynamoDB, the OU
+ // leaves DynamoDB and IAM, so a report reading both answers DynamoDB alone: reading only
+ // the OU would add IAM and reading only the root would add S3.
+ String entityPath = organizationWithScpsEnabled();
+ String rootId = entityPath.substring(entityPath.indexOf('/') + 1);
+ String ouId = createOrganizationalUnit("Workloads", rootId);
+ attach(createScp("RootCeiling", denyAllBut("s3", "dynamodb")), rootId);
+ attach(createScp("OuCeiling", denyAllBut("dynamodb", "iam")), ouId);
+
+ XmlPath report = report(generate(entityPath + "/" + ouId, null));
+
+ assertEquals("1", report.getString(result("NumberOfServicesAccessible")));
+ assertEquals("dynamodb", report.getString(result("AccessDetails.member.ServiceNamespace")));
+ }
+
+ @Test
+ void theManagementAccountReportsEveryServiceAndIgnoresAPolicyId() {
+ // Both halves of what the reference says about that entity: it "is not limited by SCPs",
+ // so the root's ceiling does not apply to it, and a policy ID passed with it "is ignored".
+ String entityPath = organizationWithScpsEnabled();
+ attach(createScp("S3Ceiling", DENY_ALL_BUT_S3),
+ entityPath.substring(entityPath.indexOf('/') + 1));
+ String policyId = createScp("S3Only", ALLOW_S3_ONLY);
+
+ XmlPath report = report(generate(entityPath + "/" + MANAGEMENT_ACCOUNT, policyId));
+
+ assertTrue(Integer.parseInt(report.getString(result("NumberOfServicesAccessible"))) > 100,
+ "the management account is not limited by SCPs, so every service is reachable");
+ }
+
+ @Test
+ void anOrganizationWithoutServiceControlPoliciesFailsTheJob() {
+ // The reference states SCPs must be enabled for the root and models no error for an
+ // organization where they are not, so the failure lands where the other one does.
+ String jobId = generate(organizationWithoutScpsEnabled(), null);
+
+ XmlPath report = report(jobId);
+
+ assertEquals("FAILED", report.getString(result("JobStatus")));
+ assertEquals("PolicyTypeNotEnabled", report.getString(result("ErrorDetails.Code")));
+ }
+
+ @Test
+ void anEntityPathWhoseOusAreNotParentAndChildFailsTheJob() {
+ // Both OUs exist and the path is well formed, but Workloads is not under Platform. Taking
+ // each segment as an independent policy target would report the Platform and Workloads
+ // ceilings as a chain the organization does not have.
+ String entityPath = organizationWithScpsEnabled();
+ String rootId = entityPath.substring(entityPath.indexOf('/') + 1);
+ String platform = createOrganizationalUnit("Platform", rootId);
+ String workloads = createOrganizationalUnit("Workloads", rootId);
+
+ XmlPath report = report(generate(entityPath + "/" + platform + "/" + workloads, null));
+
+ assertEquals("FAILED", report.getString(result("JobStatus")));
+ assertEquals("InvalidEntityPath", report.getString(result("ErrorDetails.Code")));
+ }
+
+ @Test
+ void anEntityPathThatSkipsAnOuFailsTheJob() {
+ // Workloads is under Platform, so naming it straight off the root skips a ceiling.
+ String entityPath = organizationWithScpsEnabled();
+ String rootId = entityPath.substring(entityPath.indexOf('/') + 1);
+ String platform = createOrganizationalUnit("Platform", rootId);
+ String workloads = createOrganizationalUnit("Workloads", platform);
+
+ XmlPath report = report(generate(entityPath + "/" + workloads, null));
+
+ assertEquals("FAILED", report.getString(result("JobStatus")));
+ assertEquals("InvalidEntityPath", report.getString(result("ErrorDetails.Code")));
+ }
+
+ @Test
+ void aManagementAccountBehindAnUnknownOuFailsTheJob() {
+ // The management account reports every service, so a path resolved no further than its
+ // last segment would answer a completed all-services report for a path that names an OU
+ // the organization does not hold.
+ String entityPath = organizationWithScpsEnabled();
+
+ XmlPath report = report(generate(
+ entityPath + "/ou-rge0-notthere/" + MANAGEMENT_ACCOUNT, null));
+
+ assertEquals("FAILED", report.getString(result("JobStatus")));
+ assertEquals("InvalidEntityPath", report.getString(result("ErrorDetails.Code")));
+ }
+
+ @Test
+ void aPolicyIdNamingSomethingOtherThanAnScpFailsTheJob() {
+ // Organizations keeps every policy type in one id space, and a tag policy carries no
+ // statements, so evaluating one as a ceiling would read as a level that constrains
+ // nothing and report every service there is.
+ String entityPath = organizationWithScpsEnabled();
+ String rootId = entityPath.substring(entityPath.indexOf('/') + 1);
+ organizations(MANAGEMENT_ACCOUNT, "EnablePolicyType",
+ "{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"TAG_POLICY\"}")
+ .when().post("/").then().statusCode(200);
+ String tagPolicyId = organizations(MANAGEMENT_ACCOUNT, "CreatePolicy",
+ "{\"Content\":\"{\\\"tags\\\":{}}\",\"Description\":\"Tags\","
+ + "\"Name\":\"Tags\",\"Type\":\"TAG_POLICY\"}")
+ .when().post("/").then().statusCode(200)
+ .extract().jsonPath().getString("Policy.PolicySummary.Id");
+
+ XmlPath report = report(generate(entityPath, tagPolicyId));
+
+ assertEquals("FAILED", report.getString(result("JobStatus")));
+ assertEquals("InvalidInputException", report.getString(result("ErrorDetails.Code")));
+ }
+
+ @Test
+ void anEmptySortKeyIsRejectedRatherThanReadAsAnAbsentOne() {
+ String jobId = generate(organizationWithScpsEnabled(), null);
+
+ iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")
+ .formParam("JobId", jobId)
+ .formParam("SortKey", "")
+ .when().post("/").then().statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+ }
+
+ @Test
+ void anEmptyPolicyIdIsRejectedRatherThanReadAsAnAbsentOne() {
+ String entityPath = organizationWithScpsEnabled();
+
+ iam(MANAGEMENT_ACCOUNT, "GenerateOrganizationsAccessReport")
+ .formParam("EntityPath", entityPath)
+ .formParam("OrganizationsPolicyId", "")
+ .when().post("/").then().statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+ }
+
+ @Test
+ void anEntityPathNamingAnOuTheOrganizationDoesNotHoldFailsTheJob() {
+ String entityPath = organizationWithScpsEnabled();
+
+ XmlPath report = report(generate(entityPath + "/ou-rge0-notthere", null));
+
+ assertEquals("FAILED", report.getString(result("JobStatus")));
+ assertEquals("OrganizationalUnitNotFoundException",
+ report.getString(result("ErrorDetails.Code")));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportServiceTest.java
new file mode 100644
index 0000000000..9ff0d4f82a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/OrganizationsAccessReportServiceTest.java
@@ -0,0 +1,62 @@
+package io.github.hectorvent.floci.services.iam;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.organizations.OrganizationsService;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * What the report service does with an Organizations read that fails for a reason other than the
+ * caller having no organization. The end-to-end behaviour is in
+ * {@link OrganizationsAccessReportIntegrationTest}; this is the one case a real organization
+ * cannot be made to produce.
+ */
+class OrganizationsAccessReportServiceTest {
+
+ private static final String CALLER = "111122223333";
+ private static final String ENTITY_PATH = "o-a1b2c3d4e5/r-abcd";
+
+ @Test
+ void anOrganizationsReadThatFailsForAnotherReasonKeepsItsOwnError() {
+ OrganizationsService organizations = mock(OrganizationsService.class);
+ when(organizations.describeOrganization(CALLER))
+ .thenThrow(new AwsException("ServiceFailure",
+ "The request processing has failed because of an unknown error.", 500));
+ OrganizationsAccessReportService service = new OrganizationsAccessReportService(
+ new InMemoryStorage<>(), organizations,
+ new IamPolicyEvaluator(new ObjectMapper()), Clock.systemUTC());
+
+ AwsException thrown = assertThrows(AwsException.class,
+ () -> service.generate(CALLER, ENTITY_PATH, null));
+
+ // Reading it as AccessDenied would send the caller after a permission they already have.
+ assertEquals("ServiceFailure", thrown.getErrorCode());
+ assertEquals(500, thrown.getHttpStatus());
+ }
+
+ @Test
+ void anAccountInNoOrganizationIsNotAManagementAccount() {
+ OrganizationsService organizations = mock(OrganizationsService.class);
+ when(organizations.describeOrganization(CALLER))
+ .thenThrow(new AwsException("AWSOrganizationsNotInUseException",
+ "Your account is not a member of an organization.", 400));
+ OrganizationsAccessReportService service = new OrganizationsAccessReportService(
+ new InMemoryStorage<>(), organizations,
+ new IamPolicyEvaluator(new ObjectMapper()), Clock.systemUTC());
+
+ AwsException thrown = assertThrows(AwsException.class,
+ () -> service.generate(CALLER, ENTITY_PATH, null));
+
+ // AWSOrganizationsNotInUse is an Organizations code this operation does not publish.
+ assertEquals("AccessDenied", thrown.getErrorCode());
+ assertEquals(403, thrown.getHttpStatus());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
index 4ea4568da0..f13e0f56ec 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
@@ -393,6 +393,22 @@ class ResourceArnBuilderTest {
+ "&PolicyArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Apolicy%2Fp"));
}
+ /**
+ * The report {@code GenerateOrganizationsAccessReport} would produce. The reference spells the
+ * type as {@code access-report/${EntityPath}}, so the entity path goes in whole: its slashes
+ * are the organization's tree and there is no IAM path to read, which is why this does not go
+ * through the minting the creates use.
+ */
+ @Test
+ void iamNamesTheAccessReportAnOrganizationsEntityPathAsksFor() {
+ assertEquals("arn:aws:iam::000000000000:access-report/"
+ + "o-a1b2c3d4e5/r-f6g7h8i9j0example/ou-rge0-awsabcde/123456789012",
+ resourceOf(builder, "Action=GenerateOrganizationsAccessReport&EntityPath="
+ + "o-a1b2c3d4e5%2Fr-f6g7h8i9j0example%2Fou-rge0-awsabcde%2F123456789012"));
+ // Without the path there is nothing to name, so the permissive answer stands.
+ assertEquals("*", resourceOf(builder, "Action=GenerateOrganizationsAccessReport"));
+ }
+
/**
* The resource a certificate-specific policy statement has to match. Without this the action
* is evaluated against {@code *}, so a deny naming the certificate never applies.