diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamTest.java index a2fa3bde66..28aa4766e5 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/IamTest.java @@ -33,6 +33,8 @@ import software.amazon.awssdk.services.iam.model.DeleteSamlProviderRequest; import software.amazon.awssdk.services.iam.model.DeleteUserRequest; import software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest; import software.amazon.awssdk.services.iam.model.DetachUserPolicyRequest; +import software.amazon.awssdk.services.iam.model.GenerateServiceLastAccessedDetailsRequest; +import software.amazon.awssdk.services.iam.model.GenerateServiceLastAccessedDetailsResponse; import software.amazon.awssdk.services.iam.model.GetAccountSummaryResponse; import software.amazon.awssdk.services.iam.model.GetGroupRequest; import software.amazon.awssdk.services.iam.model.GetGroupResponse; @@ -50,6 +52,10 @@ import software.amazon.awssdk.services.iam.model.GetRoleRequest; import software.amazon.awssdk.services.iam.model.GetRoleResponse; import software.amazon.awssdk.services.iam.model.GetSamlProviderRequest; import software.amazon.awssdk.services.iam.model.GetSamlProviderResponse; +import software.amazon.awssdk.services.iam.model.GetServiceLastAccessedDetailsRequest; +import software.amazon.awssdk.services.iam.model.GetServiceLastAccessedDetailsResponse; +import software.amazon.awssdk.services.iam.model.GetServiceLastAccessedDetailsWithEntitiesRequest; +import software.amazon.awssdk.services.iam.model.GetServiceLastAccessedDetailsWithEntitiesResponse; import software.amazon.awssdk.services.iam.model.GetUserRequest; import software.amazon.awssdk.services.iam.model.GetUserResponse; import software.amazon.awssdk.services.iam.model.ListAccessKeysRequest; @@ -64,6 +70,9 @@ import software.amazon.awssdk.services.iam.model.ListGroupsForUserResponse; import software.amazon.awssdk.services.iam.model.ListInstanceProfileTagsRequest; import software.amazon.awssdk.services.iam.model.ListInstanceProfileTagsResponse; import software.amazon.awssdk.services.iam.model.ListInstanceProfilesResponse; +import software.amazon.awssdk.services.iam.model.ListPoliciesGrantingServiceAccessEntry; +import software.amazon.awssdk.services.iam.model.ListPoliciesGrantingServiceAccessRequest; +import software.amazon.awssdk.services.iam.model.ListPoliciesGrantingServiceAccessResponse; import software.amazon.awssdk.services.iam.model.ListRolePoliciesRequest; import software.amazon.awssdk.services.iam.model.ListRolePoliciesResponse; import software.amazon.awssdk.services.iam.model.ListRolesResponse; @@ -799,4 +808,76 @@ class IamTest { .policyArn(AWS_MANAGED_POLICY_PREFIX + "NoSuchManagedPolicyXyz").build())) .isInstanceOf(NoSuchEntityException.class); } + + // ── Last-Accessed Reporting ──────────────────────────────────────── + + @Test + @Order(102) + void generateAndGetServiceLastAccessedDetails() { + GenerateServiceLastAccessedDetailsResponse generated = iam.generateServiceLastAccessedDetails( + GenerateServiceLastAccessedDetailsRequest.builder() + .arn("arn:aws:iam::000000000000:user/" + USER_NAME).build()); + + assertThat(generated.jobId()).hasSize(36); + + GetServiceLastAccessedDetailsResponse details = iam.getServiceLastAccessedDetails( + GetServiceLastAccessedDetailsRequest.builder().jobId(generated.jobId()).build()); + + assertThat(details.jobStatusAsString()).isEqualTo("COMPLETED"); + assertThat(details.jobCreationDate()).isNotNull(); + assertThat(details.jobCompletionDate()).isNotNull(); + // A service the entity could reach is listed even though it was never used, so the + // attempt details are the part that stays null, not the service itself. + assertThat(details.servicesLastAccessed()) + .allSatisfy(service -> { + assertThat(service.serviceNamespace()).isNotBlank(); + assertThat(service.lastAuthenticated()).isNull(); + assertThat(service.totalAuthenticatedEntities()).isNull(); + }); + } + + @Test + @Order(103) + void getServiceLastAccessedDetailsWithEntitiesDescribesReachingEntities() { + GenerateServiceLastAccessedDetailsResponse generated = iam.generateServiceLastAccessedDetails( + GenerateServiceLastAccessedDetailsRequest.builder() + .arn("arn:aws:iam::000000000000:user/" + USER_NAME).build()); + + GetServiceLastAccessedDetailsWithEntitiesResponse details = + iam.getServiceLastAccessedDetailsWithEntities( + GetServiceLastAccessedDetailsWithEntitiesRequest.builder() + .jobId(generated.jobId()).serviceNamespace("s3").build()); + + assertThat(details.jobStatusAsString()).isEqualTo("COMPLETED"); + // Entities are those that could reach the service, so the access time is what stays null. + assertThat(details.entityDetailsList()) + .allSatisfy(entity -> { + assertThat(entity.entityInfo().arn()).isNotBlank(); + assertThat(entity.entityInfo().id()).isNotBlank(); + assertThat(entity.entityInfo().typeAsString()).isIn("USER", "ROLE", "GROUP"); + assertThat(entity.lastAuthenticated()).isNull(); + }); + } + + @Test + @Order(104) + void getServiceLastAccessedDetailsForUnknownJobThrows() { + assertThatThrownBy(() -> iam.getServiceLastAccessedDetails( + GetServiceLastAccessedDetailsRequest.builder() + .jobId("00000000-0000-0000-0000-000000000000").build())) + .isInstanceOf(NoSuchEntityException.class); + } + + @Test + @Order(105) + void listPoliciesGrantingServiceAccessEchoesEachRequestedNamespace() { + ListPoliciesGrantingServiceAccessResponse response = iam.listPoliciesGrantingServiceAccess( + ListPoliciesGrantingServiceAccessRequest.builder() + .arn("arn:aws:iam::000000000000:user/" + USER_NAME) + .serviceNamespaces("s3", "dynamodb").build()); + + assertThat(response.policiesGrantingServiceAccess()) + .extracting(ListPoliciesGrantingServiceAccessEntry::serviceNamespace) + .containsExactly("s3", "dynamodb"); + } } diff --git a/docs/services/iam.md b/docs/services/iam.md index 8baab1aa44..0ced23f51c 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -338,6 +338,69 @@ top-level `EvalDecision` is populated. `ContextEntries.member.N.ContextKeyType` read; the comparison is driven entirely by the policy's own condition operator (`Bool`, `NumericEquals`, `DateEquals`, and so on), not by the declared type. +### Last-Accessed Reporting + +| Action | Description | +|--------|-------------| +| GenerateServiceLastAccessedDetails | Starts an Access Advisor job for a user, group, role or managed policy and returns its job ID. | +| 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. | + +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 +inventing one. That shape is what these actions reproduce: AWS lists every service an entity could +reach through its permissions policies, and for a service with no access attempt it leaves +`LastAuthenticated` and `TotalAuthenticatedEntities` null rather than dropping the service. So +`GetServiceLastAccessedDetails` returns a real, policy-derived `ServicesLastAccessed` list in which +every entry is that "no attempt" shape. The missing piece is the usage timestamps, not the list. + +Only the namespaces a policy names literally can be enumerated. An `Action` of `*`, a globbed +prefix such as `s3*`, and any `NotAction` all denote a set no policy document spells out, and Floci +has no catalog of every AWS service namespace to expand them against, so services reachable only +through one of those are absent from the list. `ServiceName` is a required member that AWS fills +with a display name (`Amazon S3`); Floci has no such mapping and repeats the namespace instead. + +`GetServiceLastAccessedDetailsWithEntities` is policy-derived in the same way. AWS reports the +entities that *could have used* the reported permissions to reach a service, so a group report +lists the group's users, a policy report lists the users and roles the policy is attached to plus +the users of any group it is attached to, and a user or role report lists that entity. A user +reachable by more than one of those paths is listed once. Entities are omitted when the reported permissions do not +grant the requested service at all. `LastAuthenticated` is absent on every entry, since that is +the part Floci does not record. + +`GenerateServiceLastAccessedDetails` resolves the ARN first and returns `NoSuchEntity` for one that +names nothing, rather than handing out a job ID that could never be meaningful. That resolution +checks the whole ARN: an ARN whose account is not the caller's, or whose path is not the resolved +entity's own, names no entity and is rejected rather than falling back to a same-named local one. A +job belongs to the account that created it, an unknown `JobId` is `NoSuchEntity`, and `Granularity` +is validated against `SERVICE_LEVEL`/`ACTION_LEVEL` and echoed back as `JobType`. + +The report is produced when the job is created and stored with it, matching AWS, where +`GenerateServiceLastAccessedDetails` produces a report and the `Get*` operations retrieve that one. +So a completed job keeps answering what it answered first: editing the policies afterwards does not +change it, and deleting the entity it covers does not stop a valid `JobId` from resolving. There is +nothing left to compute asynchronously, so a job is complete when created and its creation and +completion timestamps are the same instant. Jobs are kept for the life of the store: AWS documents +no expiry for a `JobId`, so ageing them out would mean inventing a retention window and failing a +caller holding an ID that AWS would still answer. + +Both readers honour `MaxItems` and `Marker` and report `IsTruncated` truthfully, returning a +`Marker` only when a page remains. This differs from the rest of this page, where pagination inputs +are accepted and ignored; these actions apply them rather than inherit that gap. + +`ListPoliciesGrantingServiceAccess` is not an Access Advisor job and needs no usage history: AWS +defines it purely over permissions-policy logic, so it is answered from real policy content. It +follows AWS's documented scoping, where 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. Managed +policies are reported with their ARN and their current default version is the one read; inline +policies have no ARN and are identified by the entity holding them. Only `Allow` grants, so a +Deny-only policy is not listed, and an `Allow` with `NotAction` grants every service the list does +not carve out. Permissions boundaries are excluded, as the operation's documentation requires, and +resource-based policies, ACLs, Organizations policies and trust policies are not consulted. +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. + ### Account | Action | Description | 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 09a548f200..f6bd7a60db 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 @@ -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 AUTOSCALING_ACTIONS = Set.of( 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 087982fa46..4c8d10ab70 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 @@ -345,6 +345,118 @@ public class IamPolicyEvaluator { return keys; } + /** + * Whether {@code policyDocument} lets its holder reach any action in {@code serviceNamespace}, + * backing {@code ListPoliciesGrantingServiceAccess}. + * + *

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. + * + *

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}. + * + *

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 policyDocuments) { + List 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 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 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 values, List 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 52fcfb3d7e..a9d5bf938b 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 @@ -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 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 params, + String authorization) { + ServiceLastAccessedJob job = serviceLastAccessedService.get( + accountResolver.resolve(authorization), requireParam(params, "JobId")); + Page 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 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 reported = job.getServiceNamespaces().contains(namespace) + ? job.getEntities() : List.of(); + Page 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 params, + String authorization) { + String accountId = accountResolver.resolve(authorization); + String arn = requireParam(params, "Arn"); + List namespaces = getMemberList(params, "ServiceNamespaces"); + if (namespaces.isEmpty()) { + throw new AwsException("InvalidInput", + "The request must include at least one service namespace.", 400); + } + List candidates = policiesForIdentity(accountId, arn); + // The response list carries one entry per requested namespace, so that is what a Marker + // walks through. + Page 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(List 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 Page paginate(List items, MultivaluedMap 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 Page paginateByMarker(List items, MultivaluedMap params) { + return paginate(items, params, false); + } + + private Page paginate(List items, MultivaluedMap 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 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 policyDocuments, List 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 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 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 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 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 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 policies = new ArrayList<>(); + collectGroupPolicies(group.getGroupName(), policies); + yield policies; + } + case "role" -> { + IamRole role = iamService.getRole(parsed.name()); + requireMatchingArn(role.getArn(), arn, role); + List 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 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 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 identityPolicyDocuments(String accountId, String arn) { + List 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 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 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 params, String name, int defaultValue) { String value = params.getFirst(name); if (value == null) return defaultValue; 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 new file mode 100644 index 0000000000..1dcc40f541 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedService.java @@ -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. + * + *

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. + * + *

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 GRANULARITIES = Set.of("SERVICE_LEVEL", "ACTION_LEVEL"); + private static final String DEFAULT_GRANULARITY = "SERVICE_LEVEL"; + + private final StorageBackend jobs; + + @Inject + public ServiceLastAccessedService(StorageFactory storageFactory) { + this(storageFactory.create("iam", "iam-service-last-accessed-jobs.json", new TypeReference<>() {})); + } + + ServiceLastAccessedService(StorageBackend 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 serviceNamespaces, + List 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 find(String accountId, String jobId) { + if (jobId == null || jobId.isBlank()) { + return Optional.empty(); + } + if (jobs instanceof AccountAwareStorageBackend aware) { + return aware.getForAccount(accountId, jobId); + } + return jobs.get(jobId); + } + + private void putForAccount(String accountId, ServiceLastAccessedJob job) { + if (jobs instanceof AccountAwareStorageBackend aware) { + aware.putForAccount(accountId, job.getJobId(), job); + } else { + jobs.put(job.getJobId(), job); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/ServiceLastAccessedEntity.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/ServiceLastAccessedEntity.java new file mode 100644 index 0000000000..4be38eb588 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/ServiceLastAccessedEntity.java @@ -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}. + * + *

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; } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/ServiceLastAccessedJob.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/ServiceLastAccessedJob.java new file mode 100644 index 0000000000..c84dbc7c33 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/ServiceLastAccessedJob.java @@ -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. + * + *

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 serviceNamespaces = new ArrayList<>(); + private List entities = new ArrayList<>(); + + public ServiceLastAccessedJob() {} + + public ServiceLastAccessedJob(String jobId, String arn, String granularity, + Instant jobCreationDate, Instant jobCompletionDate, + List serviceNamespaces, + List 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 getServiceNamespaces() { return serviceNamespaces; } + + public void setServiceNamespaces(List serviceNamespaces) { + this.serviceNamespaces = serviceNamespaces == null ? new ArrayList<>() : new ArrayList<>(serviceNamespaces); + } + + public List getEntities() { return entities; } + + public void setEntities(List entities) { + this.entities = entities == null ? new ArrayList<>() : new ArrayList<>(entities); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java new file mode 100644 index 0000000000..4de6426402 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java @@ -0,0 +1,827 @@ +package io.github.hectorvent.floci.services.iam; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Verifies the Access Advisor job operations and ListPoliciesGrantingServiceAccess. + * + *

Floci records no service-access history, so no report here carries an access timestamp. The + * service list itself is real, though: AWS lists a service the entity could reach even when it was + * never used, and that list comes from permissions-policy logic, which Floci can evaluate. So the + * assertions cover both halves, the policy-derived list and the absent attempt details. + * + *

IAM state is shared across the suite, so every test names its own entities uniquely. + */ +@QuarkusTest +class ServiceLastAccessedIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request"; + + private static final String S3_POLICY = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + + private static final String TRUST_POLICY = + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},\"Action\":\"sts:AssumeRole\"}]}"; + + private static RequestSpecification iam(String action) { + return given().header("Authorization", IAM_AUTH).formParam("Action", action); + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } + + private static String createUser(String userName) { + iam("CreateUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200); + return "arn:aws:iam::000000000000:user/" + userName; + } + + private static String generateJobFor(String arn) { + return iam("GenerateServiceLastAccessedDetails").formParam("Arn", arn) + .when().post("/").then().statusCode(200) + .extract().path("GenerateServiceLastAccessedDetailsResponse." + + "GenerateServiceLastAccessedDetailsResult.JobId"); + } + + @Test + void generateServiceLastAccessedDetailsReturnsAJobIdOfTheModeledLength() { + String arn = createUser("laa-gen-" + suffix()); + + String jobId = generateJobFor(arn); + + // 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); + } + + @Test + void generateServiceLastAccessedDetailsAcceptsRoleGroupAndPolicyArns() { + String tag = suffix(); + String roleName = "laa-role-" + tag; + iam("CreateRole").formParam("RoleName", roleName).formParam("Path", "/") + .formParam("AssumeRolePolicyDocument", TRUST_POLICY) + .when().post("/").then().statusCode(200); + String groupName = "laa-group-" + tag; + iam("CreateGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200); + String policyArn = iam("CreatePolicy").formParam("PolicyName", "laa-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + + for (String arn : new String[] { + "arn:aws:iam::000000000000:role/" + roleName, + "arn:aws:iam::000000000000:group/" + groupName, + policyArn }) { + assertEquals(36, generateJobFor(arn).length(), "expected a job id for " + arn); + } + } + + @Test + void generateServiceLastAccessedDetailsForAnUnknownEntityReturnsNoSuchEntity() { + iam("GenerateServiceLastAccessedDetails") + .formParam("Arn", "arn:aws:iam::000000000000:user/no-such-user-" + suffix()) + .when().post("/").then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @Test + void generateServiceLastAccessedDetailsRejectsANonIamArn() { + iam("GenerateServiceLastAccessedDetails") + .formParam("Arn", "arn:aws:s3:::some-bucket") + .when().post("/").then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + + @Test + void generateServiceLastAccessedDetailsRejectsAnUnmodeledGranularity() { + String arn = createUser("laa-granularity-" + suffix()); + + iam("GenerateServiceLastAccessedDetails").formParam("Arn", arn) + .formParam("Granularity", "MINUTE_LEVEL") + .when().post("/").then() + .statusCode(400) + .body(containsString("ValidationError")); + } + + /** + * AWS lists a service the entity could reach even when it was never used, leaving the + * attempt details null rather than dropping the service, so the list reflects the entity's + * policies while the timestamps stay absent. + */ + @Test + void getServiceLastAccessedDetailsListsGrantedServicesWithNoAttemptDetails() { + String tag = suffix(); + String userName = "laa-get-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-get-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + String jobId = generateJobFor(arn); + + String body = iam("GetServiceLastAccessedDetails").formParam("JobId", jobId) + .when().post("/").then() + .statusCode(200) + .body("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.JobStatus", + equalTo("COMPLETED")) + .body("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.JobType", + equalTo("SERVICE_LEVEL")) + .body(containsString("s3")) + .extract().asString(); + + // Required members must be present even though nothing was ever accessed. + assertTrue(body.contains("") && body.contains(""), + "expected both job timestamps in: " + body); + // Nothing accessed the service, so AWS leaves these two out entirely. + assertTrue(!body.contains(""), + "no access is recorded, so LastAuthenticated must be absent, in: " + body); + assertTrue(!body.contains(""), + "no access is recorded, so TotalAuthenticatedEntities must be absent, in: " + body); + } + + /** A service the entity's policies never mention is not part of its report. */ + @Test + void getServiceLastAccessedDetailsOmitsServicesTheEntityCannotReach() { + String tag = suffix(); + String userName = "laa-scope-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-scope-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetails").formParam("JobId", generateJobFor(arn)) + .when().post("/").then() + .statusCode(200) + .body(containsString("s3")) + .body(not(containsString("dynamodb"))); + } + + /** A managed-policy ARN reports on that policy's own document, not on any identity. */ + @Test + void getServiceLastAccessedDetailsForAPolicyArnUsesThatPolicysDocument() { + String tag = suffix(); + String policyArn = iam("CreatePolicy").formParam("PolicyName", "laa-policy-report-" + tag) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"dynamodb:GetItem\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + + iam("GetServiceLastAccessedDetails").formParam("JobId", generateJobFor(policyArn)) + .when().post("/").then() + .statusCode(200) + .body(containsString("dynamodb")); + } + + @Test + void getServiceLastAccessedDetailsEchoesTheRequestedGranularity() { + String arn = createUser("laa-action-level-" + suffix()); + String jobId = iam("GenerateServiceLastAccessedDetails").formParam("Arn", arn) + .formParam("Granularity", "ACTION_LEVEL") + .when().post("/").then().statusCode(200) + .extract().path("GenerateServiceLastAccessedDetailsResponse." + + "GenerateServiceLastAccessedDetailsResult.JobId"); + + iam("GetServiceLastAccessedDetails").formParam("JobId", jobId) + .when().post("/").then() + .statusCode(200) + .body("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.JobType", + equalTo("ACTION_LEVEL")); + } + + @Test + void getServiceLastAccessedDetailsForAnUnknownJobReturnsNoSuchEntity() { + iam("GetServiceLastAccessedDetails") + .formParam("JobId", "00000000-0000-0000-0000-000000000000") + .when().post("/").then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + /** + * AWS reports the entities that could have used the permissions to reach the service, which is + * policy-derived, so a user report names that user with no access timestamp. + */ + @Test + void getServiceLastAccessedDetailsWithEntitiesNamesTheReportedUser() { + String tag = suffix(); + String userName = "laa-entities-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-entities-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + + String body = iam("GetServiceLastAccessedDetailsWithEntities") + .formParam("JobId", generateJobFor(arn)) + .formParam("ServiceNamespace", "s3") + .when().post("/").then() + .statusCode(200) + .body("GetServiceLastAccessedDetailsWithEntitiesResponse." + + "GetServiceLastAccessedDetailsWithEntitiesResult.JobStatus", equalTo("COMPLETED")) + .body(containsString("" + userName + "")) + .body(containsString("USER")) + .extract().asString(); + + assertTrue(!body.contains(""), + "no access is recorded, so LastAuthenticated must be absent, in: " + body); + } + + /** A group report names the group's users, not the group, since users hold its permissions. */ + @Test + void getServiceLastAccessedDetailsWithEntitiesForAGroupNamesItsUsers() { + String tag = suffix(); + String groupName = "laa-ent-group-" + tag; + String userName = "laa-ent-member-" + tag; + createUser(userName); + iam("CreateGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200); + iam("AddUserToGroup").formParam("GroupName", groupName).formParam("UserName", userName) + .when().post("/").then().statusCode(200); + iam("PutGroupPolicy").formParam("GroupName", groupName) + .formParam("PolicyName", "laa-ent-group-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetailsWithEntities") + .formParam("JobId", generateJobFor("arn:aws:iam::000000000000:group/" + groupName)) + .formParam("ServiceNamespace", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString("" + userName + "")) + .body(containsString("USER")); + } + + /** A policy report names the users and roles the policy is attached to. */ + @Test + void getServiceLastAccessedDetailsWithEntitiesForAPolicyNamesItsAttachedEntities() { + String tag = suffix(); + String userName = "laa-ent-attached-" + tag; + createUser(userName); + String policyArn = iam("CreatePolicy").formParam("PolicyName", "laa-ent-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + iam("AttachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetailsWithEntities") + .formParam("JobId", generateJobFor(policyArn)) + .formParam("ServiceNamespace", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString("" + userName + "")); + } + + /** + * A user reached through a group the policy is attached to could have used that policy just as + * a directly attached user could, so AWS reports it as well. + */ + @Test + void getServiceLastAccessedDetailsWithEntitiesForAPolicyNamesUsersOfAnAttachedGroup() { + String tag = suffix(); + String userName = "laa-ent-viagroup-user-" + tag; + createUser(userName); + String groupName = "laa-ent-viagroup-" + tag; + iam("CreateGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200); + iam("AddUserToGroup").formParam("GroupName", groupName).formParam("UserName", userName) + .when().post("/").then().statusCode(200); + String policyArn = iam("CreatePolicy").formParam("PolicyName", "laa-ent-viagroup-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + // Attached to the group only, never to the user directly. + iam("AttachGroupPolicy").formParam("GroupName", groupName).formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetailsWithEntities") + .formParam("JobId", generateJobFor(policyArn)) + .formParam("ServiceNamespace", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString("" + userName + "")) + .body(containsString("USER")); + } + + /** A user both attached directly and a member of an attached group is one entity, not two. */ + @Test + void getServiceLastAccessedDetailsWithEntitiesDoesNotRepeatAUserReachedTwice() { + String tag = suffix(); + String userName = "laa-ent-dup-user-" + tag; + createUser(userName); + String groupName = "laa-ent-dup-group-" + tag; + iam("CreateGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200); + iam("AddUserToGroup").formParam("GroupName", groupName).formParam("UserName", userName) + .when().post("/").then().statusCode(200); + String policyArn = iam("CreatePolicy").formParam("PolicyName", "laa-ent-dup-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + iam("AttachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200); + iam("AttachGroupPolicy").formParam("GroupName", groupName).formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200); + + String body = iam("GetServiceLastAccessedDetailsWithEntities") + .formParam("JobId", generateJobFor(policyArn)) + .formParam("ServiceNamespace", "s3") + .when().post("/").then().statusCode(200).extract().asString(); + + int first = body.indexOf("" + userName + ""); + assertTrue(first >= 0, "expected the user to be reported at all, in: " + body); + assertEquals(-1, body.indexOf("" + userName + "", first + 1), + "expected the user reported once, not once per path that reaches it, in: " + body); + } + + /** A service the reported permissions never grant yields no entities at all. */ + @Test + void getServiceLastAccessedDetailsWithEntitiesOmitsEntitiesForAnUngrantedService() { + String tag = suffix(); + String userName = "laa-ent-ungranted-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-ent-ungranted-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetailsWithEntities") + .formParam("JobId", generateJobFor(arn)) + .formParam("ServiceNamespace", "dynamodb") + .when().post("/").then() + .statusCode(200) + .body(not(containsString("" + userName + ""))); + } + + @Test + void getServiceLastAccessedDetailsWithEntitiesForAnUnknownJobReturnsNoSuchEntity() { + iam("GetServiceLastAccessedDetailsWithEntities") + .formParam("JobId", "00000000-0000-0000-0000-000000000000") + .formParam("ServiceNamespace", "s3") + .when().post("/").then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @Test + void listPoliciesGrantingServiceAccessReturnsAnAttachedManagedPolicy() { + String tag = suffix(); + String userName = "laa-managed-" + tag; + String arn = createUser(userName); + String policyArn = iam("CreatePolicy").formParam("PolicyName", "laa-granting-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + iam("AttachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", policyArn) + .when().post("/").then().statusCode(200); + + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString("s3")) + .body(containsString("MANAGED")) + .body(containsString(policyArn)); + } + + @Test + void listPoliciesGrantingServiceAccessIdentifiesAnInlinePolicyByItsEntityNotAnArn() { + String tag = suffix(); + String userName = "laa-inline-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-inline-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + + String body = iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString("INLINE")) + .body(containsString("USER")) + .body(containsString("" + userName + "")) + .extract().asString(); + + // Inline policies have no ARN, so none must be emitted for one. + assertTrue(!body.contains(""), "inline policies carry no ARN, in: " + body); + } + + @Test + void listPoliciesGrantingServiceAccessIncludesPoliciesInheritedFromAUsersGroup() { + String tag = suffix(); + String userName = "laa-inherit-" + tag; + String arn = createUser(userName); + String groupName = "laa-inherit-group-" + tag; + iam("CreateGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200); + iam("AddUserToGroup").formParam("GroupName", groupName).formParam("UserName", userName) + .when().post("/").then().statusCode(200); + iam("PutGroupPolicy").formParam("GroupName", groupName) + .formParam("PolicyName", "laa-group-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString("GROUP")) + .body(containsString("" + groupName + "")); + } + + /** AWS: for a group ARN, a policy attached to one of its users is not included. */ + @Test + void listPoliciesGrantingServiceAccessForAGroupExcludesItsUsersOwnPolicies() { + String tag = suffix(); + String userName = "laa-groupscope-user-" + tag; + createUser(userName); + String groupName = "laa-groupscope-" + tag; + iam("CreateGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200); + iam("AddUserToGroup").formParam("GroupName", groupName).formParam("UserName", userName) + .when().post("/").then().statusCode(200); + String userPolicyName = "laa-groupscope-userpolicy-" + tag; + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", userPolicyName) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + + // Positive control first: the policy really is discoverable through the user's own ARN, + // so its absence from the group's answer below means scoping, not a missing policy. + iam("ListPoliciesGrantingServiceAccess") + .formParam("Arn", "arn:aws:iam::000000000000:user/" + userName) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString(userPolicyName)); + + iam("ListPoliciesGrantingServiceAccess") + .formParam("Arn", "arn:aws:iam::000000000000:group/" + groupName) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(200) + .body(not(containsString(userPolicyName))); + } + + @Test + void listPoliciesGrantingServiceAccessReturnsAnEmptyPolicyListForAnUngrantedService() { + String tag = suffix(); + String userName = "laa-ungranted-" + tag; + String arn = createUser(userName); + String policyName = "laa-ungranted-policy-" + tag; + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", policyName) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + + // The namespace is still echoed back, with no policies under it. + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "dynamodb") + .when().post("/").then() + .statusCode(200) + .body(containsString("dynamodb")) + .body(not(containsString(policyName))); + } + + /** {@code Allow} with {@code NotAction} grants everything it does not carve out. */ + @Test + void listPoliciesGrantingServiceAccessHonoursNotActionGrants() { + String tag = suffix(); + String userName = "laa-notaction-" + tag; + String arn = createUser(userName); + String granted = "laa-notaction-granted-" + tag; + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", granted) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"NotAction\":\"iam:*\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + + // s3 is not carved out, so the policy still grants it. + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString(granted)); + + // iam is carved out entirely, so it does not. + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "iam") + .when().post("/").then() + .statusCode(200) + .body(not(containsString(granted))); + } + + /** A Deny-only policy grants nothing, so it is not a policy "granting service access". */ + @Test + void listPoliciesGrantingServiceAccessExcludesADenyOnlyPolicy() { + String tag = suffix(); + String userName = "laa-deny-" + tag; + String arn = createUser(userName); + String denyName = "laa-deny-policy-" + tag; + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", denyName) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\"," + + "\"Action\":\"s3:*\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(200) + .body(not(containsString(denyName))); + } + + @Test + void listPoliciesGrantingServiceAccessRequiresAtLeastOneServiceNamespace() { + String arn = createUser("laa-nonamespace-" + suffix()); + + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .when().post("/").then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + + + /** + * A name is unique within an account, so a lookup by name alone would resolve a same-named + * local identity for an ARN naming a different account. The account in the ARN has to be + * checked, or one account's report answers for another's ARN. + */ + @Test + void generateServiceLastAccessedDetailsRejectsAnArnFromAnotherAccount() { + String userName = "laa-cross-account-" + suffix(); + createUser(userName); + + iam("GenerateServiceLastAccessedDetails") + .formParam("Arn", "arn:aws:iam::999999999999:user/" + userName) + .when().post("/").then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + /** An ARN carrying a path the entity does not have names nothing in AWS. */ + @Test + void generateServiceLastAccessedDetailsRejectsAnArnWithTheWrongPath() { + String userName = "laa-wrong-path-" + suffix(); + createUser(userName); + + iam("GenerateServiceLastAccessedDetails") + .formParam("Arn", "arn:aws:iam::000000000000:user/engineering/" + userName) + .when().post("/").then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @Test + void listPoliciesGrantingServiceAccessRejectsAnArnFromAnotherAccount() { + String userName = "laa-cross-list-" + suffix(); + createUser(userName); + + iam("ListPoliciesGrantingServiceAccess") + .formParam("Arn", "arn:aws:iam::999999999999:user/" + userName) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + /** + * AWS fixes a report when the job runs and the readers only retrieve it, so editing the + * policies afterwards must not change what an already-completed job answers. + */ + @Test + void aCompletedReportDoesNotChangeWhenThePoliciesDo() { + String tag = suffix(); + String userName = "laa-snapshot-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-snapshot-policy-" + tag) + .formParam("PolicyDocument", S3_POLICY) + .when().post("/").then().statusCode(200); + String jobId = generateJobFor(arn); + + // Replace the policy so the live answer would now be dynamodb rather than s3. + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-snapshot-policy-" + tag) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"dynamodb:GetItem\",\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetails").formParam("JobId", jobId) + .when().post("/").then() + .statusCode(200) + .body(containsString("s3")) + .body(not(containsString("dynamodb"))); + } + + /** Deleting the entity must not make an already-issued, valid JobId stop resolving. */ + @Test + void aCompletedReportStillResolvesAfterItsEntityIsDeleted() { + String userName = "laa-deleted-entity-" + suffix(); + String arn = createUser(userName); + String jobId = generateJobFor(arn); + + iam("DeleteUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetails").formParam("JobId", jobId) + .when().post("/").then() + .statusCode(200) + .body("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.JobStatus", + equalTo("COMPLETED")); + } + + /** MaxItems bounds the page and the Marker continues it, rather than everything at once. */ + @Test + void getServiceLastAccessedDetailsHonoursMaxItemsAndMarker() { + String tag = suffix(); + String userName = "laa-paging-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-paging-policy-" + tag) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":[\"s3:GetObject\",\"dynamodb:GetItem\"],\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + String jobId = generateJobFor(arn); + + // Namespaces are stored sorted, so the first page is dynamodb and the second s3. + String marker = iam("GetServiceLastAccessedDetails") + .formParam("JobId", jobId).formParam("MaxItems", "1") + .when().post("/").then() + .statusCode(200) + .body(containsString("dynamodb")) + .body(not(containsString("s3"))) + .body("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.IsTruncated", + equalTo("true")) + .extract().path("GetServiceLastAccessedDetailsResponse." + + "GetServiceLastAccessedDetailsResult.Marker"); + + iam("GetServiceLastAccessedDetails") + .formParam("JobId", jobId).formParam("Marker", marker) + .when().post("/").then() + .statusCode(200) + .body(containsString("s3")) + .body(not(containsString("dynamodb"))) + .body("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.IsTruncated", + equalTo("false")); + } + + @Test + void getServiceLastAccessedDetailsWithEntitiesWithoutAServiceNamespaceIsRejected() { + String arn = createUser("laa-missing-ns-" + suffix()); + + iam("GetServiceLastAccessedDetailsWithEntities") + .formParam("JobId", generateJobFor(arn)) + .when().post("/").then() + .statusCode(400) + .body(containsString("ValidationError")); + } + + /** A malformed request stays malformed even when the marker sits past the end of the list. */ + @Test + void getServiceLastAccessedDetailsRejectsMaxItemsBelowOneEvenPastTheEnd() { + String arn = createUser("laa-maxitems-" + suffix()); + String jobId = generateJobFor(arn); + + iam("GetServiceLastAccessedDetails") + .formParam("JobId", jobId).formParam("Marker", "999").formParam("MaxItems", "0") + .when().post("/").then() + .statusCode(400) + .body(containsString("ValidationError")); + } + + @Test + void getServiceLastAccessedDetailsRejectsANegativeMarker() { + String arn = createUser("laa-neg-marker-" + suffix()); + + iam("GetServiceLastAccessedDetails") + .formParam("JobId", generateJobFor(arn)).formParam("Marker", "-1") + .when().post("/").then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + + /** ListPoliciesGrantingServiceAccess models a Marker, so it walks the namespace entries too. */ + @Test + void listPoliciesGrantingServiceAccessHonoursItsMarker() { + String arn = createUser("laa-list-marker-" + suffix()); + + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "s3") + .formParam("ServiceNamespaces.member.2", "dynamodb") + .formParam("Marker", "1") + .when().post("/").then() + .statusCode(200) + .body(containsString("dynamodb")) + .body(not(containsString("s3"))); + } + + @Test + void listPoliciesGrantingServiceAccessRejectsAMalformedMarker() { + String arn = createUser("laa-list-bad-marker-" + suffix()); + + iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "s3") + .formParam("Marker", "not-a-marker") + .when().post("/").then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + + /** + * An AWS-managed policy ARN carries the literal "aws" in its account field, which is the + * global catalog rather than a foreign account, so the account check must let it through. + */ + @Test + void generateServiceLastAccessedDetailsAcceptsAnAwsManagedPolicyArn() { + String jobId = generateJobFor("arn:aws:iam::aws:policy/ReadOnlyAccess"); + + assertEquals(36, jobId.length(), "expected a job id for an AWS-managed policy"); + iam("GetServiceLastAccessedDetails").formParam("JobId", jobId) + .when().post("/").then() + .statusCode(200) + .body("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.JobStatus", + equalTo("COMPLETED")); + } + + /** A huge MaxItems must page, not overflow into a negative index. */ + @Test + void getServiceLastAccessedDetailsSurvivesAnEnormousMaxItems() { + String tag = suffix(); + String userName = "laa-overflow-" + tag; + String arn = createUser(userName); + iam("PutUserPolicy").formParam("UserName", userName) + .formParam("PolicyName", "laa-overflow-policy-" + tag) + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":[\"s3:GetObject\",\"dynamodb:GetItem\"],\"Resource\":\"*\"}]}") + .when().post("/").then().statusCode(200); + + iam("GetServiceLastAccessedDetails") + .formParam("JobId", generateJobFor(arn)) + .formParam("Marker", "1") + .formParam("MaxItems", Integer.toString(Integer.MAX_VALUE)) + .when().post("/").then() + .statusCode(200) + .body(containsString("s3")); + } + + /** An empty report is a valid answer, not a request that fails its own page-size check. */ + @Test + void getServiceLastAccessedDetailsReturnsAnEmptyReportWithoutMaxItems() { + String arn = createUser("laa-empty-report-" + suffix()); + + iam("GetServiceLastAccessedDetails").formParam("JobId", generateJobFor(arn)) + .when().post("/").then() + .statusCode(200) + .body("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.IsTruncated", + equalTo("false")); + } + + @Test + void getServiceLastAccessedDetailsWithoutAJobIdIsRejected() { + iam("GetServiceLastAccessedDetails") + .when().post("/").then() + .statusCode(400) + .body(containsString("ValidationError")); + } + + /** + * Without an Authorization header there is no credential scope to resolve, so the request + * reaches IAM only through AwsQueryController's action-name fallback. This pins the entries + * added there for these actions. + */ + @Test + void lastAccessedActionsRouteToIamWithoutACredentialScope() { + String arn = createUser("laa-unsigned-" + suffix()); + + given().formParam("Action", "GenerateServiceLastAccessedDetails") + .formParam("Arn", arn) + .when().post("/").then() + .statusCode(200) + .body(containsString("GenerateServiceLastAccessedDetailsResponse")); + + given().formParam("Action", "ListPoliciesGrantingServiceAccess") + .formParam("Arn", arn) + .formParam("ServiceNamespaces.member.1", "s3") + .when().post("/").then() + .statusCode(200) + .body(containsString("ListPoliciesGrantingServiceAccessResponse")); + } +}