feat(inspector2): support disabling scans (#7181)

* feat(inspector2): support disabling scans

* fix(inspector2): enforce disable permission

* fix(inspector2): accept optional resource types

---------

Co-authored-by: Ovidiu (Ovi) <462561+ovidiubute@users.noreply.github.com>
This commit is contained in:
Ovidiu (Ovi)andOvidiu authored and GitHub committed 2026-11-01 12:22:49 -04:00
1 parent 488a3197f1
commit fd4abd365b
11 files changed
+275 -33

No files matched your search

@@ -9,6 +9,7 @@ import software.amazon.awssdk.services.inspector2.model.AutoEnable;
import software.amazon.awssdk.services.inspector2.model.BatchGetAccountStatusResponse;
import software.amazon.awssdk.services.inspector2.model.DescribeOrganizationConfigurationResponse;
import software.amazon.awssdk.services.inspector2.model.DisableDelegatedAdminAccountResponse;
import software.amazon.awssdk.services.inspector2.model.DisableResponse;
import software.amazon.awssdk.services.inspector2.model.EnableDelegatedAdminAccountResponse;
import software.amazon.awssdk.services.inspector2.model.EnableResponse;
import software.amazon.awssdk.services.inspector2.model.ResourceScanType;
@@ -83,6 +84,26 @@ class Inspector2OrganizationConfigurationTest {
assertThat(account.resourceState().ecr().statusAsString()).isEqualTo("DISABLED");
});
DisableResponse disableMember = administrator.disable(request -> request
.accountIds(inspectedMemberAccount)
.resourceTypes(ResourceScanType.EC2));
assertThat(disableMember.accounts()).singleElement().satisfies(account -> {
assertThat(account.accountId()).isEqualTo(inspectedMemberAccount);
assertThat(account.statusAsString()).isEqualTo("DISABLING");
assertThat(account.resourceStatus().ec2AsString()).isEqualTo("DISABLING");
});
administrator.batchGetAccountStatus(request -> request.accountIds(inspectedMemberAccount));
assertThat(administrator.batchGetAccountStatus(request -> request.accountIds(inspectedMemberAccount))
.accounts()).singleElement().satisfies(account -> {
assertThat(account.state().statusAsString()).isEqualTo("DISABLED");
assertThat(account.resourceState().ec2().statusAsString()).isEqualTo("DISABLED");
});
assertThat(administrator.disable(request -> request.accountIds(inspectedMemberAccount)).accounts())
.singleElement().satisfies(account -> {
assertThat(account.accountId()).isEqualTo(inspectedMemberAccount);
assertThat(account.statusAsString()).isEqualTo("DISABLED");
});
UpdateOrganizationConfigurationResponse updated = administrator.updateOrganizationConfiguration(request -> request
.autoEnable(AutoEnable.builder()
.ec2(true)
+1 -1
View File
@@ -54,7 +54,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [IAM Identity Center Access Portal](ssoportal.md) | `/assignment/accounts`, `/assignment/roles`, `/federation/credentials`, `/logout` | REST JSON | 4 |
| [Identity Store](identitystore.md) | `POST /` + `X-Amz-Target: AWSIdentityStore.*` | JSON 1.1 | 19 |
| [Amazon Macie](macie2.md) | `/admin`, `/macie`, `/admin/configuration` | REST JSON | 8 |
| [Amazon Inspector](inspector2.md) | `/delegatedadminaccounts/*`, `/status/batch/get`, `/enable`, `/organizationconfiguration/*` | REST JSON | 7 |
| [Amazon Inspector](inspector2.md) | `/delegatedadminaccounts/*`, `/status/batch/get`, `/enable`, `/disable`, `/organizationconfiguration/*` | REST JSON | 8 |
| [Amazon Verified Permissions](verifiedpermissions.md) | `POST /` + `X-Amz-Target: VerifiedPermissions.*` | JSON 1.0 | 34 |
| [Security Hub](securityhub.md) | `/organization/*`, `/accounts`, `/findingAggregator/*`, `/configurationPolicy*`, `/standards*`, `/tags/*` | REST JSON | 26 |
| [Amazon Detective](detective.md) | `/orgs/*`, `/graphs/list`, `/graph/*` | REST JSON | 8 |
+3 -2
View File
@@ -16,15 +16,16 @@ Floci implements the Amazon Inspector organization operations used by local secu
| `DisableDelegatedAdminAccount` | - |
| `BatchGetAccountStatus` | - |
| `Enable` | - |
| `Disable` | - |
| `UpdateOrganizationConfiguration` | - |
| `DescribeOrganizationConfiguration` | - |
<!-- floci:actions:end -->
## Supported behavior
The supported surface includes delegated administrator management, `BatchGetAccountStatus`, Inspector enablement, and organization auto-enable configuration. Delegation is reflected into the delegated account so organization configuration can be managed through credentials for that administrator account.
The supported surface includes delegated administrator management, `BatchGetAccountStatus`, Inspector enablement and disablement, and organization auto-enable configuration. Delegation is reflected into the delegated account so organization configuration can be managed through credentials for that administrator account.
`BatchGetAccountStatus` accepts an omitted or empty `accountIds` list and resolves it to the caller account. Explicit enablement supports `EC2`, `ECR`, `LAMBDA`, `LAMBDA_CODE`, and `CODE_REPOSITORY`, with the documented request-size limits. Explicit enablement uses the account-state values `ENABLING` and `ENABLED` so SDK and deployment waiters can converge.
`BatchGetAccountStatus` accepts an omitted or empty `accountIds` list and resolves it to the caller account. Explicit enablement and disablement support `EC2`, `ECR`, `LAMBDA`, `LAMBDA_CODE`, and `CODE_REPOSITORY`, with the documented request-size limits. `Disable` also accepts an omitted or empty `resourceTypes` list. State changes use `ENABLING`, `ENABLED`, `DISABLING`, and `DISABLED` so SDK and deployment waiters can converge. Disabling selected scan types leaves the others enabled.
Organization auto-enable supports `ec2`, `ecr`, `lambda`, `lambdaCode`, and `codeRepository`. Only the delegated administrator account can update or describe organization configuration.
@@ -273,6 +273,9 @@ public class IamActionRegistry {
rule("rds-data", "POST", "^/CommitTransaction/?$", "rds-data:CommitTransaction"),
rule("rds-data", "POST", "^/RollbackTransaction/?$", "rds-data:RollbackTransaction"),
// ── Amazon Inspector ───────────────────────────────────────────────────
rule("inspector2", "POST", "^/disable/?$", "inspector2:Disable"),
// ── API Gateway ────────────────────────────────────────────────────────
// The management API, v1 and v2, is authorized by HTTP method on the resource path:
// apigateway:GET, POST, PUT, PATCH or DELETE. Two operations have an action of their own. The
@@ -113,18 +113,30 @@ public class Inspector2Controller {
@POST
@Path("/enable")
public Response enable(@Context HttpHeaders headers, String body) {
JsonNode request = parse(body);
Map<String, InspectorState> enabled = service.enable(region(headers), requestContext.getAccountId(), request);
Map<String, InspectorState> enabled = service.enable(
region(headers), requestContext.getAccountId(), parse(body));
return Response.ok(accountOperationResponse(enabled)).build();
}
@POST
@Path("/disable")
public Response disable(@Context HttpHeaders headers, String body) {
Map<String, InspectorState> disabled = service.disable(
region(headers), requestContext.getAccountId(), parse(body));
return Response.ok(accountOperationResponse(disabled)).build();
}
private ObjectNode accountOperationResponse(Map<String, InspectorState> states) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode accounts = response.putArray("accounts");
enabled.forEach((accountId, state) -> {
states.forEach((accountId, state) -> {
ObjectNode account = accounts.addObject();
account.put("accountId", accountId);
account.put("status", state.getStatus());
account.set("resourceStatus", resourceStatus(state));
});
response.putArray("failedAccounts");
return Response.ok(response).build();
return response;
}
@POST
@@ -16,11 +16,10 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@ApplicationScoped
public class Inspector2Service implements Resettable {
private static final Set<String> RESOURCE_TYPES = Set.of(
private static final List<String> RESOURCE_TYPES = List.of(
"EC2", "ECR", "LAMBDA", "LAMBDA_CODE", "CODE_REPOSITORY");
private final AccountAwareStorageBackend<InspectorState> states;
@@ -65,7 +64,7 @@ public class Inspector2Service implements Resettable {
delegated.setResourceStatus(resourceType, "ENABLED");
}
delegated.setStatus("ENABLED");
delegated.setEnablingPollsRemaining(0);
resetTransitionPolls(delegated);
states.putForAccount(accountId, region, delegated);
}
@@ -89,29 +88,30 @@ public class Inspector2Service implements Resettable {
requireAccountId(accountId);
authorizeAccountAccess(region, callerAccountId, accountId);
InspectorState state = stateForAccount(accountId, region);
if ("ENABLING".equals(state.getStatus()) && state.getEnablingPollsRemaining() > 0) {
InspectorState response = copyState(state);
state.setEnablingPollsRemaining(state.getEnablingPollsRemaining() - 1);
states.putForAccount(accountId, region, state);
return response;
}
if ("ENABLING".equals(state.getStatus())) {
for (String resourceType : RESOURCE_TYPES) {
if ("ENABLING".equals(state.resourceStatus(resourceType))) {
state.setResourceStatus(resourceType, "ENABLED");
}
}
state.setStatus(overallStatus(state));
states.putForAccount(accountId, region, state);
return advanceTransition(region, accountId, state, "ENABLING", "ENABLED");
}
if ("DISABLING".equals(state.getStatus())) {
return advanceTransition(region, accountId, state, "DISABLING", "DISABLED");
}
return copyState(state);
}
public synchronized Map<String, InspectorState> enable(
String region, String callerAccountId, JsonNode request) {
List<String> resourceTypes = resourceTypes(request);
List<String> accountIds = accountIds(request, callerAccountId);
return updateResourceStatus(region, callerAccountId, accountIds(request, callerAccountId),
resourceTypes(request, false), "ENABLING", "ENABLED");
}
public synchronized Map<String, InspectorState> disable(
String region, String callerAccountId, JsonNode request) {
return updateResourceStatus(region, callerAccountId, accountIds(request, callerAccountId),
resourceTypes(request, true), "DISABLING", "DISABLED");
}
private Map<String, InspectorState> updateResourceStatus(
String region, String callerAccountId, List<String> accountIds, List<String> resourceTypes,
String transitionalStatus, String finalStatus) {
for (String accountId : accountIds) {
authorizeAccountAccess(region, callerAccountId, accountId);
}
@@ -122,14 +122,15 @@ public class Inspector2Service implements Resettable {
boolean changed = false;
for (String resourceType : resourceTypes) {
String current = state.resourceStatus(resourceType);
if (!"ENABLED".equals(current) && !"ENABLING".equals(current)) {
state.setResourceStatus(resourceType, "ENABLING");
if (!finalStatus.equals(current) && !transitionalStatus.equals(current)) {
state.setResourceStatus(resourceType, transitionalStatus);
changed = true;
}
}
if (changed) {
state.setStatus("ENABLING");
state.setEnablingPollsRemaining(1);
state.setStatus(transitionalStatus);
resetTransitionPolls(state);
setTransitionPollsRemaining(state, transitionalStatus, 1);
states.putForAccount(accountId, region, state);
}
result.put(accountId, copyState(state));
@@ -137,6 +138,25 @@ public class Inspector2Service implements Resettable {
return result;
}
private InspectorState advanceTransition(String region, String accountId, InspectorState state,
String transitionalStatus, String finalStatus) {
int pollsRemaining = transitionPollsRemaining(state, transitionalStatus);
if (pollsRemaining > 0) {
InspectorState response = copyState(state);
setTransitionPollsRemaining(state, transitionalStatus, pollsRemaining - 1);
states.putForAccount(accountId, region, state);
return response;
}
for (String resourceType : RESOURCE_TYPES) {
if (transitionalStatus.equals(state.resourceStatus(resourceType))) {
state.setResourceStatus(resourceType, finalStatus);
}
}
state.setStatus(overallStatus(state));
states.putForAccount(accountId, region, state);
return copyState(state);
}
public synchronized InspectorState updateOrganizationConfiguration(
String region, String callerAccountId, JsonNode request) {
InspectorState state = requireAdministrator(region, callerAccountId);
@@ -216,11 +236,19 @@ public class Inspector2Service implements Resettable {
return states.getForAccount(accountId, region).orElseGet(InspectorState::new);
}
private static List<String> resourceTypes(JsonNode request) {
private static List<String> resourceTypes(JsonNode request, boolean allowEmpty) {
JsonNode resourceTypes = request.get("resourceTypes");
if (resourceTypes == null || !resourceTypes.isArray() || resourceTypes.isEmpty() || resourceTypes.size() > 5) {
throw new AwsException("ValidationException",
"resourceTypes must contain between 1 and 5 resource types.", 400);
if (resourceTypes == null) {
if (allowEmpty) {
return List.of();
}
throw invalidResourceTypes(false);
}
if (!resourceTypes.isArray() || resourceTypes.size() > 5 || (!allowEmpty && resourceTypes.isEmpty())) {
throw invalidResourceTypes(allowEmpty);
}
if (resourceTypes.isEmpty()) {
return List.of();
}
List<String> result = new ArrayList<>(resourceTypes.size());
for (JsonNode resourceType : resourceTypes) {
@@ -234,6 +262,15 @@ public class Inspector2Service implements Resettable {
return result;
}
private static AwsException invalidResourceTypes(boolean allowEmpty) {
if (allowEmpty) {
return new AwsException("ValidationException",
"resourceTypes must contain between 0 and 5 resource types.", 400);
}
return new AwsException("ValidationException",
"resourceTypes must contain between 1 and 5 resource types.", 400);
}
private static List<String> accountIds(JsonNode request, String callerAccountId) {
JsonNode accountIds = request.get("accountIds");
if (accountIds != null && (!accountIds.isArray() || accountIds.size() > 100)) {
@@ -255,15 +292,42 @@ public class Inspector2Service implements Resettable {
if (enabling) {
return "ENABLING";
}
boolean disabling = RESOURCE_TYPES.stream().anyMatch(type -> "DISABLING".equals(state.resourceStatus(type)));
if (disabling) {
return "DISABLING";
}
boolean enabled = RESOURCE_TYPES.stream().anyMatch(type -> "ENABLED".equals(state.resourceStatus(type)));
return enabled ? "ENABLED" : "DISABLED";
}
private static int transitionPollsRemaining(InspectorState state, String transitionalStatus) {
return switch (transitionalStatus) {
case "ENABLING" -> state.getEnablingPollsRemaining();
case "DISABLING" -> state.getDisablingPollsRemaining();
default -> throw new IllegalArgumentException("Unsupported transition status: " + transitionalStatus);
};
}
private static void setTransitionPollsRemaining(
InspectorState state, String transitionalStatus, int pollsRemaining) {
switch (transitionalStatus) {
case "ENABLING" -> state.setEnablingPollsRemaining(pollsRemaining);
case "DISABLING" -> state.setDisablingPollsRemaining(pollsRemaining);
default -> throw new IllegalArgumentException("Unsupported transition status: " + transitionalStatus);
}
}
private static void resetTransitionPolls(InspectorState state) {
state.setEnablingPollsRemaining(0);
state.setDisablingPollsRemaining(0);
}
private static InspectorState copyState(InspectorState source) {
InspectorState copy = new InspectorState();
copy.setAdminAccountId(source.getAdminAccountId());
copy.setStatus(source.getStatus());
copy.setEnablingPollsRemaining(source.getEnablingPollsRemaining());
copy.setDisablingPollsRemaining(source.getDisablingPollsRemaining());
copy.setEc2Status(source.getEc2Status());
copy.setEcrStatus(source.getEcrStatus());
copy.setLambdaStatus(source.getLambdaStatus());
@@ -9,6 +9,7 @@ public class InspectorState {
private String adminAccountId;
private String status = "DISABLED";
private int enablingPollsRemaining;
private int disablingPollsRemaining;
private String ec2Status = "DISABLED";
private String ecrStatus = "DISABLED";
private String lambdaStatus = "DISABLED";
@@ -29,6 +30,8 @@ public class InspectorState {
public void setStatus(String status) { this.status = status; }
public int getEnablingPollsRemaining() { return enablingPollsRemaining; }
public void setEnablingPollsRemaining(int enablingPollsRemaining) { this.enablingPollsRemaining = enablingPollsRemaining; }
public int getDisablingPollsRemaining() { return disablingPollsRemaining; }
public void setDisablingPollsRemaining(int value) { disablingPollsRemaining = value; }
public String getEc2Status() { return ec2Status; }
public void setEc2Status(String value) { ec2Status = value; }
public String getEcrStatus() { return ecrStatus; }
@@ -89,6 +89,16 @@ class IamActionRegistryTest {
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")));
}
@Test
void inspector2DisableRouteResolvesItsAction() {
ContainerRequestContext ctx = mockCtx("POST", "/disable",
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}");
assertEquals("inspector2:Disable", registry.resolveRoute("inspector2", ctx));
assertNull(registry.resolveRoute("inspector2", mockCtx("GET", "/disable",
new MultivaluedHashMap<>(), null, "")));
}
@Test
void cloudWatchGetUsesQueryActionAndOperationPrecedence() {
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
@@ -0,0 +1,57 @@
package io.github.hectorvent.floci.services.inspector2;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class Inspector2IamEnforcementIntegrationTest {
private static final String ACCOUNT = "111111111111";
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void explicitDenyPreventsDisablingScans() {
String user = "inspector2-iam-" + UUID.randomUUID().toString().substring(0, 8);
String accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(),
auth(ACCOUNT, "iam"), user).accessKeyId();
String policy = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"*","Resource":"*"},
{"Effect":"Deny","Action":"inspector2:Disable","Resource":"*"}
]}""";
given().formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "p")
.formParam("PolicyDocument", policy)
.header("Authorization", auth(ACCOUNT, "iam"))
.post("/").then().statusCode(200);
given().contentType("application/json").header("Authorization", auth(ACCOUNT, "inspector2"))
.body("{\"resourceTypes\":[\"EC2\"]}")
.post("/enable").then().statusCode(200);
given().contentType("application/json").header("Authorization", auth(accessKeyId, "inspector2"))
.body("{\"resourceTypes\":[\"EC2\"]}")
.post("/disable").then().statusCode(403)
.body("__type", equalTo("AccessDeniedException"))
.body("message", containsString("inspector2:Disable"));
}
}
@@ -107,6 +107,45 @@ class Inspector2IntegrationTest {
.body("accounts[0].accountId", equalTo(member));
}
@Test
void disableSelectedScanTypePreservesOthers() {
String management = "940000000071";
String member = "940000000072";
createOrganization(management, member);
given().contentType("application/json").header("Authorization", auth(member))
.body("{\"resourceTypes\":[\"EC2\",\"ECR\"]}")
.post("/enable").then().statusCode(200);
given().contentType("application/json").header("Authorization", auth(member)).body("{}")
.post("/status/batch/get").then().statusCode(200);
given().contentType("application/json").header("Authorization", auth(member)).body("{}")
.post("/status/batch/get").then().statusCode(200);
given().contentType("application/json").header("Authorization", auth(member))
.body("{\"resourceTypes\":[\"EC2\"]}")
.post("/disable").then().statusCode(200)
.body("accounts[0].status", equalTo("DISABLING"))
.body("accounts[0].resourceStatus.ec2", equalTo("DISABLING"))
.body("accounts[0].resourceStatus.ecr", equalTo("ENABLED"));
given().contentType("application/json").header("Authorization", auth(member)).body("{}")
.post("/status/batch/get").then().statusCode(200)
.body("accounts[0].state.status", equalTo("DISABLING"));
given().contentType("application/json").header("Authorization", auth(member)).body("{}")
.post("/status/batch/get").then().statusCode(200)
.body("accounts[0].state.status", equalTo("ENABLED"))
.body("accounts[0].resourceState.ec2.status", equalTo("DISABLED"))
.body("accounts[0].resourceState.ecr.status", equalTo("ENABLED"));
given().contentType("application/json").header("Authorization", auth(member)).body("{}")
.post("/disable").then().statusCode(200)
.body("accounts[0].status", equalTo("ENABLED"));
given().contentType("application/json").header("Authorization", auth(member))
.body("{\"resourceTypes\":[]}")
.post("/disable").then().statusCode(200)
.body("accounts[0].status", equalTo("ENABLED"));
}
@Test
void failedOrganizationUpdateDoesNotPartiallyMutateState() {
String management = "940000000041";
@@ -112,6 +112,38 @@ class Inspector2ServiceTest {
assertEquals("AccessDeniedException", denied.getErrorCode());
}
@Test
void disableOnlyRequestedResourceTypesAndConverges() throws Exception {
service.enable(REGION, MEMBER_ACCOUNT, objectMapper.readTree(
"{\"resourceTypes\":[\"EC2\",\"ECR\"]}"));
service.accountStatus(REGION, MEMBER_ACCOUNT, MEMBER_ACCOUNT);
service.accountStatus(REGION, MEMBER_ACCOUNT, MEMBER_ACCOUNT);
InspectorState disabling = service.disable(REGION, MEMBER_ACCOUNT,
objectMapper.readTree("{\"resourceTypes\":[\"EC2\"]}")).get(MEMBER_ACCOUNT);
assertEquals("DISABLING", disabling.getStatus());
assertEquals("DISABLING", disabling.getEc2Status());
assertEquals("ENABLED", disabling.getEcrStatus());
InspectorState first = service.accountStatus(REGION, MEMBER_ACCOUNT, MEMBER_ACCOUNT);
assertEquals("DISABLING", first.getStatus());
InspectorState converged = service.accountStatus(REGION, MEMBER_ACCOUNT, MEMBER_ACCOUNT);
assertEquals("ENABLED", converged.getStatus());
assertEquals("DISABLED", converged.getEc2Status());
assertEquals("ENABLED", converged.getEcrStatus());
}
@Test
void disableAcceptsOmittedOrEmptyResourceTypes() throws Exception {
InspectorState omitted = service.disable(REGION, MEMBER_ACCOUNT,
objectMapper.readTree("{}")).get(MEMBER_ACCOUNT);
InspectorState empty = service.disable(REGION, MEMBER_ACCOUNT,
objectMapper.readTree("{\"resourceTypes\":[]}")).get(MEMBER_ACCOUNT);
assertEquals("DISABLED", omitted.getStatus());
assertEquals("DISABLED", empty.getStatus());
}
@Test
void managementAccountCannotUpdateOrganizationConfiguration() throws Exception {
service.enableDelegatedAdmin(REGION, MANAGEMENT_ACCOUNT, ADMIN_ACCOUNT);