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

GenerateOrganizationsAccessReport and GetOrganizationsAccessReport answered
UnsupportedOperation, which is not a reply any SDK models. They are the Access
Advisor job shape over a different question, and everything the question needs
was already here: an Organizations tree with roots, OUs, accounts and SCPs, a
policy evaluator, and a job model whose report is fixed at generation time.

The report is the services the service control policies along an entity path
leave reachable. The path names the organization, its root, and the OUs or
account below it, and the SCPs attached to each of those are read from
Organizations and evaluated. Only SCP logic applies, which the reference is
explicit about: identity policies, resource policies, ACLs, permissions
boundaries and trust policies play no part in this data.

Attached SCPs are a union within one level and the levels are intersected, so a
service survives only where every level allows it. That 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 carrying a Condition or
naming particular resources closes nothing: the region guardrail on * that most
organizations carry, and a deny scoped to one bucket, both leave the service
reachable by every request they do not cover, and reading them as total denials
would report an organization that reaches nothing.

This is still not the existing scpAllows asked once per namespace. That question
needs a concrete action, and a request action of s3:* would not match a statement
naming s3:GetObject, a pattern globbing 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, which decides the
patterns policies are written with exactly: a deny on s3:GetObject leaves the
service reachable where a deny on s3:Get* does not. A wildcard that is not a
trailing one is the limit of it, since the stand-in for s3:*Object misses the
s3:GetObject that s3:Get* would allow; such a pattern leaves the service on the
list rather than off it, which is the side the namespace reading was already on.

The management account is not limited by SCPs, so its report lists every service
and an OrganizationsPolicyId passed with it is ignored, both as documented.
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.

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 rather than each segment being resolved
on its own. Resolving them one at a time accepts a path assembled from two
branches, or one that skips an OU, and reports the policies of a chain the
organization does not have; it also lets a path whose last segment is the
management account take the unlimited answer with an OU above it that does not
exist.

Floci records no service access, so every service in a report is one principals
are allowed but never reached. The reference's own example gives such a service
as a namespace and a zero count with no region, entity path or last-authenticated
time, so that is the shape here and NumberOfServicesNotAccessed equals
NumberOfServicesAccessible. ServiceName carries a display name Floci has no
mapping for, so the namespace stands in for it as it does on the last-accessed
reader. SortKey is validated against its four values: the namespace keys sort
the list and the time keys leave it in namespace order, since 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 user guide names the code
for a denied IAM action outright in its AddRoleToInstanceProfile entry. That page
spells it AccessDeniedException where the user guide and the rest of this
service's surface spell it AccessDenied; the latter is used, so a caller sees one
spelling across IAM and STS.

Three things are inferences, and they are the same inference three times. The
docs say so. The generator models no error for an entity path that is well-formed
but resolves to nothing, nor for the prerequisite the reference states, that SCPs
be enabled for the organization root, nor for an OrganizationsPolicyId naming a
policy of some other type, so each produces a FAILED job carrying ErrorDetails:
InvalidEntityPath or the Organizations code for the entity in the first case,
PolicyTypeNotEnabled in the second, Organizations' InvalidInputException in the
third. That is read off the shape of the API rather than off a sentence: AWS
publishes both fields on this reader for failures the generator does not report
synchronously. The alternatives are worse. Letting Organizations' own error
escape unchanged puts 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 well-formed path,
a disabled policy type and an existing policy of the wrong type are not.

ReportGenerationLimitExceeded, the generator's only modeled error, reports
concurrent generations and stays unreachable: a job completes the moment it is
created, so two never overlap.

The generator also carries the access-report resource type, so it leaves
UNRESOLVED_TYPES and resolves from the request. The reference spells the type as
access-report/${EntityPath}, so the entity path goes into the ARN whole: its
slashes are the organization's tree, not an IAM path, which is why it does not
go through the minting the creates use.

Both actions join AwsQueryController.IAM_ACTIONS as well as the handler, without
which inferService would never route them. That list and the handler now hold
166 each, still exactly in step.

Validation runs before the lookup, as AWS rejects a request shape whether or not
the job exists: a SortKey outside the enum answers ValidationError even for a
job ID nothing holds, where validating it afterwards would answer NoSuchEntity.
A member the request carries is held to its shape whatever it carries, an empty
value included, since SortKey= and OrganizationsPolicyId= are a malformed enum
and a malformed id rather than a way of leaving an optional member out. The
entity path reports the constraint that failed rather than the regular
expression for every case, so a path over the maximum length reads as a length
violation, which is what every other validated IAM member does.

Only the one Organizations answer that means something about the caller becomes
AccessDenied. A read that fails for any other reason keeps its own error, rather
than reaching the caller as a permission problem they do not have.

Two things are shared rather than copied. The job registry both report
generators keep, an account-scoped store keyed by job ID that answers
NoSuchEntity for an ID it does not hold, moves into IamJobStore and
ServiceLastAccessedService reads it from there; the two had the same three
methods and the same message. The report's timestamps come from the injected
Clock, which IamService already takes, rather than from Instant.now(), so they
agree with every other time IAM decides. IamQueryHandlerTest builds the handler
itself rather than through injection, so it passes the new service along with
the dependencies it already does not use.

Fourteen unit tests cover the chain semantics, including the allow-list idiom of
allowing everything and denying all but one namespace, levels allowing disjoint
single actions, a deny on the only action allowed and on a pattern wider than it,
a conditional deny, a deny scoped to one bucket, a level with an unreadable
document, and a level with none. Twenty-one integration tests drive the pair over
an organization built through the Organizations API, on a management account of
their own so they never contend with the existing Organizations suites for one.
Two of them are the ones that hold the walk honest: the OU path, where the root
leaves S3 and DynamoDB and the OU leaves DynamoDB and IAM, so only a report
reading both levels answers DynamoDB alone, and the management account path,
which reports every service and ignores the policy ID passed with it even with a
ceiling attached to the root above it. With the tree read deliberately broken the
first SCP test returns all 456 namespaces instead of the one, and it is the only
test that notices. Two more tests mock the Organizations read, which is the one
failure a real organization cannot be made to produce.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-11 21:47:58 -05:00
1 parent 6d2aaba6a6
commit 4e769484df
16 files changed
+1607 -34

No files matched your search

@@ -113,6 +113,7 @@ public class AwsQueryController {
"TagSAMLProvider", "UntagSAMLProvider", "ListSAMLProviderTags",
"GenerateServiceLastAccessedDetails", "GetServiceLastAccessedDetails",
"GetServiceLastAccessedDetailsWithEntities", "ListPoliciesGrantingServiceAccess",
"GenerateOrganizationsAccessReport", "GetOrganizationsAccessReport",
"UploadServerCertificate", "GetServerCertificate", "UpdateServerCertificate",
"DeleteServerCertificate", "ListServerCertificates",
"TagServerCertificate", "UntagServerCertificate", "ListServerCertificateTags",
@@ -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);
}
}
}
@@ -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) {
@@ -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
@@ -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;
}
}
@@ -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()) {
@@ -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);
}
}
@@ -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; }
}