mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(iam): generate and read the Organizations access report (#5467)
GenerateOrganizationsAccessReport and GetOrganizationsAccessReport answered
UnsupportedOperation, which is not a reply any SDK models. They are the Access
Advisor job shape over a different question, and everything the question needs
was already here: an Organizations tree with roots, OUs, accounts and SCPs, a
policy evaluator, and a job model whose report is fixed at generation time.
The report is the services the service control policies along an entity path
leave reachable. The path names the organization, its root, and the OUs or
account below it, and the SCPs attached to each of those are read from
Organizations and evaluated. Only SCP logic applies, which the reference is
explicit about: identity policies, resource policies, ACLs, permissions
boundaries and trust policies play no part in this data.
Attached SCPs are a union within one level and the levels are intersected, so a
service survives only where every level allows it. That cannot be answered a
namespace at a time, because a service is reachable only while some action in it
survives the whole chain: two levels allowing single disjoint actions,
s3:GetObject under s3:PutObject, leave no S3 action at all, and a Deny on the one
action a level allows leaves none either. What a namespace-wide reading got right
stays right. An SCP denying s3:DeleteBucket alone keeps S3 on the list, because
every other S3 action is still reachable, and a Deny carrying a Condition or
naming particular resources closes nothing: the region guardrail on * that most
organizations carry, and a deny scoped to one bucket, both leave the service
reachable by every request they do not cover, and reading them as total denials
would report an organization that reaches nothing.
This is still not the existing scpAllows asked once per namespace. That question
needs a concrete action, and a request action of s3:* would not match a statement
naming s3:GetObject, a pattern globbing against a request value and never the
other way round. The survivors are found by probing instead, with the actions the
policies themselves name and one stand-in action per wildcard, which decides the
patterns policies are written with exactly: a deny on s3:GetObject leaves the
service reachable where a deny on s3:Get* does not. A wildcard that is not a
trailing one is the limit of it, since the stand-in for s3:*Object misses the
s3:GetObject that s3:Get* would allow; such a pattern leaves the service on the
list rather than off it, which is the side the namespace reading was already on.
The management account is not limited by SCPs, so its report lists every service
and an OrganizationsPolicyId passed with it is ignored, both as documented.
Passing that ID otherwise narrows the report to the one SCP named, and it has to
name one: Organizations keeps tag, backup, chatbot and opt-out policies in the
same ID space, none of them carries statements, and evaluating one as a ceiling
would read as a level that constrains nothing and report every service there is.
The entity path has to be a path the organization actually has. The segments
below the root name a chain of parent and child, so the path is held to the one
Organizations reports for its last node rather than each segment being resolved
on its own. Resolving them one at a time accepts a path assembled from two
branches, or one that skips an OU, and reports the policies of a chain the
organization does not have; it also lets a path whose last segment is the
management account take the unlimited answer with an OU above it that does not
exist.
Floci records no service access, so every service in a report is one principals
are allowed but never reached. The reference's own example gives such a service
as a namespace and a zero count with no region, entity path or last-authenticated
time, so that is the shape here and NumberOfServicesNotAccessed equals
NumberOfServicesAccessible. ServiceName carries a display name Floci has no
mapping for, so the namespace stands in for it as it does on the last-accessed
reader. SortKey is validated against its four values: the namespace keys sort
the list and the time keys leave it in namespace order, since ordering on a
timestamp no entry carries would be ordering on nothing.
A caller who is not the management account gets AccessDenied 403. Neither
operation models a code for that, but a per-action error list is additive: the
reference's common error types "that this AWS service may return" apply to every
action and include the 403 permission denial, and the user guide names the code
for a denied IAM action outright in its AddRoleToInstanceProfile entry. That page
spells it AccessDeniedException where the user guide and the rest of this
service's surface spell it AccessDenied; the latter is used, so a caller sees one
spelling across IAM and STS.
Three things are inferences, and they are the same inference three times. The
docs say so. The generator models no error for an entity path that is well-formed
but resolves to nothing, nor for the prerequisite the reference states, that SCPs
be enabled for the organization root, nor for an OrganizationsPolicyId naming a
policy of some other type, so each produces a FAILED job carrying ErrorDetails:
InvalidEntityPath or the Organizations code for the entity in the first case,
PolicyTypeNotEnabled in the second, Organizations' InvalidInputException in the
third. That is read off the shape of the API rather than off a sentence: AWS
publishes both fields on this reader for failures the generator does not report
synchronously. The alternatives are worse. Letting Organizations' own error
escape unchanged puts another service's code on an IAM operation, a COMPLETED job
with an empty list cannot be told apart from an organization that reaches no
services, and ValidationError is for a shape violation, which a well-formed path,
a disabled policy type and an existing policy of the wrong type are not.
ReportGenerationLimitExceeded, the generator's only modeled error, reports
concurrent generations and stays unreachable: a job completes the moment it is
created, so two never overlap.
The generator also carries the access-report resource type, so it leaves
UNRESOLVED_TYPES and resolves from the request. The reference spells the type as
access-report/${EntityPath}, so the entity path goes into the ARN whole: its
slashes are the organization's tree, not an IAM path, which is why it does not
go through the minting the creates use.
Both actions join AwsQueryController.IAM_ACTIONS as well as the handler, without
which inferService would never route them. That list and the handler now hold
166 each, still exactly in step.
Validation runs before the lookup, as AWS rejects a request shape whether or not
the job exists: a SortKey outside the enum answers ValidationError even for a
job ID nothing holds, where validating it afterwards would answer NoSuchEntity.
A member the request carries is held to its shape whatever it carries, an empty
value included, since SortKey= and OrganizationsPolicyId= are a malformed enum
and a malformed id rather than a way of leaving an optional member out. The
entity path reports the constraint that failed rather than the regular
expression for every case, so a path over the maximum length reads as a length
violation, which is what every other validated IAM member does.
Only the one Organizations answer that means something about the caller becomes
AccessDenied. A read that fails for any other reason keeps its own error, rather
than reaching the caller as a permission problem they do not have.
Two things are shared rather than copied. The job registry both report
generators keep, an account-scoped store keyed by job ID that answers
NoSuchEntity for an ID it does not hold, moves into IamJobStore and
ServiceLastAccessedService reads it from there; the two had the same three
methods and the same message. The report's timestamps come from the injected
Clock, which IamService already takes, rather than from Instant.now(), so they
agree with every other time IAM decides. IamQueryHandlerTest builds the handler
itself rather than through injection, so it passes the new service along with
the dependencies it already does not use.
Fourteen unit tests cover the chain semantics, including the allow-list idiom of
allowing everything and denying all but one namespace, levels allowing disjoint
single actions, a deny on the only action allowed and on a pattern wider than it,
a conditional deny, a deny scoped to one bucket, a level with an unreadable
document, and a level with none. Twenty-one integration tests drive the pair over
an organization built through the Organizations API, on a management account of
their own so they never contend with the existing Organizations suites for one.
Two of them are the ones that hold the walk honest: the OU path, where the root
leaves S3 and DynamoDB and the OU leaves DynamoDB and IAM, so only a report
reading both levels answers DynamoDB alone, and the management account path,
which reports every service and ignores the policy ID passed with it even with a
ceiling attached to the root above it. With the tree read deliberately broken the
first SCP test returns all 456 namespaces instead of the one, and it is the only
test that notices. Two more tests mock the Organizations read, which is the one
failure a real organization cannot be made to produce.
This commit is contained in:
1 parent
6d2aaba6a6
commit
4e769484df
16 files changed
+1607
-34
No files matched your search
@@ -141,8 +141,10 @@ class IamActionResourcesTest {
|
||||
"user", "role", "group", "instance-profile", "server-certificate",
|
||||
// Named by an ARN the request carries, or minted by a create.
|
||||
"policy", "mfa", "sms-mfa", "saml-provider", "oidc-provider",
|
||||
// Named by a parameter that is not an IAM entity name.
|
||||
"access-report",
|
||||
// Only on actions the handler does not dispatch.
|
||||
"access-report", "delegation-request", "role-template"),
|
||||
"delegation-request", "role-template"),
|
||||
inUse,
|
||||
"AWS has changed which resource types IAM actions are authorized against; "
|
||||
+ "teach ResourceArnBuilder the new one or list it as unresolved");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsServiceNamespaces;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
@@ -1088,4 +1089,186 @@ class IamPolicyEvaluatorTest {
|
||||
|
||||
assertEquals(List.of("aws:PrincipalArn"), keys);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAbsentScpChainLeavesEveryServiceReachable() {
|
||||
// The management account's case: the reference says it "is not limited by SCPs", so its
|
||||
// report lists every service.
|
||||
assertEquals(AwsServiceNamespaces.all().size(),
|
||||
evaluator.servicesAllowedByScpLevels(null).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLevelAllowingEverythingLeavesEveryServiceReachable() {
|
||||
assertEquals(AwsServiceNamespaces.all().size(),
|
||||
evaluator.servicesAllowedByScpLevels(List.of(List.of(ALLOW_ALL))).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLevelsAreIntersectedAndTheAttachedPoliciesWithinOneAreNot() {
|
||||
// FullAWSAccess at the root, S3 only at the OU: the OU's ceiling wins.
|
||||
assertEquals(List.of("s3"),
|
||||
evaluator.servicesAllowedByScpLevels(
|
||||
List.of(List.of(ALLOW_ALL), List.of(ALLOW_S3_ONLY))));
|
||||
// Two policies attached at one level are a union, so both services survive a root that
|
||||
// allows everything.
|
||||
assertEquals(List.of("dynamodb", "s3"),
|
||||
evaluator.servicesAllowedByScpLevels(List.of(List.of(ALLOW_ALL),
|
||||
List.of(ALLOW_S3_ONLY, allowOnly("dynamodb")))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void levelsThatCannotOverlapLeaveNothingReachable() {
|
||||
assertEquals(List.of(), evaluator.servicesAllowedByScpLevels(
|
||||
List.of(List.of(ALLOW_S3_ONLY), List.of(allowOnly("dynamodb")))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyDropsAServiceOnlyWhenItClosesTheWholeNamespace() {
|
||||
// DENY_S3 denies s3:*, so S3 goes.
|
||||
assertFalse(evaluator.servicesAllowedByScpLevels(List.of(List.of(DENY_S3))).contains("s3"));
|
||||
// One action is not the service: a principal can still reach S3 through everything else.
|
||||
String denyOneAction =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:DeleteBucket\","
|
||||
+ "\"Resource\":\"*\"}]}";
|
||||
assertTrue(evaluator.servicesAllowedByScpLevels(List.of(List.of(denyOneAction)))
|
||||
.contains("s3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConditionalDenyLeavesEveryServiceReachable() {
|
||||
// The region guardrail most organizations carry. It bites only outside one region, so
|
||||
// every service is still reachable inside it, and treating it as a total deny would report
|
||||
// an organization that reaches nothing at all.
|
||||
String denyOutsideOneRegion =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"*\",\"Resource\":\"*\","
|
||||
+ "\"Condition\":{\"StringNotEquals\":"
|
||||
+ "{\"aws:RequestedRegion\":\"us-east-1\"}}}]}";
|
||||
|
||||
assertEquals(AwsServiceNamespaces.all().size(),
|
||||
evaluator.servicesAllowedByScpLevels(List.of(List.of(denyOutsideOneRegion)))
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyScopedToOneResourceLeavesTheServiceReachable() {
|
||||
// Denying s3:* on one bucket does not put S3 out of reach: every other bucket is still
|
||||
// there, which is the same reading that keeps a service denied one action on the list.
|
||||
String denyOneBucket =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:*\","
|
||||
+ "\"Resource\":\"arn:aws:s3:::locked-bucket/*\"}]}";
|
||||
|
||||
assertTrue(evaluator.servicesAllowedByScpLevels(List.of(List.of(denyOneBucket)))
|
||||
.contains("s3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNotActionDenyIsTheAllowListIdiomItIsWrittenAs() {
|
||||
// The common SCP shape: allow everything, then deny everything that is not S3.
|
||||
String denyAllButS3 =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"NotAction\":\"s3:*\","
|
||||
+ "\"Resource\":\"*\"}]}";
|
||||
|
||||
assertEquals(List.of("s3"),
|
||||
evaluator.servicesAllowedByScpLevels(List.of(List.of(denyAllButS3))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void levelsAllowingDisjointSingleActionsLeaveNothingReachable() {
|
||||
// Both levels allow an S3 action, so a namespace-at-a-time reading intersects S3 with S3
|
||||
// and keeps it, although no one action clears both ceilings.
|
||||
assertFalse(evaluator.servicesAllowedByScpLevels(
|
||||
List.of(List.of(allowOnlyAction("s3:GetObject")),
|
||||
List.of(allowOnlyAction("s3:PutObject"))))
|
||||
.contains("s3"));
|
||||
// The same two levels where the actions do overlap keep it.
|
||||
assertTrue(evaluator.servicesAllowedByScpLevels(
|
||||
List.of(List.of(allowOnlyAction("s3:Get*")),
|
||||
List.of(allowOnlyAction("s3:GetObject"))))
|
||||
.contains("s3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyOnTheOnlyAllowedActionDropsTheService() {
|
||||
// The deny closes nothing like the whole namespace, but it closes everything the level
|
||||
// allowed, which leaves no S3 action to reach.
|
||||
String allowAndDenyOneAction =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\","
|
||||
+ "\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:GetObject\","
|
||||
+ "\"Resource\":\"*\"}]}";
|
||||
|
||||
assertFalse(evaluator.servicesAllowedByScpLevels(List.of(List.of(allowAndDenyOneAction)))
|
||||
.contains("s3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyOnAWiderPatternThanTheAllowDropsTheService() {
|
||||
String allowOneDenyThePrefix =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\","
|
||||
+ "\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:Get*\","
|
||||
+ "\"Resource\":\"*\"}]}";
|
||||
|
||||
assertFalse(evaluator.servicesAllowedByScpLevels(List.of(List.of(allowOneDenyThePrefix)))
|
||||
.contains("s3"));
|
||||
// Narrower the other way round: the deny takes GetObject and the allow keeps the rest of
|
||||
// the prefix, so the service stays.
|
||||
String allowThePrefixDenyOne =
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"s3:Get*\","
|
||||
+ "\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:GetObject\","
|
||||
+ "\"Resource\":\"*\"}]}";
|
||||
|
||||
assertTrue(evaluator.servicesAllowedByScpLevels(List.of(List.of(allowThePrefixDenyOne)))
|
||||
.contains("s3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWildcardThatIsNotATrailingOneKeepsTheServiceOnTheList() {
|
||||
// The documented limit of the probes: s3:*Object and s3:Get* do overlap, at s3:GetObject,
|
||||
// but no stand-in action shows it. The service stays on the list rather than coming off
|
||||
// it, which is the side the namespace reading was already on.
|
||||
assertTrue(evaluator.servicesAllowedByScpLevels(
|
||||
List.of(List.of(allowOnlyAction("s3:Get*")),
|
||||
List.of(allowOnlyAction("s3:*Object"))))
|
||||
.contains("s3"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnreadableGuardrailLeavesNothingReachable() {
|
||||
// The same judgement scpAllows makes: the ceiling cannot tell what the document said, and
|
||||
// reporting every service would be the permissive answer.
|
||||
assertEquals(List.of(),
|
||||
evaluator.servicesAllowedByScpLevels(List.of(List.of(ALLOW_ALL, MALFORMED))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLevelWithNoPolicyConstrainsNothing() {
|
||||
// AWS keeps FullAWSAccess attached to every target, so a bare level is not a level that
|
||||
// denies: it is one that has nothing to say.
|
||||
assertEquals(List.of("s3"), evaluator.servicesAllowedByScpLevels(
|
||||
List.of(List.of(), List.of(ALLOW_S3_ONLY))));
|
||||
}
|
||||
|
||||
private static String allowOnlyAction(String action) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"" + action + "\",\"Resource\":\"*\"}]}";
|
||||
}
|
||||
|
||||
private static String allowOnly(String namespace) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Action\":\"" + namespace + ":*\",\"Resource\":\"*\"}]}";
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ class IamQueryHandlerTest {
|
||||
"fabricated-key", null, Map.of())).thenReturn(certificate);
|
||||
when(service.getServerCertificate(CERTIFICATE_NAME)).thenReturn(certificate);
|
||||
when(service.listServerCertificates(null)).thenReturn(List.of(certificate));
|
||||
IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null);
|
||||
IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null);
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("ServerCertificateName", CERTIFICATE_NAME);
|
||||
@@ -90,7 +90,7 @@ class IamQueryHandlerTest {
|
||||
IamService service = mock(IamService.class);
|
||||
when(service.createRole(ROLE_NAME, "/", "{}", null, 3600, Map.of(), null)).thenReturn(role);
|
||||
when(service.getValidatedRole(ROLE_NAME)).thenReturn(role);
|
||||
IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null);
|
||||
IamQueryHandler handler = new IamQueryHandler(service, null, null, null, null, null, null, null);
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("RoleName", ROLE_NAME);
|
||||
|
||||
+463
@@ -0,0 +1,463 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.path.xml.XmlPath;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The Organizations access report end to end, over a real organization built through the
|
||||
* Organizations API.
|
||||
*
|
||||
* <p>Runs as its own management account so it never contends with the other Organizations suites
|
||||
* for one, and each test deletes the organization it built, the Quarkus instance being shared.
|
||||
*
|
||||
* <p>Floci records no service access, so every service in a report is one principals are allowed
|
||||
* but never reached. That is the shape the reference's own example gives such a service: a
|
||||
* namespace and a zero count, with no region, entity path or last-authenticated time.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class OrganizationsAccessReportIntegrationTest {
|
||||
|
||||
private static final String MANAGEMENT_ACCOUNT = "555555555555";
|
||||
private static final String MEMBER_ACCOUNT = "555555555556";
|
||||
private static final String CONTENT_TYPE = "application/x-amz-json-1.1";
|
||||
private static final String TARGET_PREFIX = "AWSOrganizationsV20161128.";
|
||||
/** The allow-list idiom an SCP is actually written as: allow all, then deny all but one. */
|
||||
private static final String DENY_ALL_BUT_S3 =
|
||||
"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":["
|
||||
+ "{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"*\\\",\\\"Resource\\\":\\\"*\\\"},"
|
||||
+ "{\\\"Effect\\\":\\\"Deny\\\",\\\"NotAction\\\":\\\"s3:*\\\","
|
||||
+ "\\\"Resource\\\":\\\"*\\\"}]}";
|
||||
private static final String ALLOW_S3_ONLY =
|
||||
"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Effect\\\":\\\"Allow\\\","
|
||||
+ "\\\"Action\\\":\\\"s3:*\\\",\\\"Resource\\\":\\\"*\\\"}]}";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private static String authorization(String accountId, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accountId
|
||||
+ "/20261010/us-east-1/" + service + "/aws4_request, SignedHeaders=host, "
|
||||
+ "Signature=abc";
|
||||
}
|
||||
|
||||
private static RequestSpecification organizations(String accountId, String action, String body) {
|
||||
return given()
|
||||
.header("Authorization", authorization(accountId, "organizations"))
|
||||
.header("X-Amz-Target", TARGET_PREFIX + action)
|
||||
.contentType(CONTENT_TYPE)
|
||||
.body(body);
|
||||
}
|
||||
|
||||
private static RequestSpecification iam(String accountId, String action) {
|
||||
return given().header("Authorization", authorization(accountId, "iam"))
|
||||
.formParam("Action", action);
|
||||
}
|
||||
|
||||
/** Creates the organization with SCPs enabled on its root, and returns its entity path. */
|
||||
private String organizationWithScpsEnabled() {
|
||||
return organization(true);
|
||||
}
|
||||
|
||||
/** The same organization with the prerequisite left off: SCPs never enabled on the root. */
|
||||
private String organizationWithoutScpsEnabled() {
|
||||
return organization(false);
|
||||
}
|
||||
|
||||
private String organization(boolean enableServiceControlPolicies) {
|
||||
cleanup.register(() -> organizations(MANAGEMENT_ACCOUNT, "DeleteOrganization", "{}")
|
||||
.when().post("/").then().statusCode(200));
|
||||
String organizationId = organizations(MANAGEMENT_ACCOUNT, "CreateOrganization",
|
||||
"{\"FeatureSet\":\"ALL\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Organization.Id");
|
||||
String rootId = organizations(MANAGEMENT_ACCOUNT, "ListRoots", "{}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Roots[0].Id");
|
||||
if (enableServiceControlPolicies) {
|
||||
organizations(MANAGEMENT_ACCOUNT, "EnablePolicyType",
|
||||
"{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"SERVICE_CONTROL_POLICY\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
return organizationId + "/" + rootId;
|
||||
}
|
||||
|
||||
private void attach(String policyId, String targetId) {
|
||||
organizations(MANAGEMENT_ACCOUNT, "AttachPolicy",
|
||||
"{\"PolicyId\":\"" + policyId + "\",\"TargetId\":\"" + targetId + "\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private String createOrganizationalUnit(String name, String parentId) {
|
||||
String ouId = organizations(MANAGEMENT_ACCOUNT, "CreateOrganizationalUnit",
|
||||
"{\"Name\":\"" + name + "\",\"ParentId\":\"" + parentId + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("OrganizationalUnit.Id");
|
||||
// Registered after the organization's own undo so it runs before it: Organizations
|
||||
// refuses to delete an organization that still holds an OU, and the leftover would then
|
||||
// fail the next test's CreateOrganization rather than this one.
|
||||
cleanup.register(() -> organizations(MANAGEMENT_ACCOUNT, "DeleteOrganizationalUnit",
|
||||
"{\"OrganizationalUnitId\":\"" + ouId + "\"}")
|
||||
.when().post("/").then().statusCode(200));
|
||||
return ouId;
|
||||
}
|
||||
|
||||
/** The allow-list idiom over several namespaces: allow everything, then deny all but these. */
|
||||
private static String denyAllBut(String... namespaces) {
|
||||
StringBuilder notActions = new StringBuilder();
|
||||
for (String namespace : namespaces) {
|
||||
notActions.append(notActions.isEmpty() ? "" : ",")
|
||||
.append("\\\"").append(namespace).append(":*\\\"");
|
||||
}
|
||||
return "{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":["
|
||||
+ "{\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"*\\\","
|
||||
+ "\\\"Resource\\\":\\\"*\\\"},"
|
||||
+ "{\\\"Effect\\\":\\\"Deny\\\",\\\"NotAction\\\":[" + notActions
|
||||
+ "],\\\"Resource\\\":\\\"*\\\"}]}";
|
||||
}
|
||||
|
||||
private String createScp(String name, String content) {
|
||||
return organizations(MANAGEMENT_ACCOUNT, "CreatePolicy",
|
||||
"{\"Content\":\"" + content + "\",\"Description\":\"" + name + "\","
|
||||
+ "\"Name\":\"" + name + "\",\"Type\":\"SERVICE_CONTROL_POLICY\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Policy.PolicySummary.Id");
|
||||
}
|
||||
|
||||
private String generate(String entityPath, String policyId) {
|
||||
RequestSpecification request = iam(MANAGEMENT_ACCOUNT, "GenerateOrganizationsAccessReport")
|
||||
.formParam("EntityPath", entityPath);
|
||||
if (policyId != null) {
|
||||
request = request.formParam("OrganizationsPolicyId", policyId);
|
||||
}
|
||||
return request.when().post("/").then().statusCode(200)
|
||||
.extract().path("GenerateOrganizationsAccessReportResponse."
|
||||
+ "GenerateOrganizationsAccessReportResult.JobId");
|
||||
}
|
||||
|
||||
private XmlPath report(String jobId, String... extraParams) {
|
||||
RequestSpecification request = iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")
|
||||
.formParam("JobId", jobId);
|
||||
for (int i = 0; i < extraParams.length; i += 2) {
|
||||
request = request.formParam(extraParams[i], extraParams[i + 1]);
|
||||
}
|
||||
return request.when().post("/").then().statusCode(200).extract().xmlPath();
|
||||
}
|
||||
|
||||
private static String result(String field) {
|
||||
return "GetOrganizationsAccessReportResponse.GetOrganizationsAccessReportResult." + field;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aJobIdIsTheModeledLengthAndTheReportReadsBackCompleted() {
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
|
||||
String jobId = generate(entityPath, null);
|
||||
|
||||
// jobIDType is min 36 / max 36, so a client buffer sized to the model must fit it exactly.
|
||||
assertEquals(36, jobId.length(), "expected a 36-character job id, got: " + jobId);
|
||||
XmlPath report = report(jobId);
|
||||
assertEquals("COMPLETED", report.getString(result("JobStatus")));
|
||||
assertFalse(report.getString(result("JobCreationDate")).isBlank());
|
||||
assertFalse(report.getString(result("JobCompletionDate")).isBlank());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceNobodyReachedCarriesAZeroCountAndNoAttemptDetails() {
|
||||
String jobId = generate(organizationWithScpsEnabled(), null);
|
||||
|
||||
XmlPath report = report(jobId, "MaxItems", "1");
|
||||
|
||||
assertEquals("0", report.getString(result("AccessDetails.member[0]"
|
||||
+ ".TotalAuthenticatedEntities")));
|
||||
assertFalse(report.getString(result("AccessDetails.member[0].ServiceNamespace")).isBlank());
|
||||
// The reference's own example omits all three for a service with no attempt.
|
||||
assertTrue(report.getString(result("AccessDetails.member[0].LastAuthenticatedTime")) == null
|
||||
|| report.getString(result("AccessDetails.member[0]"
|
||||
+ ".LastAuthenticatedTime")).isBlank());
|
||||
assertTrue(report.getString(result("AccessDetails.member[0].Region")) == null
|
||||
|| report.getString(result("AccessDetails.member[0].Region")).isBlank());
|
||||
assertTrue(report.getString(result("AccessDetails.member[0].EntityPath")) == null
|
||||
|| report.getString(result("AccessDetails.member[0].EntityPath")).isBlank());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCountsAreTheWholeReportAndEveryServiceIsOneNobodyUsed() {
|
||||
String jobId = generate(organizationWithScpsEnabled(), null);
|
||||
|
||||
XmlPath report = report(jobId);
|
||||
|
||||
String accessible = report.getString(result("NumberOfServicesAccessible"));
|
||||
assertEquals(accessible, report.getString(result("NumberOfServicesNotAccessed")));
|
||||
assertTrue(Integer.parseInt(accessible) > 100, "expected the full namespace catalog, got "
|
||||
+ accessible);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyIdNarrowsTheReportToThatPolicy() {
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
String policyId = createScp("S3Only", ALLOW_S3_ONLY);
|
||||
|
||||
XmlPath report = report(generate(entityPath, policyId));
|
||||
|
||||
assertEquals("1", report.getString(result("NumberOfServicesAccessible")));
|
||||
assertEquals("s3", report.getString(result("AccessDetails.member.ServiceNamespace")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anScpOnTheRootNarrowsTheReportToWhatItLeaves() {
|
||||
// The one test that fails if the report does not read the SCPs off the organization tree:
|
||||
// with only FullAWSAccess attached every service is reachable either way, so the ceiling
|
||||
// has to come from a policy this test attached.
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
attach(createScp("S3Ceiling", DENY_ALL_BUT_S3),
|
||||
entityPath.substring(entityPath.indexOf('/') + 1));
|
||||
|
||||
XmlPath report = report(generate(entityPath, null));
|
||||
|
||||
assertEquals("1", report.getString(result("NumberOfServicesAccessible")));
|
||||
assertEquals("s3", report.getString(result("AccessDetails.member.ServiceNamespace")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theReportIsPaginatedAndSortable() {
|
||||
String jobId = generate(organizationWithScpsEnabled(), null);
|
||||
|
||||
XmlPath firstPage = report(jobId, "MaxItems", "2");
|
||||
assertEquals("true", firstPage.getString(result("IsTruncated")));
|
||||
List<String> ascending = firstPage.getList(result("AccessDetails.member.ServiceNamespace"));
|
||||
assertEquals(2, ascending.size());
|
||||
assertTrue(ascending.get(0).compareTo(ascending.get(1)) < 0, ascending.toString());
|
||||
|
||||
List<String> descending = report(jobId, "MaxItems", "2",
|
||||
"SortKey", "SERVICE_NAMESPACE_DESCENDING")
|
||||
.getList(result("AccessDetails.member.ServiceNamespace"));
|
||||
assertTrue(descending.get(0).compareTo(descending.get(1)) > 0, descending.toString());
|
||||
|
||||
String marker = firstPage.getString(result("Marker"));
|
||||
assertFalse(marker.isBlank());
|
||||
List<String> secondPage = report(jobId, "MaxItems", "2", "Marker", marker)
|
||||
.getList(result("AccessDetails.member.ServiceNamespace"));
|
||||
assertFalse(secondPage.contains(ascending.get(0)), secondPage.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSortKeyOutsideTheEnumIsRejected() {
|
||||
String jobId = generate(organizationWithScpsEnabled(), null);
|
||||
|
||||
iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")
|
||||
.formParam("JobId", jobId)
|
||||
.formParam("SortKey", "SERVICE_NAMESPACE")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheManagementAccountCanReadOrGenerateAReport() {
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
String jobId = generate(entityPath, null);
|
||||
|
||||
iam(MEMBER_ACCOUNT, "GenerateOrganizationsAccessReport")
|
||||
.formParam("EntityPath", entityPath)
|
||||
.when().post("/").then().statusCode(403)
|
||||
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
|
||||
|
||||
iam(MEMBER_ACCOUNT, "GetOrganizationsAccessReport")
|
||||
.formParam("JobId", jobId)
|
||||
.when().post("/").then().statusCode(403)
|
||||
.body("ErrorResponse.Error.Code", equalTo("AccessDenied"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntityPathTheModelRejectsIsAValidationError() {
|
||||
organizationWithScpsEnabled();
|
||||
|
||||
iam(MANAGEMENT_ACCOUNT, "GenerateOrganizationsAccessReport")
|
||||
.formParam("EntityPath", "o-a1b2c3d4e5")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntityPathNamingAnotherOrganizationFailsTheJobRatherThanTheCall() {
|
||||
organizationWithScpsEnabled();
|
||||
|
||||
String jobId = generate("o-zzzzzzzzzz/r-zzzz", null);
|
||||
|
||||
XmlPath report = report(jobId);
|
||||
assertEquals("FAILED", report.getString(result("JobStatus")));
|
||||
assertEquals("InvalidEntityPath", report.getString(result("ErrorDetails.Code")));
|
||||
assertFalse(report.getString(result("ErrorDetails.Message")).isBlank());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownJobIdIsNoSuchEntity() {
|
||||
organizationWithScpsEnabled();
|
||||
|
||||
iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")
|
||||
.formParam("JobId", "00000000-0000-0000-0000-000000000000")
|
||||
.when().post("/").then().statusCode(404)
|
||||
.body("ErrorResponse.Error.Code", equalTo("NoSuchEntity"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOuPathIntersectsTheRootCeilingWithTheOneBelowIt() {
|
||||
// The only test that drives more than one level. The root leaves S3 and DynamoDB, the OU
|
||||
// leaves DynamoDB and IAM, so a report reading both answers DynamoDB alone: reading only
|
||||
// the OU would add IAM and reading only the root would add S3.
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
String rootId = entityPath.substring(entityPath.indexOf('/') + 1);
|
||||
String ouId = createOrganizationalUnit("Workloads", rootId);
|
||||
attach(createScp("RootCeiling", denyAllBut("s3", "dynamodb")), rootId);
|
||||
attach(createScp("OuCeiling", denyAllBut("dynamodb", "iam")), ouId);
|
||||
|
||||
XmlPath report = report(generate(entityPath + "/" + ouId, null));
|
||||
|
||||
assertEquals("1", report.getString(result("NumberOfServicesAccessible")));
|
||||
assertEquals("dynamodb", report.getString(result("AccessDetails.member.ServiceNamespace")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theManagementAccountReportsEveryServiceAndIgnoresAPolicyId() {
|
||||
// Both halves of what the reference says about that entity: it "is not limited by SCPs",
|
||||
// so the root's ceiling does not apply to it, and a policy ID passed with it "is ignored".
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
attach(createScp("S3Ceiling", DENY_ALL_BUT_S3),
|
||||
entityPath.substring(entityPath.indexOf('/') + 1));
|
||||
String policyId = createScp("S3Only", ALLOW_S3_ONLY);
|
||||
|
||||
XmlPath report = report(generate(entityPath + "/" + MANAGEMENT_ACCOUNT, policyId));
|
||||
|
||||
assertTrue(Integer.parseInt(report.getString(result("NumberOfServicesAccessible"))) > 100,
|
||||
"the management account is not limited by SCPs, so every service is reachable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOrganizationWithoutServiceControlPoliciesFailsTheJob() {
|
||||
// The reference states SCPs must be enabled for the root and models no error for an
|
||||
// organization where they are not, so the failure lands where the other one does.
|
||||
String jobId = generate(organizationWithoutScpsEnabled(), null);
|
||||
|
||||
XmlPath report = report(jobId);
|
||||
|
||||
assertEquals("FAILED", report.getString(result("JobStatus")));
|
||||
assertEquals("PolicyTypeNotEnabled", report.getString(result("ErrorDetails.Code")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntityPathWhoseOusAreNotParentAndChildFailsTheJob() {
|
||||
// Both OUs exist and the path is well formed, but Workloads is not under Platform. Taking
|
||||
// each segment as an independent policy target would report the Platform and Workloads
|
||||
// ceilings as a chain the organization does not have.
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
String rootId = entityPath.substring(entityPath.indexOf('/') + 1);
|
||||
String platform = createOrganizationalUnit("Platform", rootId);
|
||||
String workloads = createOrganizationalUnit("Workloads", rootId);
|
||||
|
||||
XmlPath report = report(generate(entityPath + "/" + platform + "/" + workloads, null));
|
||||
|
||||
assertEquals("FAILED", report.getString(result("JobStatus")));
|
||||
assertEquals("InvalidEntityPath", report.getString(result("ErrorDetails.Code")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntityPathThatSkipsAnOuFailsTheJob() {
|
||||
// Workloads is under Platform, so naming it straight off the root skips a ceiling.
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
String rootId = entityPath.substring(entityPath.indexOf('/') + 1);
|
||||
String platform = createOrganizationalUnit("Platform", rootId);
|
||||
String workloads = createOrganizationalUnit("Workloads", platform);
|
||||
|
||||
XmlPath report = report(generate(entityPath + "/" + workloads, null));
|
||||
|
||||
assertEquals("FAILED", report.getString(result("JobStatus")));
|
||||
assertEquals("InvalidEntityPath", report.getString(result("ErrorDetails.Code")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aManagementAccountBehindAnUnknownOuFailsTheJob() {
|
||||
// The management account reports every service, so a path resolved no further than its
|
||||
// last segment would answer a completed all-services report for a path that names an OU
|
||||
// the organization does not hold.
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
|
||||
XmlPath report = report(generate(
|
||||
entityPath + "/ou-rge0-notthere/" + MANAGEMENT_ACCOUNT, null));
|
||||
|
||||
assertEquals("FAILED", report.getString(result("JobStatus")));
|
||||
assertEquals("InvalidEntityPath", report.getString(result("ErrorDetails.Code")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPolicyIdNamingSomethingOtherThanAnScpFailsTheJob() {
|
||||
// Organizations keeps every policy type in one id space, and a tag policy carries no
|
||||
// statements, so evaluating one as a ceiling would read as a level that constrains
|
||||
// nothing and report every service there is.
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
String rootId = entityPath.substring(entityPath.indexOf('/') + 1);
|
||||
organizations(MANAGEMENT_ACCOUNT, "EnablePolicyType",
|
||||
"{\"RootId\":\"" + rootId + "\",\"PolicyType\":\"TAG_POLICY\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
String tagPolicyId = organizations(MANAGEMENT_ACCOUNT, "CreatePolicy",
|
||||
"{\"Content\":\"{\\\"tags\\\":{}}\",\"Description\":\"Tags\","
|
||||
+ "\"Name\":\"Tags\",\"Type\":\"TAG_POLICY\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Policy.PolicySummary.Id");
|
||||
|
||||
XmlPath report = report(generate(entityPath, tagPolicyId));
|
||||
|
||||
assertEquals("FAILED", report.getString(result("JobStatus")));
|
||||
assertEquals("InvalidInputException", report.getString(result("ErrorDetails.Code")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptySortKeyIsRejectedRatherThanReadAsAnAbsentOne() {
|
||||
String jobId = generate(organizationWithScpsEnabled(), null);
|
||||
|
||||
iam(MANAGEMENT_ACCOUNT, "GetOrganizationsAccessReport")
|
||||
.formParam("JobId", jobId)
|
||||
.formParam("SortKey", "")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyPolicyIdIsRejectedRatherThanReadAsAnAbsentOne() {
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
|
||||
iam(MANAGEMENT_ACCOUNT, "GenerateOrganizationsAccessReport")
|
||||
.formParam("EntityPath", entityPath)
|
||||
.formParam("OrganizationsPolicyId", "")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("ValidationError"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntityPathNamingAnOuTheOrganizationDoesNotHoldFailsTheJob() {
|
||||
String entityPath = organizationWithScpsEnabled();
|
||||
|
||||
XmlPath report = report(generate(entityPath + "/ou-rge0-notthere", null));
|
||||
|
||||
assertEquals("FAILED", report.getString(result("JobStatus")));
|
||||
assertEquals("OrganizationalUnitNotFoundException",
|
||||
report.getString(result("ErrorDetails.Code")));
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* What the report service does with an Organizations read that fails for a reason other than the
|
||||
* caller having no organization. The end-to-end behaviour is in
|
||||
* {@link OrganizationsAccessReportIntegrationTest}; this is the one case a real organization
|
||||
* cannot be made to produce.
|
||||
*/
|
||||
class OrganizationsAccessReportServiceTest {
|
||||
|
||||
private static final String CALLER = "111122223333";
|
||||
private static final String ENTITY_PATH = "o-a1b2c3d4e5/r-abcd";
|
||||
|
||||
@Test
|
||||
void anOrganizationsReadThatFailsForAnotherReasonKeepsItsOwnError() {
|
||||
OrganizationsService organizations = mock(OrganizationsService.class);
|
||||
when(organizations.describeOrganization(CALLER))
|
||||
.thenThrow(new AwsException("ServiceFailure",
|
||||
"The request processing has failed because of an unknown error.", 500));
|
||||
OrganizationsAccessReportService service = new OrganizationsAccessReportService(
|
||||
new InMemoryStorage<>(), organizations,
|
||||
new IamPolicyEvaluator(new ObjectMapper()), Clock.systemUTC());
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> service.generate(CALLER, ENTITY_PATH, null));
|
||||
|
||||
// Reading it as AccessDenied would send the caller after a permission they already have.
|
||||
assertEquals("ServiceFailure", thrown.getErrorCode());
|
||||
assertEquals(500, thrown.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAccountInNoOrganizationIsNotAManagementAccount() {
|
||||
OrganizationsService organizations = mock(OrganizationsService.class);
|
||||
when(organizations.describeOrganization(CALLER))
|
||||
.thenThrow(new AwsException("AWSOrganizationsNotInUseException",
|
||||
"Your account is not a member of an organization.", 400));
|
||||
OrganizationsAccessReportService service = new OrganizationsAccessReportService(
|
||||
new InMemoryStorage<>(), organizations,
|
||||
new IamPolicyEvaluator(new ObjectMapper()), Clock.systemUTC());
|
||||
|
||||
AwsException thrown = assertThrows(AwsException.class,
|
||||
() -> service.generate(CALLER, ENTITY_PATH, null));
|
||||
|
||||
// AWSOrganizationsNotInUse is an Organizations code this operation does not publish.
|
||||
assertEquals("AccessDenied", thrown.getErrorCode());
|
||||
assertEquals(403, thrown.getHttpStatus());
|
||||
}
|
||||
}
|
||||
@@ -393,6 +393,22 @@ class ResourceArnBuilderTest {
|
||||
+ "&PolicyArn=arn%3Aaws%3Aiam%3A%3A000000000000%3Apolicy%2Fp"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The report {@code GenerateOrganizationsAccessReport} would produce. The reference spells the
|
||||
* type as {@code access-report/${EntityPath}}, so the entity path goes in whole: its slashes
|
||||
* are the organization's tree and there is no IAM path to read, which is why this does not go
|
||||
* through the minting the creates use.
|
||||
*/
|
||||
@Test
|
||||
void iamNamesTheAccessReportAnOrganizationsEntityPathAsksFor() {
|
||||
assertEquals("arn:aws:iam::000000000000:access-report/"
|
||||
+ "o-a1b2c3d4e5/r-f6g7h8i9j0example/ou-rge0-awsabcde/123456789012",
|
||||
resourceOf(builder, "Action=GenerateOrganizationsAccessReport&EntityPath="
|
||||
+ "o-a1b2c3d4e5%2Fr-f6g7h8i9j0example%2Fou-rge0-awsabcde%2F123456789012"));
|
||||
// Without the path there is nothing to name, so the permissive answer stands.
|
||||
assertEquals("*", resourceOf(builder, "Action=GenerateOrganizationsAccessReport"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource a certificate-specific policy statement has to match. Without this the action
|
||||
* is evaluated against {@code *}, so a deny naming the certificate never applies.
|
||||
|
||||
Reference in new issue
Block a user