feat(iam): add last-accessed reporting actions (#4488)

Add GenerateServiceLastAccessedDetails, GetServiceLastAccessedDetails,
GetServiceLastAccessedDetailsWithEntities and ListPoliciesGrantingServiceAccess.

Floci records no service-access history, but AWS's "never used" shape keeps
the report and nulls the usage fields rather than emptying the report, so
that is what these reproduce. GetServiceLastAccessedDetails lists every
service the entity could reach through its permissions policies and leaves
LastAuthenticated and TotalAuthenticatedEntities absent for the ones never
used. GetServiceLastAccessedDetailsWithEntities lists the entities that
could have used the reported permissions: a group report yields the group's
users, a policy report the users and roles it is attached to, and a user or
role report that entity. Both lists come from permissions-policy logic,
which Floci can evaluate, so both are computed rather than stubbed; the
usage timestamps are the only part left out.

A report is produced when the job is created and stored with it, matching
AWS, where the Get operations retrieve a report that Generate produced. So
editing the policies afterwards does not change what a completed job
answers, and deleting the entity does not stop a valid JobId resolving.
Generate resolves the whole ARN first, rejecting one whose account is not
the caller's or whose path is not the resolved entity's, so it cannot fall
back to a same-named local identity; AWS-managed policy ARNs carry the
literal "aws" account and are allowed through to the global catalog. An
unknown JobId is NoSuchEntity, Granularity is validated and echoed back as
JobType, and both readers honour MaxItems and Marker.

ListPoliciesGrantingServiceAccess needs no job and no usage history, since
AWS defines it purely over permissions-policy logic. A user contributes its
own managed and inline policies plus those of every group it belongs to,
while a group or role contributes only its own; permissions boundaries are
excluded. Only Allow grants, and Allow with NotAction grants every service
the list does not carve out. It models a Marker but no MaxItems, so only the
former is applied.

Services reachable only through a wildcard or NotAction cannot be
enumerated without a catalog of IAM service namespaces, which is tracked
separately in #4487 and documented.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-26 20:12:27 -04:00
1 parent 0cfb467cac
commit 67437115c5
9 files changed
+1763 -3

No files matched your search

@@ -110,7 +110,9 @@ public class AwsQueryController {
"GetContextKeysForCustomPolicy", "GetContextKeysForPrincipalPolicy",
"ListSAMLProviders", "CreateSAMLProvider", "GetSAMLProvider",
"UpdateSAMLProvider", "DeleteSAMLProvider",
"TagSAMLProvider", "UntagSAMLProvider", "ListSAMLProviderTags"
"TagSAMLProvider", "UntagSAMLProvider", "ListSAMLProviderTags",
"GenerateServiceLastAccessedDetails", "GetServiceLastAccessedDetails",
"GetServiceLastAccessedDetailsWithEntities", "ListPoliciesGrantingServiceAccess"
);
private static final Set<String> AUTOSCALING_ACTIONS = Set.of(
@@ -345,6 +345,118 @@ public class IamPolicyEvaluator {
return keys;
}
/**
* Whether {@code policyDocument} lets its holder reach any action in {@code serviceNamespace},
* backing {@code ListPoliciesGrantingServiceAccess}.
*
* <p>Only {@code Allow} statements grant, and only the permissions-policy logic is applied:
* AWS documents that this operation ignores resource-based policies, ACLs, Organizations
* policies, permissions boundaries and trust policies. Resources and conditions are not
* consulted either, because the question is which policies could grant the service at all,
* not whether a specific call would be authorized.
*
* <p>A document that fails to parse grants nothing, matching {@link #parseAll} elsewhere here.
*/
public boolean grantsServiceAccess(String policyDocument, String serviceNamespace) {
if (policyDocument == null || serviceNamespace == null || serviceNamespace.isBlank()) {
return false;
}
for (PolicyStatement stmt : parseAll(List.of(policyDocument))) {
if (!"Allow".equalsIgnoreCase(stmt.getEffect())) {
continue;
}
if (stmt.getActions() != null) {
for (String pattern : stmt.getActions()) {
if (actionPatternReaches(pattern, serviceNamespace)) {
return true;
}
}
} else if (stmt.getNotActions() != null && !excludesEntirely(stmt.getNotActions(), serviceNamespace)) {
// Allow + NotAction grants everything the list does not carve out, so the
// namespace is still reachable unless the list removes all of it.
return true;
}
}
return false;
}
/**
* The service namespaces {@code policyDocuments} name explicitly in an {@code Allow}, backing
* the service list in {@code GetServiceLastAccessedDetails}.
*
* <p>AWS lists a service the entity could reach even when it was never used, so the list is
* derived from the same permissions-policy logic as {@link #grantsServiceAccess}. Only
* namespaces written out literally can be enumerated: {@code Action: "*"}, a globbed prefix
* like {@code s3*}, and {@code NotAction} all denote a set no policy document enumerates, so
* they are reported through {@code grantsAllServices} for the caller to expand against
* whatever universe of services it knows.
*/
public GrantedServices servicesGrantedBy(List<String> policyDocuments) {
List<String> namespaces = new ArrayList<>();
boolean all = false;
for (PolicyStatement stmt : parseAll(policyDocuments)) {
if (!"Allow".equalsIgnoreCase(stmt.getEffect())) {
continue;
}
if (stmt.getNotActions() != null) {
all = true;
continue;
}
if (stmt.getActions() == null) {
continue;
}
for (String pattern : stmt.getActions()) {
int colon = pattern == null ? -1 : pattern.indexOf(':');
if (colon < 0) {
// "*" grants every service; anything else without a colon is malformed.
all = all || "*".equals(pattern);
continue;
}
String namespace = pattern.substring(0, colon);
if (namespace.indexOf('*') >= 0 || namespace.indexOf('?') >= 0) {
all = true;
} else if (!namespaces.contains(namespace)) {
namespaces.add(namespace);
}
}
}
return new GrantedServices(namespaces, all);
}
/**
* Service namespaces an identity's policies grant: those named literally, plus whether some
* statement grants every service without naming any.
*/
public record GrantedServices(List<String> namespaces, boolean grantsAllServices) {}
/** An action pattern reaches a namespace when its service part matches, whatever the verb is. */
private static boolean actionPatternReaches(String pattern, String serviceNamespace) {
if ("*".equals(pattern)) {
return true;
}
int colon = pattern == null ? -1 : pattern.indexOf(':');
if (colon < 0) {
// Not "service:Action" and not "*"; IAM would reject it, so it grants nothing here.
return false;
}
return globMatches(pattern.substring(0, colon), serviceNamespace);
}
/** True only if the NotAction list removes every action in the namespace, not merely some. */
private static boolean excludesEntirely(List<String> notActions, String serviceNamespace) {
for (String pattern : notActions) {
if ("*".equals(pattern)) {
return true;
}
int colon = pattern == null ? -1 : pattern.indexOf(':');
if (colon >= 0 && "*".equals(pattern.substring(colon + 1))
&& globMatches(pattern.substring(0, colon), serviceNamespace)) {
return true;
}
}
return false;
}
/** 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) {
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.*;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
import io.github.hectorvent.floci.services.iam.model.AccountPasswordPolicy;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
@@ -11,9 +12,10 @@ 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.SAMLProvider;
import io.github.hectorvent.floci.services.iam.model.PolicyVersion;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.github.hectorvent.floci.services.iam.model.SAMLProvider;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedEntity;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedJob;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -24,9 +26,11 @@ import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@@ -49,16 +53,19 @@ public class IamQueryHandler {
private final IamPolicyEvaluator policyEvaluator;
private final AccountResolver accountResolver;
private final SAMLProviderService samlProviderService;
private final ServiceLastAccessedService serviceLastAccessedService;
private final RegionResolver regionResolver;
@Inject
public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator,
AccountResolver accountResolver, SAMLProviderService samlProviderService,
ServiceLastAccessedService serviceLastAccessedService,
RegionResolver regionResolver) {
this.iamService = iamService;
this.policyEvaluator = policyEvaluator;
this.accountResolver = accountResolver;
this.samlProviderService = samlProviderService;
this.serviceLastAccessedService = serviceLastAccessedService;
this.regionResolver = regionResolver;
}
@@ -227,6 +234,13 @@ public class IamQueryHandler {
case "GetContextKeysForCustomPolicy" -> handleGetContextKeysForCustomPolicy(params);
case "GetContextKeysForPrincipalPolicy" -> handleGetContextKeysForPrincipalPolicy(params);
// Last-Accessed Reporting (Access Advisor)
case "GenerateServiceLastAccessedDetails" -> handleGenerateServiceLastAccessedDetails(params, authorization);
case "GetServiceLastAccessedDetails" -> handleGetServiceLastAccessedDetails(params, authorization);
case "GetServiceLastAccessedDetailsWithEntities" ->
handleGetServiceLastAccessedDetailsWithEntities(params, authorization);
case "ListPoliciesGrantingServiceAccess" -> handleListPoliciesGrantingServiceAccess(params, authorization);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.IAM, 400);
};
@@ -1533,6 +1547,436 @@ public class IamQueryHandler {
contextKeyNamesXml(keys))).build();
}
// =========================================================================
// Last-Accessed Reporting (Access Advisor)
// =========================================================================
/**
* Generates the report now and stores it with the job. AWS fixes a report at generation time
* and the readers below only retrieve it, so the service list and the entities are captured
* here rather than recomputed per read. The ARN is resolved first, because AWS answers
* {@code NoSuchEntity} for one that names nothing.
*/
private Response handleGenerateServiceLastAccessedDetails(MultivaluedMap<String, String> params,
String authorization) {
String accountId = accountResolver.resolve(authorization);
String arn = requireParam(params, "Arn");
AccessAdvisorTarget target = resolveAccessAdvisorTarget(accountId, arn);
IamPolicyEvaluator.GrantedServices granted =
policyEvaluator.servicesGrantedBy(target.policyDocuments());
ServiceLastAccessedJob job = serviceLastAccessedService.generate(accountId, arn,
params.getFirst("Granularity"), new TreeSet<>(granted.namespaces()).stream().toList(),
target.entities());
return Response.ok(AwsQueryResponse.envelope("GenerateServiceLastAccessedDetails", AwsNamespaces.IAM,
new XmlBuilder().elem("JobId", job.getJobId()).build())).build();
}
/**
* AWS lists a service the entity could reach even when it was never used, leaving
* {@code LastAuthenticated} and {@code TotalAuthenticatedEntities} null in that case rather
* than omitting the service. Floci records no access, so every entry here is that "no attempt"
* shape, over the service list captured when the job ran.
*/
private Response handleGetServiceLastAccessedDetails(MultivaluedMap<String, String> params,
String authorization) {
ServiceLastAccessedJob job = serviceLastAccessedService.get(
accountResolver.resolve(authorization), requireParam(params, "JobId"));
Page<String> page = paginate(job.getServiceNamespaces(), params);
XmlBuilder xml = new XmlBuilder()
.elem("JobStatus", "COMPLETED")
.elem("JobType", job.getGranularity())
.elem("JobCreationDate", isoDate(job.getJobCreationDate()))
.elem("JobCompletionDate", isoDate(job.getJobCompletionDate()))
.start("ServicesLastAccessed");
for (String namespace : page.items()) {
// ServiceName is a required member and AWS carries a display name ("Amazon S3") that
// Floci has no mapping for, so the namespace stands in for it.
xml.start("member")
.elem("ServiceName", namespace)
.elem("ServiceNamespace", namespace)
.end("member");
}
xml.end("ServicesLastAccessed").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("GetServiceLastAccessedDetails", AwsNamespaces.IAM,
xml.build())).build();
}
/**
* 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
* yields the group's users, a policy report the users and roles it is attached to, and a user
* or role report that entity itself. {@code LastAuthenticated} stays absent throughout, since
* Floci records no access.
*/
private Response handleGetServiceLastAccessedDetailsWithEntities(MultivaluedMap<String, String> params,
String authorization) {
ServiceLastAccessedJob job = serviceLastAccessedService.get(
accountResolver.resolve(authorization), requireParam(params, "JobId"));
String namespace = requireParam(params, "ServiceNamespace");
// The report named the services it covers, so an entity is only reported for one of those.
List<ServiceLastAccessedEntity> reported = job.getServiceNamespaces().contains(namespace)
? job.getEntities() : List.of();
Page<ServiceLastAccessedEntity> page = paginate(reported, params);
XmlBuilder xml = new XmlBuilder()
.elem("JobStatus", "COMPLETED")
.elem("JobCreationDate", isoDate(job.getJobCreationDate()))
.elem("JobCompletionDate", isoDate(job.getJobCompletionDate()))
.start("EntityDetailsList");
for (ServiceLastAccessedEntity entity : page.items()) {
xml.start("member").start("EntityInfo")
.elem("Arn", entity.getArn())
.elem("Name", entity.getName())
.elem("Type", entity.getType())
.elem("Id", entity.getId())
.elem("Path", entity.getPath())
.end("EntityInfo").end("member");
}
xml.end("EntityDetailsList").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("GetServiceLastAccessedDetailsWithEntities",
AwsNamespaces.IAM, xml.build())).build();
}
/**
* Unlike the Access Advisor jobs above, this one needs no usage history and no job: AWS defines
* it purely over permissions-policy logic, so it is answered from the identity's policies as
* they stand.
*/
private Response handleListPoliciesGrantingServiceAccess(MultivaluedMap<String, String> params,
String authorization) {
String accountId = accountResolver.resolve(authorization);
String arn = requireParam(params, "Arn");
List<String> namespaces = getMemberList(params, "ServiceNamespaces");
if (namespaces.isEmpty()) {
throw new AwsException("InvalidInput",
"The request must include at least one service namespace.", 400);
}
List<GrantingPolicy> candidates = policiesForIdentity(accountId, arn);
// The response list carries one entry per requested namespace, so that is what a Marker
// walks through.
Page<String> page = paginateByMarker(namespaces, params);
XmlBuilder xml = new XmlBuilder().start("PoliciesGrantingServiceAccess");
for (String namespace : page.items()) {
xml.start("member").elem("ServiceNamespace", namespace).start("Policies");
for (GrantingPolicy candidate : candidates) {
if (policyEvaluator.grantsServiceAccess(candidate.document(), namespace)) {
xml.start("member")
.elem("PolicyName", candidate.policyName())
.elem("PolicyType", candidate.policyType());
if (candidate.policyArn() != null) {
xml.elem("PolicyArn", candidate.policyArn());
} else {
xml.elem("EntityType", candidate.entityType())
.elem("EntityName", candidate.entityName());
}
xml.end("member");
}
}
xml.end("Policies").end("member");
}
xml.end("PoliciesGrantingServiceAccess").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("ListPoliciesGrantingServiceAccess",
AwsNamespaces.IAM, xml.build())).build();
}
/** One page of a response list, plus the marker that continues it. */
private record Page<T>(List<T> items, boolean truncated, String marker) {}
/**
* Applies {@code MaxItems} and {@code Marker}. The marker is the index the next page starts at,
* which is all a caller is meant to do with it: AWS documents it as opaque and only ever hands
* back one it produced itself.
*/
private <T> Page<T> paginate(List<T> items, MultivaluedMap<String, String> params) {
return paginate(items, params, true);
}
/**
* Marker-only pagination, for {@code ListPoliciesGrantingServiceAccess}: its request models
* {@code Marker} but no {@code MaxItems}, and honouring a member AWS does not declare would be
* inventing one.
*/
private <T> Page<T> paginateByMarker(List<T> items, MultivaluedMap<String, String> params) {
return paginate(items, params, false);
}
private <T> Page<T> paginate(List<T> items, MultivaluedMap<String, String> params, boolean maxItemsModeled) {
// Every input is validated before the bounds check, so a malformed request is rejected
// rather than answered emptily just because the marker happens to sit past the end.
int from = markerIndex(params);
// Validated only when actually supplied: an absent MaxItems means "no limit", which is not
// the same as a limit of zero, and an empty report would otherwise fail its own check.
int limit = items.size();
if (maxItemsModeled) {
String raw = params.getFirst("MaxItems");
if (raw != null && !raw.isBlank()) {
try {
limit = Integer.parseInt(raw.trim());
} catch (NumberFormatException e) {
throw new AwsException("InvalidInput",
"The value " + raw + " at 'maxItems' is not a number.", 400);
}
if (limit < 1) {
throw new AwsException("ValidationError",
"Value at 'maxItems' failed to satisfy constraint: "
+ "Member must have value greater than or equal to 1", 400);
}
}
}
if (from >= items.size()) {
return new Page<>(List.of(), false, null);
}
// Counted from the remaining items rather than added to the offset, so a large MaxItems
// cannot overflow into a negative index.
int to = from + Math.min(limit, items.size() - from);
boolean truncated = to < items.size();
return new Page<>(List.copyOf(items.subList(from, to)), truncated,
truncated ? Integer.toString(to) : null);
}
/** The index a {@code Marker} resumes at. Only a marker this handler produced is valid. */
private int markerIndex(MultivaluedMap<String, String> params) {
String marker = params.getFirst("Marker");
if (marker == null || marker.isBlank()) {
return 0;
}
int index;
try {
index = Integer.parseInt(marker.trim());
} catch (NumberFormatException e) {
throw new AwsException("InvalidInput", "The marker " + marker + " is not valid.", 400);
}
if (index < 0) {
throw new AwsException("InvalidInput", "The marker " + marker + " is not valid.", 400);
}
return index;
}
/**
* One candidate policy for {@code ListPoliciesGrantingServiceAccess}. A managed policy carries
* its ARN; an inline policy has none and is identified by the entity holding it instead.
*/
private record GrantingPolicy(String policyName, String policyType, String policyArn,
String entityType, String entityName, String document) {
static GrantingPolicy managed(IamPolicy policy, String document) {
return new GrantingPolicy(policy.getPolicyName(), "MANAGED", policy.getArn(), null, null, document);
}
static GrantingPolicy inline(String policyName, String entityType, String entityName, String document) {
return new GrantingPolicy(policyName, "INLINE", null, entityType, entityName, document);
}
}
/** What an Access Advisor ARN resolves to: the policies to report on, and who holds them. */
private record AccessAdvisorTarget(List<String> policyDocuments, List<ServiceLastAccessedEntity> entities) {}
/**
* Resolves an Access Advisor ARN to the permissions it stands for and the principals holding
* them. AWS accepts a user, group, role or managed-policy ARN, and reports the entities that
* could have used those permissions: a group's users, a policy's attached users and roles, or
* the named entity itself.
*/
private AccessAdvisorTarget resolveAccessAdvisorTarget(String accountId, String arn) {
IamArn parsed = requireIamArn(accountId, arn);
return switch (parsed.type()) {
case "user" -> {
IamUser user = requireMatchingArn(iamService.getUser(parsed.name()).getArn(), arn,
iamService.getUser(parsed.name()));
yield new AccessAdvisorTarget(identityPolicyDocuments(accountId, arn), List.of(entityOf(user)));
}
case "role" -> {
IamRole role = requireMatchingArn(iamService.getRole(parsed.name()).getArn(), arn,
iamService.getRole(parsed.name()));
yield new AccessAdvisorTarget(identityPolicyDocuments(accountId, arn), List.of(entityOf(role)));
}
case "group" -> {
IamGroup group = requireMatchingArn(iamService.getGroup(parsed.name()).getArn(), arn,
iamService.getGroup(parsed.name()));
List<ServiceLastAccessedEntity> members = new ArrayList<>();
for (String member : group.getUserNames()) {
// A looked-up-by-name member can be gone by now, since the membership list is a
// snapshot: leave that user out rather than failing a report for a group that
// does exist.
iamService.findUser(member).ifPresent(user -> members.add(entityOf(user)));
}
yield new AccessAdvisorTarget(identityPolicyDocuments(accountId, arn), members);
}
case "policy" -> {
IamPolicy policy = iamService.getPolicy(arn);
IamService.PolicyEntities holders = iamService.listEntitiesForPolicy(arn);
// A user reached through an attached group could have used the policy exactly as a
// directly attached one could, so AWS reports it too. Keyed by ARN because a user
// that is both attached directly and a member of an attached group is one entity,
// not two.
Map<String, ServiceLastAccessedEntity> byArn = new LinkedHashMap<>();
for (IamUser user : holders.users()) {
byArn.putIfAbsent(user.getArn(), entityOf(user));
}
for (IamGroup group : holders.groups()) {
for (String member : group.getUserNames()) {
// Same reason as the group branch above: a member named by the snapshot may
// already be deleted, and that must not fail a report for a live policy.
iamService.findUser(member)
.ifPresent(user -> byArn.putIfAbsent(user.getArn(), entityOf(user)));
}
}
for (IamRole role : holders.roles()) {
byArn.putIfAbsent(role.getArn(), entityOf(role));
}
yield new AccessAdvisorTarget(List.of(defaultPolicyDocument(policy)),
List.copyOf(byArn.values()));
}
default -> throw new AwsException("InvalidInput",
"The ARN " + arn + " must identify an IAM user, group, role, or policy.", 400);
};
}
private ServiceLastAccessedEntity entityOf(IamUser user) {
return new ServiceLastAccessedEntity(user.getArn(), user.getUserName(), "USER",
user.getUserId(), user.getPath());
}
private ServiceLastAccessedEntity entityOf(IamRole role) {
return new ServiceLastAccessedEntity(role.getArn(), role.getRoleName(), "ROLE",
role.getRoleId(), role.getPath());
}
/**
* Rejects an ARN whose path does not match the resolved entity's own. A name is unique within
* an account, so the lookup finds the right entity, but an ARN carrying the wrong path names
* nothing in AWS and must not resolve here either.
*/
private <T> T requireMatchingArn(String resolvedArn, String requestedArn, T entity) {
if (!requestedArn.equals(resolvedArn)) {
throw new AwsException("NoSuchEntity", "The ARN " + requestedArn + " cannot be found.", 404);
}
return entity;
}
/** An IAM ARN split into the parts needed to resolve it, with the account already checked. */
private record IamArn(String type, String name) {}
/**
* Parses an IAM ARN and rejects one belonging to another account. Without that check a name is
* looked up in the caller's own account, so an ARN naming a different account would silently
* report a same-named local identity instead.
*/
private IamArn requireIamArn(String accountId, String arn) {
AwsArnUtils.Arn parsed;
try {
parsed = AwsArnUtils.parse(arn);
} catch (RuntimeException e) {
throw new AwsException("InvalidInput", "The ARN " + arn + " is not a valid ARN.", 400);
}
if (!"iam".equals(parsed.service())) {
throw new AwsException("InvalidInput", "The ARN " + arn + " is not a valid IAM ARN.", 400);
}
// An AWS-managed policy carries the literal "aws" in the account field
// (arn:aws:iam::aws:policy/...) and is served from the global catalog, so it is not a
// foreign account and must not be rejected as one.
boolean awsManaged = "aws".equals(parsed.accountId());
if (!awsManaged && parsed.accountId() != null && !parsed.accountId().isEmpty()
&& !parsed.accountId().equals(accountId)) {
throw new AwsException("NoSuchEntity", "The ARN " + arn + " cannot be found.", 404);
}
String resource = parsed.resource();
if (awsManaged && !resource.startsWith("policy/")) {
throw new AwsException("InvalidInput", "The ARN " + arn + " is not a valid IAM ARN.", 400);
}
int slash = resource.indexOf('/');
if (slash < 0) {
throw new AwsException("InvalidInput",
"The ARN " + arn + " must identify an IAM user, group, role, or policy.", 400);
}
return new IamArn(resource.substring(0, slash), resource.substring(resource.lastIndexOf('/') + 1));
}
/**
* The policies AWS says {@code ListPoliciesGrantingServiceAccess} considers for each identity
* type: a user also inherits its groups' policies, while a group or role contributes only its
* own. Permissions boundaries are deliberately excluded, as the documentation requires.
*/
private List<GrantingPolicy> policiesForIdentity(String accountId, String arn) {
IamArn parsed = requireIamArn(accountId, arn);
return switch (parsed.type()) {
case "user" -> {
IamUser user = iamService.getUser(parsed.name());
requireMatchingArn(user.getArn(), arn, user);
List<GrantingPolicy> policies = new ArrayList<>();
collectUserPolicies(user.getUserName(), policies);
for (IamGroup group : iamService.listGroupsForUser(user.getUserName())) {
collectGroupPolicies(group.getGroupName(), policies);
}
yield policies;
}
case "group" -> {
IamGroup group = iamService.getGroup(parsed.name());
requireMatchingArn(group.getArn(), arn, group);
List<GrantingPolicy> policies = new ArrayList<>();
collectGroupPolicies(group.getGroupName(), policies);
yield policies;
}
case "role" -> {
IamRole role = iamService.getRole(parsed.name());
requireMatchingArn(role.getArn(), arn, role);
List<GrantingPolicy> policies = new ArrayList<>();
for (IamPolicy policy : iamService.listAttachedRolePolicies(role.getRoleName(), null)) {
policies.add(GrantingPolicy.managed(policy, defaultPolicyDocument(policy)));
}
for (String policyName : iamService.listRolePolicies(role.getRoleName())) {
policies.add(GrantingPolicy.inline(policyName, "ROLE", role.getRoleName(),
iamService.getRolePolicy(role.getRoleName(), policyName)));
}
yield policies;
}
default -> throw new AwsException("InvalidInput",
"The ARN " + arn + " must identify an IAM user, group, or role.", 400);
};
}
private void collectUserPolicies(String userName, List<GrantingPolicy> policies) {
for (IamPolicy policy : iamService.listAttachedUserPolicies(userName, null)) {
policies.add(GrantingPolicy.managed(policy, defaultPolicyDocument(policy)));
}
for (String policyName : iamService.listUserPolicies(userName)) {
policies.add(GrantingPolicy.inline(policyName, "USER", userName,
iamService.getUserPolicy(userName, policyName)));
}
}
private void collectGroupPolicies(String groupName, List<GrantingPolicy> policies) {
for (IamPolicy policy : iamService.listAttachedGroupPolicies(groupName, null)) {
policies.add(GrantingPolicy.managed(policy, defaultPolicyDocument(policy)));
}
for (String policyName : iamService.listGroupPolicies(groupName)) {
policies.add(GrantingPolicy.inline(policyName, "GROUP", groupName,
iamService.getGroupPolicy(groupName, policyName)));
}
}
/** The documents behind an identity ARN, reusing the scoping rules above. */
private List<String> identityPolicyDocuments(String accountId, String arn) {
List<String> documents = new ArrayList<>();
for (GrantingPolicy candidate : policiesForIdentity(accountId, arn)) {
documents.add(candidate.document());
}
return documents;
}
/** A managed policy grants through whichever version is current, so only that one is read. */
private String defaultPolicyDocument(IamPolicy policy) {
return iamService.getPolicyVersion(policy.getArn(), policy.getDefaultVersionId()).getDocument();
}
private String contextKeyNamesXml(List<String> keys) {
XmlBuilder xml = new XmlBuilder().start("ContextKeyNames");
for (String key : keys) {
@@ -1824,6 +2268,21 @@ public class IamQueryHandler {
return params.getFirst(name);
}
/**
* A required request member. {@link #getParam} returns null for an absent one, which lets a
* malformed request read as a valid empty answer, so anything the model marks required is read
* through here instead.
*/
private String requireParam(MultivaluedMap<String, String> params, String name) {
String value = params.getFirst(name);
if (value == null || value.isBlank()) {
throw new AwsException("ValidationError",
"Value null at '" + Character.toLowerCase(name.charAt(0)) + name.substring(1)
+ "' failed to satisfy constraint: Member must not be null", 400);
}
return value;
}
private int getIntParam(MultivaluedMap<String, String> params, String name, int defaultValue) {
String value = params.getFirst(name);
if (value == null) return defaultValue;
@@ -0,0 +1,96 @@
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;
import io.github.hectorvent.floci.services.iam.model.ServiceLastAccessedJob;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
/**
* Access Advisor job registry behind {@code GenerateServiceLastAccessedDetails} and the two
* {@code GetServiceLastAccessedDetails*} readers.
*
* <p>Floci records no service-access history: nothing populates {@code IamUser.passwordLastUsed},
* and {@code GetAccessKeyLastUsed} already answers with AWS's documented "never used" shape rather
* than inventing usage. A job therefore has no report to compute and is complete the moment it is
* created; the service list it is read back with is derived from the entity's policies by
* {@code IamQueryHandler}, not stored here.
*
* <p>Jobs are never evicted. AWS documents no expiry for a {@code JobId}, so ageing them out would
* mean inventing a retention window and failing a caller holding an ID that AWS would still
* answer, which is a worse trade for an emulator than an unbounded store of small records.
*/
@ApplicationScoped
public class ServiceLastAccessedService {
/** {@code AccessAdvisorUsageGranularityType}; AWS defaults to service-level. */
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;
@Inject
public ServiceLastAccessedService(StorageFactory storageFactory) {
this(storageFactory.create("iam", "iam-service-last-accessed-jobs.json", new TypeReference<>() {}));
}
ServiceLastAccessedService(StorageBackend<String, ServiceLastAccessedJob> jobs) {
this.jobs = jobs;
}
/**
* Records a completed job for {@code arn} together with the report it produced, and returns
* it. The report is computed by the caller and stored here, because AWS fixes a report at
* generation time and the {@code Get*} operations only retrieve it. There is no work left to
* defer, so the creation and completion timestamps are the same instant.
*/
public ServiceLastAccessedJob generate(String accountId, String arn, String granularity,
List<String> serviceNamespaces,
List<ServiceLastAccessedEntity> entities) {
if (granularity != null && !GRANULARITIES.contains(granularity)) {
throw new AwsException("ValidationError",
"Value '" + granularity + "' at 'granularity' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [SERVICE_LEVEL, ACTION_LEVEL]", 400);
}
Instant now = Instant.now();
// jobIDType is min 36 / max 36, which is exactly a UUID string.
ServiceLastAccessedJob job = new ServiceLastAccessedJob(UUID.randomUUID().toString(), arn,
granularity == null ? DEFAULT_GRANULARITY : granularity, now, now,
serviceNamespaces, entities);
putForAccount(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));
}
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);
}
}
}
@@ -0,0 +1,47 @@
package io.github.hectorvent.floci.services.iam.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* One entity recorded in an Access Advisor report, carrying the {@code EntityInfo} members AWS
* requires: {@code Arn}, {@code Name}, {@code Type} and {@code Id}, plus the optional {@code Path}.
*
* <p>Captured when the report is generated rather than resolved on read, so the report a completed
* job returns does not change when the underlying entity is renamed, re-tagged or deleted.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceLastAccessedEntity {
private String arn;
private String name;
private String type;
private String id;
private String path;
public ServiceLastAccessedEntity() {}
public ServiceLastAccessedEntity(String arn, String name, String type, String id, String path) {
this.arn = arn;
this.name = name;
this.type = type;
this.id = id;
this.path = path;
}
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getPath() { return path; }
public void setPath(String path) { this.path = path; }
}
@@ -0,0 +1,73 @@
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 Access Advisor job created by {@code GenerateServiceLastAccessedDetails}, together with the
* report it produced.
*
* <p>AWS generates a report once and the {@code Get*} operations retrieve that report, so the
* answer for a completed job is fixed at generation time. The service namespaces and entities are
* therefore captured here rather than recomputed on read: editing a policy afterwards does not
* change what an already-completed job returns, and deleting the entity does not make a valid
* {@code JobId} stop resolving.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ServiceLastAccessedJob {
private String jobId;
private String arn;
private String granularity;
private Instant jobCreationDate;
private Instant jobCompletionDate;
private List<String> serviceNamespaces = new ArrayList<>();
private List<ServiceLastAccessedEntity> entities = new ArrayList<>();
public ServiceLastAccessedJob() {}
public ServiceLastAccessedJob(String jobId, String arn, String granularity,
Instant jobCreationDate, Instant jobCompletionDate,
List<String> serviceNamespaces,
List<ServiceLastAccessedEntity> entities) {
this.jobId = jobId;
this.arn = arn;
this.granularity = granularity;
this.jobCreationDate = jobCreationDate;
this.jobCompletionDate = jobCompletionDate;
setServiceNamespaces(serviceNamespaces);
setEntities(entities);
}
public String getJobId() { return jobId; }
public void setJobId(String jobId) { this.jobId = jobId; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getGranularity() { return granularity; }
public void setGranularity(String granularity) { this.granularity = granularity; }
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 List<ServiceLastAccessedEntity> getEntities() { return entities; }
public void setEntities(List<ServiceLastAccessedEntity> entities) {
this.entities = entities == null ? new ArrayList<>() : new ArrayList<>(entities);
}
}