feat(verifiedpermissions): add full service emulation (#3128)

* feat(verifiedpermissions): add full service emulation

* fix(verifiedpermissions): harden OIDC and schema validation

* test(verifiedpermissions): add service layer coverage

* fix(verifiedpermissions): support native Cedar runtime

* fix(verifiedpermissions): package Cedar native FFI

* fix(verifiedpermissions): register Cedar deserializers for native

* fix(verifiedpermissions): bound JWKS refreshes

* fix(verifiedpermissions): avoid Cedar entity reflection

* fix(verifiedpermissions): register Cedar native reflection

* fix(verifiedpermissions): refresh rotated OIDC keys safely

* fix(verifiedpermissions): retry failed JWKS refreshes

* refactor(verifiedpermissions): isolate Cedar in sidecar

* fix(verifiedpermissions): harden Cedar sidecar runtime

* fix(verifiedpermissions): build cedar sidecar in compatibility CI

* fix(verifiedpermissions): remove stale cedar jni config

* fix(verifiedpermissions): recover cedar sidecar

* fix(verifiedpermissions): bound OIDC document responses

* fix(verifiedpermissions): start cedar sidecar in native sdk CI
This commit is contained in:
Franklin G. Mendoza authored and GitHub committed 2026-09-10 22:25:50 -04:00
1 parent 7a7531a6b9
commit 2d51259120
41 files changed
+4800 -4

No files matched your search

@@ -734,6 +734,7 @@ public interface EmulatorConfig {
SecurityHubServiceConfig securityhub();
DetectiveServiceConfig detective();
ServiceQuotasServiceConfig servicequotas();
VerifiedPermissionsServiceConfig verifiedpermissions();
RamServiceConfig ram();
ControlCatalogServiceConfig controlcatalog();
ControlTowerServiceConfig controltower();
@@ -926,6 +927,17 @@ public interface EmulatorConfig {
boolean enabled();
}
interface VerifiedPermissionsServiceConfig {
@WithDefault("true")
boolean enabled();
/** When set, Floci uses this URL and skips Cedar sidecar container management. */
Optional<String> cedarUrl();
@WithDefault("floci/floci:latest-cedar")
String cedarImage();
}
interface RamServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
import io.github.hectorvent.floci.services.swf.SwfJsonHandler;
import io.github.hectorvent.floci.services.verifiedpermissions.VerifiedPermissionsJsonHandler;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
@@ -51,6 +52,7 @@ public class AwsJsonController {
private final SwfJsonHandler swfJsonHandler;
private final NetworkFirewallJsonHandler networkFirewallJsonHandler;
private final MarketplaceJsonHandler marketplaceJsonHandler;
private final VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler;
@Inject
public AwsJsonController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
@@ -63,7 +65,8 @@ public class AwsJsonController {
CloudControlJsonHandler cloudControlJsonHandler,
SwfJsonHandler swfJsonHandler,
NetworkFirewallJsonHandler networkFirewallJsonHandler,
MarketplaceJsonHandler marketplaceJsonHandler) {
MarketplaceJsonHandler marketplaceJsonHandler,
VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler) {
this.objectMapper = objectMapper;
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.catalog = catalog;
@@ -78,6 +81,7 @@ public class AwsJsonController {
this.swfJsonHandler = swfJsonHandler;
this.networkFirewallJsonHandler = networkFirewallJsonHandler;
this.marketplaceJsonHandler = marketplaceJsonHandler;
this.verifiedPermissionsJsonHandler = verifiedPermissionsJsonHandler;
}
@POST
@@ -129,6 +133,7 @@ public class AwsJsonController {
case "network-firewall" -> networkFirewallJsonHandler.handle(
action, request, region, regionResolver.getAccountId());
case "marketplace" -> marketplaceJsonHandler.handle(action, request, region);
case "verifiedpermissions" -> verifiedPermissionsJsonHandler.handle(action, request, region);
default -> null;
};
// catalog.matchTarget is protocol-agnostic: a JSON 1.1 target
@@ -649,6 +649,10 @@ public class ResolvedServiceCatalog {
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("codeguru-reviewer"), Set.of(),
Set.of(io.github.hectorvent.floci.services.codegurureviewer.CodeGuruReviewerController.class)),
descriptor("verifiedpermissions", "verifiedpermissions", config.services().verifiedpermissions().enabled(), true,
"verifiedpermissions", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
Set.of("VerifiedPermissions."), Set.of("verifiedpermissions"), Set.of(), Set.of()),
descriptor("marketplace", "marketplace", config.services().marketplace().enabled(), true,
"marketplace", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON, ServiceProtocol.JSON, ServiceProtocol.CBOR),
@@ -0,0 +1,216 @@
package io.github.hectorvent.floci.services.verifiedpermissions;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.verifiedpermissions.model.EntityIdentifier;
import io.github.hectorvent.floci.services.verifiedpermissions.model.Policy;
import io.github.hectorvent.floci.services.verifiedpermissions.model.PolicyTemplate;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* AVP request adapter for the Cedar sidecar.
*
* Cedar parsing and authorization run outside the Floci process. This class only performs
* AWS-request normalization that does not require the Cedar runtime and delegates evaluation
* to {@link CedarSidecarClient}.
*/
@ApplicationScoped
public class CedarAuthorizationEvaluator {
private final ObjectMapper objectMapper;
private final CedarSidecarClient cedarClient;
@Inject
public CedarAuthorizationEvaluator(ObjectMapper objectMapper, CedarSidecarClient cedarClient) {
this.objectMapper = objectMapper;
this.cedarClient = cedarClient;
}
public ObjectNode appendTokenPrincipal(JsonNode entitiesDefinition, EntityIdentifier principal,
JsonNode identityClaims, List<EntityIdentifier> parents) {
ArrayNode cedarEntities;
try {
if (entitiesDefinition == null || entitiesDefinition.isNull()) {
cedarEntities = objectMapper.createArrayNode();
} else if (entitiesDefinition.has("cedarJson")) {
JsonNode parsed = objectMapper.readTree(entitiesDefinition.path("cedarJson").asText());
if (!parsed.isArray()) {
throw VerifiedPermissionsService.validation("entities.cedarJson must encode an array.");
}
cedarEntities = (ArrayNode) parsed.deepCopy();
} else if (entitiesDefinition.has("entityList") && entitiesDefinition.get("entityList").isArray()) {
cedarEntities = toCedarEntities((ArrayNode) entitiesDefinition.get("entityList"));
} else {
throw VerifiedPermissionsService.validation("entities must contain cedarJson or entityList.");
}
ObjectNode entity = objectMapper.createObjectNode();
entity.set("uid", cedarEntity(principal));
ObjectNode attrs = entity.putObject("attrs");
if (identityClaims != null && identityClaims.isObject()) {
identityClaims.fields().forEachRemaining(entry -> {
if (!isGroupClaim(entry.getKey()) && claimCanBeCedar(entry.getValue())) {
attrs.set(entry.getKey(), entry.getValue().deepCopy());
}
});
}
ArrayNode parentArray = entity.putArray("parents");
parents.forEach(parent -> parentArray.add(cedarEntity(parent)));
cedarEntities.add(entity);
ObjectNode union = objectMapper.createObjectNode();
union.put("cedarJson", cedarEntities.toString());
return union;
} catch (JsonProcessingException e) {
throw VerifiedPermissionsService.validation("entities.cedarJson is invalid JSON.");
}
}
public EvaluationResult evaluate(JsonNode request, List<Policy> storedPolicies,
Map<String, PolicyTemplate> templates) {
CedarSidecarClient.EvaluationResult result = cedarClient.authorize(request, storedPolicies, templates);
return new EvaluationResult(result.decision(), result.determiningPolicyIds(), result.errors());
}
private static boolean isGroupClaim(String name) {
return "cognito:groups".equals(name) || "groups".equals(name);
}
private static boolean claimCanBeCedar(JsonNode value) {
if (value == null || value.isNull()) {
return false;
}
if (value.isTextual() || value.isBoolean() || value.isIntegralNumber()) {
return true;
}
if (value.isArray()) {
for (JsonNode item : value) {
if (!claimCanBeCedar(item) || item.isContainerNode()) {
return false;
}
}
return true;
}
if (value.isObject()) {
var iterator = value.elements();
while (iterator.hasNext()) {
if (!claimCanBeCedar(iterator.next())) {
return false;
}
}
return true;
}
return false;
}
private ArrayNode toCedarEntities(ArrayNode input) {
ArrayNode output = objectMapper.createArrayNode();
Map<String, ObjectNode> lastByUid = new LinkedHashMap<>();
for (JsonNode entity : input) {
if (!entity.isObject()) {
throw VerifiedPermissionsService.validation("Each entityList item must be an object.");
}
EntityIdentifier id = identifier(entity.get("identifier"), "identifier");
ObjectNode cedar = objectMapper.createObjectNode();
cedar.set("uid", cedarEntity(id));
ObjectNode attrs = cedar.putObject("attrs");
JsonNode attributes = entity.get("attributes");
if (attributes != null && !attributes.isNull()) {
if (!attributes.isObject()) {
throw VerifiedPermissionsService.validation("entity attributes must be an object.");
}
attributes.fields().forEachRemaining(entry -> attrs.set(entry.getKey(), cedarAttribute(entry.getValue())));
}
ArrayNode parents = cedar.putArray("parents");
JsonNode parentInput = entity.get("parents");
if (parentInput != null && !parentInput.isNull()) {
if (!parentInput.isArray()) {
throw VerifiedPermissionsService.validation("entity parents must be an array.");
}
parentInput.forEach(parent -> parents.add(cedarEntity(identifier(parent, "parent"))));
}
ObjectNode tags = cedar.putObject("tags");
JsonNode tagInput = entity.get("tags");
if (tagInput != null && !tagInput.isNull()) {
if (!tagInput.isObject()) {
throw VerifiedPermissionsService.validation("entity tags must be an object.");
}
tagInput.fields().forEachRemaining(entry -> tags.set(entry.getKey(), cedarAttribute(entry.getValue())));
}
lastByUid.put(id.entityType() + "\u0000" + id.entityId(), cedar);
}
lastByUid.values().forEach(output::add);
return output;
}
private JsonNode cedarAttribute(JsonNode union) {
if (union == null || !union.isObject() || union.size() != 1) {
throw VerifiedPermissionsService.validation("Attribute values must contain exactly one union member.");
}
Map.Entry<String, JsonNode> member = union.fields().next();
return switch (member.getKey()) {
case "boolean" -> objectMapper.getNodeFactory().booleanNode(member.getValue().asBoolean());
case "long" -> objectMapper.getNodeFactory().numberNode(member.getValue().asLong());
case "string" -> objectMapper.getNodeFactory().textNode(member.getValue().asText());
case "entityIdentifier" -> explicitEntity(identifier(member.getValue(), "entityIdentifier"));
case "ipaddr" -> extension("ip", member.getValue().asText());
case "decimal" -> extension("decimal", member.getValue().asText());
case "datetime" -> extension("datetime", member.getValue().asText());
case "duration" -> extension("duration", member.getValue().asText());
case "set" -> {
if (!member.getValue().isArray()) {
throw VerifiedPermissionsService.validation("set must be an array.");
}
ArrayNode set = objectMapper.createArrayNode();
member.getValue().forEach(value -> set.add(cedarAttribute(value)));
yield set;
}
case "record" -> {
if (!member.getValue().isObject()) {
throw VerifiedPermissionsService.validation("record must be an object.");
}
ObjectNode record = objectMapper.createObjectNode();
member.getValue().fields().forEachRemaining(entry -> record.set(entry.getKey(), cedarAttribute(entry.getValue())));
yield record;
}
default -> throw VerifiedPermissionsService.validation("Unsupported attribute union member: " + member.getKey());
};
}
private ObjectNode explicitEntity(EntityIdentifier id) {
ObjectNode out = objectMapper.createObjectNode();
out.set("__entity", cedarEntity(id));
return out;
}
private ObjectNode cedarEntity(EntityIdentifier id) {
ObjectNode node = objectMapper.createObjectNode();
node.put("type", id.entityType());
node.put("id", id.entityId());
return node;
}
private ObjectNode extension(String fn, String arg) {
ObjectNode root = objectMapper.createObjectNode();
ObjectNode ext = root.putObject("__extn");
ext.put("fn", fn);
ext.put("arg", arg);
return root;
}
private static EntityIdentifier identifier(JsonNode node, String field) {
if (node == null || !node.isObject()) {
throw VerifiedPermissionsService.validation(field + " is required.");
}
String type = VerifiedPermissionsService.requiredText(node, node.has("entityType") ? "entityType" : "type");
String id = VerifiedPermissionsService.requiredText(node, node.has("entityId") ? "entityId" : "id");
return new EntityIdentifier(type, id);
}
public record EvaluationResult(String decision, List<String> determiningPolicyIds, List<String> errors) {}
}
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.verifiedpermissions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.verifiedpermissions.model.Policy;
import io.github.hectorvent.floci.services.verifiedpermissions.model.PolicyTemplate;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.Map;
/** HTTP client for the stateless Cedar 4 sidecar. */
@ApplicationScoped
public class CedarSidecarClient {
private final CedarSidecarManager manager;
private final ObjectMapper mapper;
private final HttpClient httpClient;
@Inject
public CedarSidecarClient(CedarSidecarManager manager, ObjectMapper mapper) {
this(manager, mapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
}
CedarSidecarClient(CedarSidecarManager manager, ObjectMapper mapper, HttpClient httpClient) {
this.manager = manager;
this.mapper = mapper;
this.httpClient = httpClient;
}
public void validateEntityType(String entityType) {
ObjectNode body = mapper.createObjectNode().put("entityType", entityType);
post("/v1/entity-type/validate", body, "entity type validation");
}
public void validateSchema(String schema) {
ObjectNode body = mapper.createObjectNode().put("schema", schema);
post("/v1/schema/validate", body, "schema validation");
}
public ParsedPolicy parsePolicy(String statement, boolean template) {
ObjectNode body = mapper.createObjectNode();
body.put("statement", statement);
body.put("template", template);
JsonNode response = post("/v1/policy/parse", body, "policy parsing");
return new ParsedPolicy(response.path("effect").asText(), response.path("ast").deepCopy());
}
public void validatePolicy(String schema, String statement, boolean template) {
ObjectNode body = mapper.createObjectNode();
body.put("schema", schema);
body.put("statement", statement);
body.put("template", template);
post("/v1/policy/validate", body, "policy validation");
}
public EvaluationResult authorize(JsonNode request, List<Policy> policies,
Map<String, PolicyTemplate> templates) {
ObjectNode body = mapper.createObjectNode();
body.set("request", request.deepCopy());
ArrayNode policyArray = body.putArray("policies");
policies.forEach(policy -> policyArray.add(mapper.valueToTree(policy)));
ObjectNode templateObject = body.putObject("templates");
templates.forEach((id, template) -> templateObject.set(id, mapper.valueToTree(template)));
JsonNode response = post("/v1/authorize", body, "authorization");
return new EvaluationResult(
response.path("decision").asText(),
stringList(response.path("determiningPolicyIds")),
stringList(response.path("errors")));
}
private List<String> stringList(JsonNode node) {
if (!node.isArray()) {
return List.of();
}
return java.util.stream.StreamSupport.stream(node.spliterator(), false)
.map(JsonNode::asText)
.toList();
}
private JsonNode post(String path, JsonNode body, String operation) {
try {
String baseUrl = manager.ensureReady();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + path))
.timeout(Duration.ofSeconds(30))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(body)))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
JsonNode responseBody = response.body() == null || response.body().isBlank()
? mapper.createObjectNode() : mapper.readTree(response.body());
if (response.statusCode() == 400) {
throw VerifiedPermissionsService.validation(responseBody.path("error").asText("Cedar " + operation + " failed."));
}
if (response.statusCode() != 200) {
throw new AwsException("InternalServerException",
"Cedar sidecar " + operation + " failed with HTTP " + response.statusCode() + ".", 500);
}
return responseBody;
} catch (AwsException e) {
throw e;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AwsException("InternalServerException", "Cedar sidecar " + operation + " was interrupted.", 500);
} catch (Exception e) {
throw new AwsException("InternalServerException",
"Failed to call Cedar sidecar for " + operation + ": " + safeMessage(e), 500);
}
}
private static String safeMessage(Exception e) {
String message = e.getMessage();
return message == null || message.isBlank() ? e.getClass().getSimpleName() : message;
}
public record ParsedPolicy(String effect, JsonNode ast) {}
public record EvaluationResult(String decision, List<String> determiningPolicyIds, List<String> errors) {}
}
@@ -0,0 +1,158 @@
package io.github.hectorvent.floci.services.verifiedpermissions;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.quarkus.runtime.ShutdownEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Optional;
/** Lazily starts and manages the Cedar 4 sidecar used by Amazon Verified Permissions. */
@ApplicationScoped
public class CedarSidecarManager {
private static final Logger LOG = Logger.getLogger(CedarSidecarManager.class);
private static final String CONTAINER_NAME = "floci-cedar";
private static final int CEDAR_PORT = 8180;
private static final int HEALTH_POLL_MAX_MS = 30_000;
private static final int HEALTH_POLL_INTERVAL_MS = 500;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final EmulatorConfig config;
private volatile String resolvedUrl;
private volatile String containerId;
@Inject
public CedarSidecarManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
EmulatorConfig config) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.config = config;
}
public synchronized boolean isAvailable() {
if (resolvedUrl != null) {
if (containerId == null || probeHealth(resolvedUrl)) {
return true;
}
discardStaleManagedEndpoint();
return false;
}
Optional<String> configured = config.services().verifiedpermissions().cedarUrl();
if (configured.isPresent() && !configured.get().isBlank()) {
String url = trimTrailingSlash(configured.get());
if (probeHealth(url)) {
resolvedUrl = url;
LOG.infov("Cedar sidecar is available at pre-configured URL: {0}", url);
return true;
}
}
return false;
}
public synchronized String ensureReady() {
if (resolvedUrl != null) {
if (containerId == null || probeHealth(resolvedUrl)) {
return resolvedUrl;
}
discardStaleManagedEndpoint();
}
Optional<String> configured = config.services().verifiedpermissions().cedarUrl();
if (configured.isPresent() && !configured.get().isBlank()) {
resolvedUrl = trimTrailingSlash(configured.get());
LOG.infov("Using pre-configured Cedar sidecar URL: {0}", resolvedUrl);
return resolvedUrl;
}
startContainer();
return resolvedUrl;
}
private void discardStaleManagedEndpoint() {
String staleUrl = resolvedUrl;
String staleContainerId = containerId;
resolvedUrl = null;
containerId = null;
LOG.warnv("Cedar sidecar at {0} is no longer healthy; restarting the managed container", staleUrl);
if (staleContainerId != null) {
try {
lifecycleManager.stopAndRemove(staleContainerId, null);
} catch (Exception e) {
LOG.debugv(e, "Failed to remove stale Cedar sidecar container {0}", staleContainerId);
}
}
}
private void startContainer() {
String image = config.services().verifiedpermissions().cedarImage();
LOG.infov("Starting Cedar sidecar container using image {0}", image);
String containerName = ContainerStorageHelper.dockerName(config, CONTAINER_NAME);
lifecycleManager.removeIfExists(containerName);
ContainerSpec spec = containerBuilder.newContainer(image)
.withName(containerName)
.withDynamicPort(CEDAR_PORT)
.withDockerNetwork(config.services().dockerNetwork())
.withEmbeddedDns()
.withLogRotation()
.build();
ContainerInfo info = lifecycleManager.createAndStart(spec);
EndpointInfo endpoint = info.getEndpoint(CEDAR_PORT);
containerId = info.containerId();
String url = "http://" + endpoint;
waitForHealth(url);
resolvedUrl = url;
LOG.infov("Cedar sidecar is ready at {0}", resolvedUrl);
}
private boolean probeHealth(String baseUrl) {
try {
HttpURLConnection connection = (HttpURLConnection) URI.create(baseUrl + "/health").toURL().openConnection();
connection.setConnectTimeout(500);
connection.setReadTimeout(500);
return connection.getResponseCode() == 200;
} catch (Exception e) {
LOG.debugv(e, "Cedar sidecar health probe failed for {0}", baseUrl);
return false;
}
}
private void waitForHealth(String baseUrl) {
long deadline = System.currentTimeMillis() + HEALTH_POLL_MAX_MS;
while (System.currentTimeMillis() < deadline) {
if (probeHealth(baseUrl)) {
return;
}
try {
Thread.sleep(HEALTH_POLL_INTERVAL_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted while waiting for Cedar sidecar", e);
}
}
throw new IllegalStateException("Cedar sidecar did not become healthy within " + HEALTH_POLL_MAX_MS + " ms");
}
void onStop(@Observes ShutdownEvent event) {
if (containerId == null) {
return;
}
LOG.info("Stopping Cedar sidecar container");
lifecycleManager.stopAndRemove(containerId, null);
}
private static String trimTrailingSlash(String url) {
return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
}
}
@@ -0,0 +1,589 @@
package io.github.hectorvent.floci.services.verifiedpermissions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.services.verifiedpermissions.model.IdentitySource;
import io.github.hectorvent.floci.services.verifiedpermissions.model.Policy;
import io.github.hectorvent.floci.services.verifiedpermissions.model.PolicyStore;
import io.github.hectorvent.floci.services.verifiedpermissions.model.PolicyStoreAlias;
import io.github.hectorvent.floci.services.verifiedpermissions.model.PolicyTemplate;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@ApplicationScoped
public class VerifiedPermissionsJsonHandler {
private final VerifiedPermissionsService service;
private final ObjectMapper objectMapper;
private final CedarAuthorizationEvaluator authorizationEvaluator;
private final VerifiedPermissionsTokenService tokenService;
@Inject
public VerifiedPermissionsJsonHandler(VerifiedPermissionsService service, ObjectMapper objectMapper,
CedarAuthorizationEvaluator authorizationEvaluator,
VerifiedPermissionsTokenService tokenService) {
this.service = service;
this.objectMapper = objectMapper;
this.authorizationEvaluator = authorizationEvaluator;
this.tokenService = tokenService;
}
public Response handle(String action, JsonNode request, String region) {
return switch (action) {
case "CreatePolicyStore" -> ok(policyStoreCreate(service.createPolicyStore(request, region)));
case "GetPolicyStore" -> ok(policyStoreDetail(service.getPolicyStore(
VerifiedPermissionsService.requiredText(request, "policyStoreId"), region), request.path("tags").asBoolean(false)));
case "UpdatePolicyStore" -> ok(policyStoreUpdate(service.updatePolicyStore(request, region)));
case "DeletePolicyStore" -> {
service.deletePolicyStore(VerifiedPermissionsService.requiredText(request, "policyStoreId"), region);
yield empty();
}
case "ListPolicyStores" -> ok(policyStoreList(service.listPolicyStores(request, region)));
case "PutSchema" -> ok(schemaPut(service.putSchema(request, region)));
case "GetSchema" -> ok(schemaGet(service.getSchema(
VerifiedPermissionsService.requiredText(request, "policyStoreId"), region)));
case "CreatePolicyTemplate" -> ok(policyTemplateDetail(service.createPolicyTemplate(request, region)));
case "GetPolicyTemplate" -> ok(policyTemplateDetail(service.getPolicyTemplate(
VerifiedPermissionsService.requiredText(request, "policyStoreId"),
VerifiedPermissionsService.requiredText(request, "policyTemplateId"), region)));
case "UpdatePolicyTemplate" -> ok(policyTemplateUpdate(service.updatePolicyTemplate(request, region)));
case "DeletePolicyTemplate" -> {
service.deletePolicyTemplate(VerifiedPermissionsService.requiredText(request, "policyStoreId"),
VerifiedPermissionsService.requiredText(request, "policyTemplateId"), region);
yield empty();
}
case "ListPolicyTemplates" -> ok(policyTemplateList(service.listPolicyTemplates(request, region)));
case "CreatePolicy" -> ok(policyCreateOrUpdate(service.createPolicy(request, region), region));
case "GetPolicy" -> ok(policyDetail(service.getPolicy(
VerifiedPermissionsService.requiredText(request, "policyStoreId"),
VerifiedPermissionsService.requiredText(request, "policyId"), region), region));
case "UpdatePolicy" -> ok(policyCreateOrUpdate(service.updatePolicy(request, region), region));
case "DeletePolicy" -> {
service.deletePolicy(VerifiedPermissionsService.requiredText(request, "policyStoreId"),
VerifiedPermissionsService.requiredText(request, "policyId"), region);
yield empty();
}
case "ListPolicies" -> ok(policyList(service.listPolicies(request, region), region));
case "CreateIdentitySource" -> ok(identitySourceWrite(service.createIdentitySource(request, region)));
case "GetIdentitySource" -> ok(identitySourceDetail(service.getIdentitySource(
VerifiedPermissionsService.requiredText(request, "policyStoreId"),
VerifiedPermissionsService.requiredText(request, "identitySourceId"), region)));
case "UpdateIdentitySource" -> ok(identitySourceWrite(service.updateIdentitySource(request, region)));
case "DeleteIdentitySource" -> {
service.deleteIdentitySource(VerifiedPermissionsService.requiredText(request, "policyStoreId"),
VerifiedPermissionsService.requiredText(request, "identitySourceId"), region);
yield empty();
}
case "ListIdentitySources" -> ok(identitySourceList(service.listIdentitySources(request, region)));
case "BatchGetPolicy" -> ok(batchGetPolicy(request, region));
case "IsAuthorized" -> ok(isAuthorized(request, region));
case "BatchIsAuthorized" -> ok(batchIsAuthorized(request, region));
case "IsAuthorizedWithToken" -> ok(isAuthorizedWithToken(request, region));
case "BatchIsAuthorizedWithToken" -> ok(batchIsAuthorizedWithToken(request, region));
case "CreatePolicyStoreAlias" -> ok(aliasCreate(service.createAlias(request, region)));
case "GetPolicyStoreAlias" -> ok(aliasDetail(service.getAlias(
VerifiedPermissionsService.requiredText(request, "aliasName"), region)));
case "ListPolicyStoreAliases" -> ok(aliasList(service.listAliases(request, region)));
case "DeletePolicyStoreAlias" -> {
service.deleteAlias(request, region);
yield empty();
}
case "TagResource" -> {
service.tagResource(VerifiedPermissionsService.requiredText(request, "resourceArn"),
stringMap(request.path("tags")), region);
yield empty();
}
case "UntagResource" -> {
service.untagResource(VerifiedPermissionsService.requiredText(request, "resourceArn"),
stringList(request.path("tagKeys")), region);
yield empty();
}
case "ListTagsForResource" -> ok(tags(service.listTags(
VerifiedPermissionsService.requiredText(request, "resourceArn"), region)));
default -> Response.status(400).entity(error("UnknownOperationException",
"Unknown operation: " + action)).build();
};
}
private ObjectNode policyStoreCreate(PolicyStore store) {
ObjectNode out = objectMapper.createObjectNode();
out.put("arn", store.arn());
time(out, "createdDate", store.createdDate());
time(out, "lastUpdatedDate", store.lastUpdatedDate());
out.put("policyStoreId", store.policyStoreId());
return out;
}
private ObjectNode policyStoreUpdate(PolicyStore store) {
return policyStoreCreate(store);
}
private ObjectNode policyStoreDetail(PolicyStore store, boolean includeTags) {
ObjectNode out = policyStoreCreate(store);
out.putObject("validationSettings").put("mode", store.validationMode());
out.put("cedarVersion", "CEDAR_4");
out.put("deletionProtection", store.deletionProtection());
if (store.description() != null) {
out.put("description", store.description());
}
ObjectNode encryptionState = out.putObject("encryptionState");
if (store.encryptionKeyArn() == null) {
encryptionState.putObject("default");
} else {
ObjectNode kms = encryptionState.putObject("kmsEncryptionState");
kms.put("key", store.encryptionKeyArn());
ObjectNode context = kms.putObject("encryptionContext");
store.encryptionContext().forEach(context::put);
}
if (includeTags && !store.tags().isEmpty()) {
ObjectNode tags = out.putObject("tags");
store.tags().forEach(tags::put);
}
return out;
}
private ObjectNode policyStoreList(PaginatedResult<PolicyStore> result) {
ObjectNode out = objectMapper.createObjectNode();
ArrayNode list = out.putArray("policyStores");
for (PolicyStore store : result.items()) {
ObjectNode item = list.addObject();
item.put("arn", store.arn());
time(item, "createdDate", store.createdDate());
time(item, "lastUpdatedDate", store.lastUpdatedDate());
item.put("policyStoreId", store.policyStoreId());
if (store.description() != null) {
item.put("description", store.description());
}
}
if (result.nextToken() != null) {
out.put("nextToken", result.nextToken());
}
return out;
}
private ObjectNode schemaPut(PolicyStore store) {
ObjectNode out = objectMapper.createObjectNode();
time(out, "createdDate", store.schemaCreatedDate());
time(out, "lastUpdatedDate", store.schemaLastUpdatedDate());
out.put("policyStoreId", store.policyStoreId());
ArrayNode namespaces = out.putArray("namespaces");
schemaNamespaces(store.schema()).forEach(namespaces::add);
return out;
}
private ObjectNode schemaGet(PolicyStore store) {
ObjectNode out = schemaPut(store);
out.put("schema", store.schema());
return out;
}
private List<String> schemaNamespaces(String schema) {
if (schema == null) {
return List.of();
}
try {
JsonNode parsed = objectMapper.readTree(schema);
if (!parsed.isObject()) {
return List.of();
}
java.util.ArrayList<String> names = new java.util.ArrayList<>();
parsed.fieldNames().forEachRemaining(names::add);
names.sort(String::compareTo);
return names;
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new IllegalStateException("Stored Verified Permissions schema is not valid JSON", e);
}
}
private ObjectNode identitySourceWrite(IdentitySource source) {
ObjectNode out = objectMapper.createObjectNode();
time(out, "createdDate", source.createdDate());
out.put("identitySourceId", source.identitySourceId());
time(out, "lastUpdatedDate", source.lastUpdatedDate());
out.put("policyStoreId", source.policyStoreId());
return out;
}
private ObjectNode identitySourceDetail(IdentitySource source) {
ObjectNode out = identitySourceWrite(source);
out.put("principalEntityType", source.principalEntityType());
out.set("configuration", source.configuration().deepCopy());
if (source.configuration().has("cognitoUserPoolConfiguration")) {
JsonNode cognito = source.configuration().get("cognitoUserPoolConfiguration");
ObjectNode details = out.putObject("details");
ArrayNode clients = details.putArray("clientIds");
if (cognito.path("clientIds").isArray()) {
cognito.path("clientIds").forEach(clients::add);
}
details.put("discoveryUrl", cognito.path("issuer").asText() + "/.well-known/openid-configuration");
details.put("openIdIssuer", "COGNITO");
details.put("userPoolArn", cognito.path("userPoolArn").asText());
}
return out;
}
private ObjectNode identitySourceList(PaginatedResult<IdentitySource> result) {
ObjectNode out = objectMapper.createObjectNode();
ArrayNode list = out.putArray("identitySources");
for (IdentitySource source : result.items()) {
list.add(identitySourceDetail(source));
}
if (result.nextToken() != null) {
out.put("nextToken", result.nextToken());
}
return out;
}
private ObjectNode isAuthorizedWithToken(JsonNode request, String region) {
VerifiedPermissionsTokenService.PreparedTokenRequest prepared = tokenService.prepare(request, region);
ObjectNode out = isAuthorized(prepared.request(), region);
addEntity(out, "principal", prepared.principal());
return out;
}
private ObjectNode batchIsAuthorizedWithToken(JsonNode request, String region) {
String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
service.getPolicyStore(storeIdentifier, region);
JsonNode requests = request.get("requests");
if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 30) {
throw VerifiedPermissionsService.validation("requests must contain between 1 and 30 items.");
}
ObjectNode out = objectMapper.createObjectNode();
ArrayNode results = out.putArray("results");
io.github.hectorvent.floci.services.verifiedpermissions.model.EntityIdentifier principal = null;
for (JsonNode item : requests) {
ObjectNode single = objectMapper.createObjectNode();
single.put("policyStoreId", storeIdentifier);
if (request.has("identityToken")) {
single.set("identityToken", request.get("identityToken"));
}
if (request.has("accessToken")) {
single.set("accessToken", request.get("accessToken"));
}
if (request.has("entities")) {
single.set("entities", request.get("entities"));
}
if (item.has("action")) {
single.set("action", item.get("action"));
}
if (item.has("resource")) {
single.set("resource", item.get("resource"));
}
if (item.has("context")) {
single.set("context", item.get("context"));
}
VerifiedPermissionsTokenService.PreparedTokenRequest prepared = tokenService.prepare(single, region);
if (principal == null) {
principal = prepared.principal();
}
CedarAuthorizationEvaluator.EvaluationResult evaluation = authorizationEvaluator.evaluate(prepared.request(),
service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
ObjectNode result = authorizationResult(evaluation);
result.set("request", item.deepCopy());
results.add(result);
}
addEntity(out, "principal", principal);
return out;
}
private ObjectNode isAuthorized(JsonNode request, String region) {
String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
service.getPolicyStore(storeIdentifier, region);
CedarAuthorizationEvaluator.EvaluationResult result = authorizationEvaluator.evaluate(request,
service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
return authorizationResult(result);
}
private ObjectNode batchIsAuthorized(JsonNode request, String region) {
String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
service.getPolicyStore(storeIdentifier, region);
JsonNode requests = request.get("requests");
if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 30) {
throw VerifiedPermissionsService.validation("requests must contain between 1 and 30 items.");
}
validateBatchSharedDimension(requests);
ObjectNode out = objectMapper.createObjectNode();
ArrayNode results = out.putArray("results");
for (JsonNode batchRequest : requests) {
ObjectNode evaluationRequest = batchRequest.deepCopy();
if (request.has("entities")) {
evaluationRequest.set("entities", request.get("entities"));
}
CedarAuthorizationEvaluator.EvaluationResult result = authorizationEvaluator.evaluate(evaluationRequest,
service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
ObjectNode item = authorizationResult(result);
item.set("request", batchRequest.deepCopy());
results.add(item);
}
return out;
}
private void validateBatchSharedDimension(JsonNode requests) {
String principal = null;
String resource = null;
boolean principalsSame = true;
boolean resourcesSame = true;
for (JsonNode item : requests) {
String nextPrincipal = item.has("principal") ? item.get("principal").toString() : "<absent>";
String nextResource = item.has("resource") ? item.get("resource").toString() : "<absent>";
if (principal == null) {
principal = nextPrincipal;
} else {
principalsSame &= principal.equals(nextPrincipal);
}
if (resource == null) {
resource = nextResource;
} else {
resourcesSame &= resource.equals(nextResource);
}
}
if (!principalsSame && !resourcesSame) {
throw VerifiedPermissionsService.validation("BatchIsAuthorized requires either the same principal or the same resource in every request.");
}
}
private ObjectNode authorizationResult(CedarAuthorizationEvaluator.EvaluationResult result) {
ObjectNode out = objectMapper.createObjectNode();
out.put("decision", result.decision());
ArrayNode determining = out.putArray("determiningPolicies");
result.determiningPolicyIds().forEach(id -> determining.addObject().put("policyId", id));
ArrayNode errors = out.putArray("errors");
result.errors().forEach(message -> errors.addObject().put("errorDescription", message));
return out;
}
private ObjectNode policyTemplateDetail(PolicyTemplate template) {
ObjectNode out = objectMapper.createObjectNode();
time(out, "createdDate", template.createdDate());
time(out, "lastUpdatedDate", template.lastUpdatedDate());
out.put("policyStoreId", template.policyStoreId());
out.put("policyTemplateId", template.policyTemplateId());
out.put("statement", template.statement());
if (template.description() != null) {
out.put("description", template.description());
}
if (template.name() != null) {
out.put("name", template.name());
}
return out;
}
private ObjectNode policyTemplateUpdate(PolicyTemplate template) {
ObjectNode out = objectMapper.createObjectNode();
time(out, "createdDate", template.createdDate());
time(out, "lastUpdatedDate", template.lastUpdatedDate());
out.put("policyStoreId", template.policyStoreId());
out.put("policyTemplateId", template.policyTemplateId());
return out;
}
private ObjectNode policyTemplateList(PaginatedResult<PolicyTemplate> result) {
ObjectNode out = objectMapper.createObjectNode();
ArrayNode list = out.putArray("policyTemplates");
for (PolicyTemplate template : result.items()) {
ObjectNode item = list.addObject();
time(item, "createdDate", template.createdDate());
time(item, "lastUpdatedDate", template.lastUpdatedDate());
item.put("policyStoreId", template.policyStoreId());
item.put("policyTemplateId", template.policyTemplateId());
if (template.description() != null) {
item.put("description", template.description());
}
if (template.name() != null) {
item.put("name", template.name());
}
}
if (result.nextToken() != null) {
out.put("nextToken", result.nextToken());
}
return out;
}
private ObjectNode policyCreateOrUpdate(Policy policy, String region) {
ObjectNode out = objectMapper.createObjectNode();
time(out, "createdDate", policy.createdDate());
time(out, "lastUpdatedDate", policy.lastUpdatedDate());
out.put("policyId", policy.policyId());
out.put("policyStoreId", policy.policyStoreId());
out.put("policyType", policy.policyType());
out.put("effect", policy.effect());
VerifiedPermissionsService.PolicyMetadata metadata = service.policyMetadata(policy, region);
ArrayNode actions = out.putArray("actions");
metadata.actions().forEach(action -> {
ObjectNode node = actions.addObject();
node.put("actionType", action.entityType());
node.put("actionId", action.entityId());
});
addEntity(out, "principal", metadata.principal());
addEntity(out, "resource", metadata.resource());
return out;
}
private ObjectNode policyDetail(Policy policy, String region) {
ObjectNode out = policyCreateOrUpdate(policy, region);
if (policy.name() != null) {
out.put("name", policy.name());
}
out.set("definition", policyDefinition(policy));
return out;
}
private ObjectNode policyDefinition(Policy policy) {
ObjectNode definition = objectMapper.createObjectNode();
if ("STATIC".equals(policy.policyType())) {
ObjectNode body = definition.putObject("static");
body.put("statement", policy.statement());
if (policy.description() != null) {
body.put("description", policy.description());
}
} else {
ObjectNode body = definition.putObject("templateLinked");
body.put("policyTemplateId", policy.policyTemplateId());
addEntity(body, "principal", policy.principal());
addEntity(body, "resource", policy.resource());
}
return definition;
}
private ObjectNode policyList(PaginatedResult<Policy> result, String region) {
ObjectNode out = objectMapper.createObjectNode();
ArrayNode list = out.putArray("policies");
for (Policy policy : result.items()) {
ObjectNode item = policyDetail(policy, region);
list.add(item);
}
if (result.nextToken() != null) {
out.put("nextToken", result.nextToken());
}
return out;
}
private ObjectNode batchGetPolicy(JsonNode request, String region) {
JsonNode requests = request.get("requests");
if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 100) {
throw VerifiedPermissionsService.validation("requests must contain between 1 and 100 items.");
}
ObjectNode out = objectMapper.createObjectNode();
ArrayNode results = out.putArray("results");
ArrayNode errors = out.putArray("errors");
for (JsonNode item : requests) {
String store = VerifiedPermissionsService.requiredText(item, "policyStoreId");
String policy = VerifiedPermissionsService.requiredText(item, "policyId");
try {
results.add(policyDetail(service.getPolicy(store, policy, region), region));
} catch (io.github.hectorvent.floci.core.common.AwsException e) {
ObjectNode error = errors.addObject();
error.put("policyStoreId", store);
error.put("policyId", policy);
boolean alias = store.startsWith("policy-store-alias/");
if (alias) {
error.put("code", "POLICY_STORE_ALIAS_NOT_FOUND");
} else if ("ResourceNotFoundException".equals(e.getErrorCode()) && !storeExists(store, region)) {
error.put("code", "POLICY_STORE_NOT_FOUND");
} else {
error.put("code", "POLICY_NOT_FOUND");
}
error.put("message", e.getMessage());
}
}
return out;
}
private boolean storeExists(String id, String region) {
try { service.getPolicyStore(id, region); return true; }
catch (io.github.hectorvent.floci.core.common.AwsException e) { return false; }
}
private static void addEntity(ObjectNode out, String field, io.github.hectorvent.floci.services.verifiedpermissions.model.EntityIdentifier entity) {
if (entity == null) {
return;
}
ObjectNode node = out.putObject(field);
node.put("entityType", entity.entityType());
node.put("entityId", entity.entityId());
}
private ObjectNode aliasCreate(PolicyStoreAlias alias) {
ObjectNode out = objectMapper.createObjectNode();
out.put("aliasArn", alias.aliasArn());
out.put("aliasName", alias.aliasName());
time(out, "createdAt", alias.createdAt());
out.put("policyStoreId", alias.policyStoreId());
return out;
}
private ObjectNode aliasDetail(PolicyStoreAlias alias) {
ObjectNode out = aliasCreate(alias);
out.put("state", alias.state());
return out;
}
private ObjectNode aliasList(PaginatedResult<PolicyStoreAlias> result) {
ObjectNode out = objectMapper.createObjectNode();
ArrayNode list = out.putArray("policyStoreAliases");
result.items().forEach(a -> list.add(aliasDetail(a)));
if (result.nextToken() != null) {
out.put("nextToken", result.nextToken());
}
return out;
}
private ObjectNode tags(Map<String, String> values) {
ObjectNode out = objectMapper.createObjectNode();
ObjectNode tags = out.putObject("tags");
values.forEach(tags::put);
return out;
}
private Map<String, String> stringMap(JsonNode node) {
if (!node.isObject()) {
throw VerifiedPermissionsService.validation("tags is required.");
}
Map<String, String> out = new java.util.LinkedHashMap<>();
node.fields().forEachRemaining(e -> {
if (!e.getValue().isTextual()) {
throw VerifiedPermissionsService.validation("Tag values must be strings.");
}
out.put(e.getKey(), e.getValue().asText());
});
return out;
}
private List<String> stringList(JsonNode node) {
if (!node.isArray()) {
throw VerifiedPermissionsService.validation("tagKeys is required.");
}
java.util.ArrayList<String> out = new java.util.ArrayList<>();
node.forEach(v -> {
if (!v.isTextual()) {
throw VerifiedPermissionsService.validation("tagKeys must contain strings.");
}
out.add(v.asText());
});
return out;
}
private static void time(ObjectNode node, String field, Instant value) {
if (value != null) {
node.put(field, value.toString());
}
}
private Response ok(JsonNode body) { return Response.ok(body).build(); }
private Response empty() { return Response.ok(objectMapper.createObjectNode()).build(); }
private ObjectNode error(String type, String message) {
ObjectNode node = objectMapper.createObjectNode();
node.put("__type", type);
node.put("message", message);
return node;
}
}
@@ -0,0 +1,371 @@
package io.github.hectorvent.floci.services.verifiedpermissions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
import org.apache.hc.core5.util.Timeout;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ApplicationScoped
public class VerifiedPermissionsOidcSignatureVerifier implements AutoCloseable {
private static final Logger LOG = Logger.getLogger(VerifiedPermissionsOidcSignatureVerifier.class);
private static final Duration CACHE_TTL = Duration.ofMinutes(10);
private static final Duration UNKNOWN_KID_REFRESH_COOLDOWN = Duration.ofMinutes(1);
private static final Duration HTTP_TIMEOUT = Duration.ofSeconds(10);
static final int MAX_OIDC_DOCUMENT_BYTES = 1024 * 1024;
private final ObjectMapper objectMapper;
private final CloseableHttpClient httpClient;
private final Map<String, CachedJwks> jwksCache = new ConcurrentHashMap<>();
private final Map<String, Instant> unknownKidRefreshes = new ConcurrentHashMap<>();
private final Map<String, Object> issuerLocks = new ConcurrentHashMap<>();
@Inject
public VerifiedPermissionsOidcSignatureVerifier(ObjectMapper objectMapper) {
this(objectMapper, SystemDefaultDnsResolver.INSTANCE);
}
VerifiedPermissionsOidcSignatureVerifier(ObjectMapper objectMapper, DnsResolver dnsResolver) {
this.objectMapper = objectMapper;
DnsResolver validatingResolver = new PublicOnlyDnsResolver(dnsResolver);
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.of(HTTP_TIMEOUT))
.setSocketTimeout(Timeout.of(HTTP_TIMEOUT))
.build();
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
.setDnsResolver(validatingResolver)
.setDefaultConnectionConfig(connectionConfig)
.build();
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(Timeout.of(HTTP_TIMEOUT))
.setResponseTimeout(Timeout.of(HTTP_TIMEOUT))
.setRedirectsEnabled(false)
.build();
this.httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.disableRedirectHandling()
.disableAutomaticRetries()
.disableCookieManagement()
.build();
}
public void verify(String token, String issuer) throws VerificationException {
validatePublicHttpsUri(issuer, "OIDC issuer");
String[] parts = token == null ? new String[0] : token.split("\\.", -1);
if (parts.length != 3) {
throw new VerificationException("Token is not a well-formed JWT");
}
JsonNode header = decodeJson(parts[0]);
String alg = header.path("alg").asText("");
if (!"RS256".equals(alg)) {
throw new VerificationException("Unsupported token signing algorithm: " + (alg.isEmpty() ? "none" : alg));
}
String kid = header.path("kid").asText(null);
if (kid == null || kid.isBlank()) {
throw new VerificationException("Token header has no kid");
}
RSAPublicKey key = resolveKey(issuer, kid);
if (key == null) {
throw new VerificationException("No JWKS key matches kid '" + kid + "' for issuer " + issuer);
}
if (!signatureValid(parts[0] + "." + parts[1], parts[2], key)) {
throw new VerificationException("Token signature is invalid");
}
}
RSAPublicKey resolveKey(String issuer, String kid) throws VerificationException {
Object lock = issuerLocks.computeIfAbsent(issuer, ignored -> new Object());
synchronized (lock) {
Instant now = Instant.now();
CachedJwks cached = jwksCache.get(issuer);
if (cached == null || cached.expired()) {
Map<String, RSAPublicKey> fetched = fetchJwks(issuer);
jwksCache.put(issuer, new CachedJwks(fetched, now));
if (!fetched.containsKey(kid)) {
unknownKidRefreshes.put(issuer, now);
}
return fetched.get(kid);
}
RSAPublicKey cachedKey = cached.keysByKid().get(kid);
if (cachedKey != null) {
return cachedKey;
}
Instant lastRefresh = unknownKidRefreshes.get(issuer);
if (lastRefresh != null && now.isBefore(lastRefresh.plus(UNKNOWN_KID_REFRESH_COOLDOWN))) {
return null;
}
Map<String, RSAPublicKey> refreshed = fetchJwks(issuer);
unknownKidRefreshes.put(issuer, now);
jwksCache.put(issuer, new CachedJwks(refreshed, now));
return refreshed.get(kid);
}
}
Map<String, RSAPublicKey> fetchJwks(String issuer) throws VerificationException {
String discoveryUrl = issuer.replaceAll("/+$", "") + "/.well-known/openid-configuration";
JsonNode discovery = getJson(discoveryUrl, "OIDC discovery document");
String jwksUri = discovery.path("jwks_uri").asText(null);
if (jwksUri == null || jwksUri.isBlank()) {
throw new VerificationException("OIDC discovery document has no jwks_uri");
}
validatePublicHttpsUri(jwksUri, "JWKS document");
JsonNode jwks = getJson(jwksUri, "JWKS document");
JsonNode keys = jwks.path("keys");
if (!keys.isArray()) {
throw new VerificationException("JWKS document has no keys array");
}
Map<String, RSAPublicKey> result = new ConcurrentHashMap<>();
for (JsonNode jwk : keys) {
String kty = jwk.path("kty").asText("");
String keyId = jwk.path("kid").asText(null);
if (!"RSA".equals(kty) || keyId == null || keyId.isBlank()) {
continue;
}
String modulus = jwk.path("n").asText(null);
String exponent = jwk.path("e").asText(null);
if (modulus == null || exponent == null) {
continue;
}
try {
result.put(keyId, toRsaPublicKey(modulus, exponent));
} catch (GeneralSecurityException | IllegalArgumentException e) {
LOG.debugv("Skipping unparsable OIDC key {0}: {1}", keyId, e.getMessage());
}
}
return result;
}
private JsonNode getJson(String url, String description) throws VerificationException {
URI uri = validatePublicHttpsUri(url, description);
HttpClientContext context = HttpClientContext.create();
try {
return httpClient.execute(ClassicRequestBuilder.get(uri).build(), context, response -> {
if (response.getCode() >= 300 && response.getCode() < 400) {
throw new VerificationException("Redirects aren't allowed while fetching " + description);
}
if (response.getCode() != HttpStatus.SC_OK) {
throw new VerificationException("Fetching " + description + " returned HTTP " + response.getCode());
}
byte[] body;
if (response.getEntity() == null) {
body = new byte[0];
} else {
try (InputStream input = response.getEntity().getContent()) {
body = readBoundedBody(input, response.getEntity().getContentLength(), description);
}
}
try {
return objectMapper.readTree(body);
} catch (Exception e) {
throw new VerificationException(description + " is not valid JSON", e);
}
});
} catch (VerificationException e) {
throw e;
} catch (Exception e) {
throw new VerificationException("Failed to fetch " + description, e);
}
}
static byte[] readBoundedBody(InputStream input, long contentLength, String description)
throws IOException, VerificationException {
if (contentLength > MAX_OIDC_DOCUMENT_BYTES) {
throw new VerificationException(description + " exceeds the maximum allowed response size");
}
byte[] body = input.readNBytes(MAX_OIDC_DOCUMENT_BYTES + 1);
if (body.length > MAX_OIDC_DOCUMENT_BYTES) {
throw new VerificationException(description + " exceeds the maximum allowed response size");
}
return body;
}
static URI validatePublicHttpsUri(String value, String description) throws VerificationException {
URI uri;
try {
uri = URI.create(value);
} catch (IllegalArgumentException e) {
throw new VerificationException("Invalid " + description + " URL", e);
}
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getHost().isBlank()
|| uri.getUserInfo() != null) {
throw new VerificationException(description + " must use a public HTTPS URL");
}
String host = uri.getHost();
boolean literalAddress = host.indexOf(':') >= 0 || host.matches("[0-9]{1,3}(?:\\.[0-9]{1,3}){3}");
if (literalAddress && isBlockedPublicAddress(InetAddress.ofLiteral(host))) {
throw new VerificationException(description + " resolves to a non-public address");
}
return uri;
}
private static RSAPublicKey toRsaPublicKey(String n, String e) throws GeneralSecurityException {
BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(pad(n)));
BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(pad(e)));
return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent));
}
private static boolean signatureValid(String signingInput, String encodedSignature, RSAPublicKey key) {
try {
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initVerify(key);
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
return signature.verify(Base64.getUrlDecoder().decode(pad(encodedSignature)));
} catch (GeneralSecurityException | IllegalArgumentException e) {
return false;
}
}
private JsonNode decodeJson(String segment) throws VerificationException {
try {
JsonNode node = objectMapper.readTree(Base64.getUrlDecoder().decode(pad(segment)));
if (node == null || !node.isObject()) {
throw new VerificationException("Token header is not valid JSON");
}
return node;
} catch (IllegalArgumentException | java.io.IOException e) {
throw new VerificationException("Token header is not valid JSON", e);
}
}
private static String pad(String value) {
return switch (value.length() % 4) {
case 2 -> value + "==";
case 3 -> value + "=";
default -> value;
};
}
@PreDestroy
@Override
public void close() {
try {
httpClient.close();
} catch (Exception e) {
LOG.debugv("Could not close Verified Permissions OIDC client: {0}", e.getMessage());
}
}
private record CachedJwks(Map<String, RSAPublicKey> keysByKid, Instant fetchedAt) {
boolean expired() {
return Instant.now().isAfter(fetchedAt.plus(CACHE_TTL));
}
}
private record PublicOnlyDnsResolver(DnsResolver delegate) implements DnsResolver {
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {
InetAddress[] addresses = delegate.resolve(host);
if (addresses == null || addresses.length == 0) {
throw new UnknownHostException("OIDC host has no addresses: " + host);
}
for (InetAddress address : addresses) {
if (isBlockedPublicAddress(address)) {
throw new UnknownHostException("OIDC host resolves to a non-public address: " + host);
}
}
return addresses.clone();
}
@Override
public String resolveCanonicalHostname(String host) {
return host;
}
}
static boolean isBlockedPublicAddress(InetAddress address) {
if (address.isAnyLocalAddress() || address.isLoopbackAddress()
|| address.isLinkLocalAddress() || address.isSiteLocalAddress()
|| address.isMulticastAddress()) {
return true;
}
byte[] bytes = address.getAddress();
if (bytes.length == 4) {
return blockedIpv4(bytes, 0);
}
if (bytes.length == 16) {
if (ipv4Mapped(bytes)) {
return blockedIpv4(bytes, 12);
}
int first = Byte.toUnsignedInt(bytes[0]);
boolean uniqueLocal = (first & 0xfe) == 0xfc;
boolean documentation = first == 0x20
&& Byte.toUnsignedInt(bytes[1]) == 0x01
&& Byte.toUnsignedInt(bytes[2]) == 0x0d
&& Byte.toUnsignedInt(bytes[3]) == 0xb8;
return uniqueLocal || documentation;
}
return true;
}
private static boolean ipv4Mapped(byte[] bytes) {
for (int i = 0; i < 10; i++) {
if (bytes[i] != 0) {
return false;
}
}
return bytes[10] == (byte) 0xff && bytes[11] == (byte) 0xff;
}
private static boolean blockedIpv4(byte[] bytes, int offset) {
int first = Byte.toUnsignedInt(bytes[offset]);
int second = Byte.toUnsignedInt(bytes[offset + 1]);
int third = Byte.toUnsignedInt(bytes[offset + 2]);
return first == 0
|| first == 10
|| first == 127
|| (first == 100 && second >= 64 && second <= 127)
|| (first == 169 && second == 254)
|| (first == 172 && second >= 16 && second <= 31)
|| (first == 192 && second == 168)
|| (first == 192 && second == 0 && third == 0)
|| (first == 192 && second == 0 && third == 2)
|| (first == 198 && (second == 18 || second == 19))
|| (first == 198 && second == 51 && third == 100)
|| (first == 203 && second == 0 && third == 113)
|| first >= 224;
}
public static class VerificationException extends RuntimeException {
public VerificationException(String message) {
super(message);
}
public VerificationException(String message, Throwable cause) {
super(message, cause);
}
}
}
@@ -0,0 +1,307 @@
package io.github.hectorvent.floci.services.verifiedpermissions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.verifiedpermissions.model.EntityIdentifier;
import io.github.hectorvent.floci.services.verifiedpermissions.model.IdentitySource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
@ApplicationScoped
public class VerifiedPermissionsTokenService {
private final VerifiedPermissionsService service;
private final CedarAuthorizationEvaluator evaluator;
private final VerifiedPermissionsOidcSignatureVerifier signatureVerifier;
private final ObjectMapper objectMapper;
@Inject
public VerifiedPermissionsTokenService(VerifiedPermissionsService service,
CedarAuthorizationEvaluator evaluator,
VerifiedPermissionsOidcSignatureVerifier signatureVerifier,
ObjectMapper objectMapper) {
this.service = service;
this.evaluator = evaluator;
this.signatureVerifier = signatureVerifier;
this.objectMapper = objectMapper;
}
public PreparedTokenRequest prepare(JsonNode request, String region) {
String store = VerifiedPermissionsService.requiredText(request, "policyStoreId");
String identityToken = VerifiedPermissionsService.text(request, "identityToken", null);
String accessToken = VerifiedPermissionsService.text(request, "accessToken", null);
if ((identityToken == null || identityToken.isBlank()) && (accessToken == null || accessToken.isBlank())) {
throw VerifiedPermissionsService.validation("You must specify identityToken, accessToken, or both.");
}
TokenInfo identity = identityToken == null ? null : validateToken(store, identityToken, TokenKind.IDENTITY, region);
TokenInfo access = accessToken == null ? null : validateToken(store, accessToken, TokenKind.ACCESS, region);
TokenInfo principalToken = identity != null ? identity : access;
if (identity != null && access != null
&& (!identity.principal().equals(access.principal()) || !identity.source().identitySourceId().equals(access.source().identitySourceId()))) {
throw VerifiedPermissionsService.validation("identityToken and accessToken must identify the same principal and identity source.");
}
ObjectNode prepared = request.deepCopy();
prepared.remove(List.of("identityToken", "accessToken"));
ObjectNode principal = prepared.putObject("principal");
principal.put("entityType", principalToken.principal().entityType());
principal.put("entityId", principalToken.principal().entityId());
JsonNode identityClaims = identity == null ? null : identity.claims();
List<EntityIdentifier> parents = mergeParents(identity, access);
prepared.set("entities", evaluator.appendTokenPrincipal(prepared.get("entities"), principalToken.principal(), identityClaims, parents));
if (access != null) {
prepared.set("context", mergeAccessContext(prepared.get("context"), access.claims()));
}
return new PreparedTokenRequest(prepared, principalToken.principal());
}
private TokenInfo validateToken(String store, String token, TokenKind requestedKind, String region) {
JsonNode claims = decodeClaims(token);
String issuer = claims.path("iss").asText(null);
if (issuer == null || issuer.isBlank()) {
throw VerifiedPermissionsService.validation("Token has no issuer claim.");
}
IdentitySource source = service.identitySourcesForStore(store, region).stream()
.filter(candidate -> issuer.equals(VerifiedPermissionsService.identityIssuer(candidate.configuration())))
.findFirst().orElseThrow(() -> VerifiedPermissionsService.validation("No identity source matches the token issuer."));
try {
signatureVerifier.verify(token, issuer);
} catch (VerifiedPermissionsOidcSignatureVerifier.VerificationException e) {
throw VerifiedPermissionsService.validation("Token signature validation failed: " + e.getMessage());
}
validateTimes(claims);
JsonNode configuration = source.configuration();
if (configuration.has("cognitoUserPoolConfiguration")) {
return validateCognito(source, claims, requestedKind);
}
return validateOidc(source, claims, requestedKind);
}
private TokenInfo validateCognito(IdentitySource source, JsonNode claims, TokenKind requestedKind) {
String expectedUse = requestedKind == TokenKind.IDENTITY ? "id" : "access";
if (!expectedUse.equals(claims.path("token_use").asText())) {
throw VerifiedPermissionsService.validation("The submitted token has the wrong token_use claim.");
}
JsonNode config = source.configuration().get("cognitoUserPoolConfiguration");
JsonNode clients = config.path("clientIds");
if (clients.isArray() && !clients.isEmpty()) {
String actual = requestedKind == TokenKind.IDENTITY ? claims.path("aud").asText(null) : claims.path("client_id").asText(null);
if (actual == null || !arrayContains(clients, actual)) {
throw VerifiedPermissionsService.validation("The token client application isn't allowed by this identity source.");
}
}
String sub = requiredClaim(claims, "sub");
String poolId = config.path("userPoolArn").asText().substring(config.path("userPoolArn").asText().lastIndexOf('/') + 1);
EntityIdentifier principal = new EntityIdentifier(source.principalEntityType(), poolId + "|" + sub);
return new TokenInfo(source, claims, principal, groupParents(source, claims, poolId, "cognito:groups"));
}
private TokenInfo validateOidc(IdentitySource source, JsonNode claims, TokenKind requestedKind) {
JsonNode config = source.configuration().get("openIdConnectConfiguration");
JsonNode selection = config.path("tokenSelection");
boolean accessConfigured = selection.has("accessTokenOnly");
if ((requestedKind == TokenKind.ACCESS) != accessConfigured) {
throw VerifiedPermissionsService.validation("The token type isn't enabled for this OIDC identity source.");
}
JsonNode tokenConfig = accessConfigured ? selection.get("accessTokenOnly") : selection.get("identityTokenOnly");
JsonNode accepted = accessConfigured ? tokenConfig.path("audiences") : tokenConfig.path("clientIds");
if (accepted.isArray() && !accepted.isEmpty() && !audienceMatches(claims.get("aud"), accepted)) {
throw VerifiedPermissionsService.validation("The token audience isn't allowed by this identity source.");
}
String principalClaim = tokenConfig.path("principalIdClaim").asText("sub");
String principalId = requiredClaim(claims, principalClaim);
String prefix = config.path("entityIdPrefix").asText("");
String composed = prefix.isEmpty() ? principalId : prefix + "|" + principalId;
EntityIdentifier principal = new EntityIdentifier(source.principalEntityType(), composed);
String groupClaim = config.path("groupConfiguration").path("groupClaim").asText(null);
return new TokenInfo(source, claims, principal, groupClaim == null ? List.of() : groupParents(source, claims, prefix, groupClaim));
}
private List<EntityIdentifier> groupParents(IdentitySource source, JsonNode claims, String prefix, String claimName) {
JsonNode groupConfiguration = source.configuration().has("cognitoUserPoolConfiguration")
? source.configuration().path("cognitoUserPoolConfiguration").path("groupConfiguration")
: source.configuration().path("openIdConnectConfiguration").path("groupConfiguration");
String groupType = groupConfiguration.path("groupEntityType").asText(null);
if (groupType == null) {
return List.of();
}
JsonNode groups = claims.get(claimName);
if (groups == null || groups.isNull()) {
return List.of();
}
List<EntityIdentifier> result = new ArrayList<>();
if (groups.isArray()) {
groups.forEach(group -> result.add(new EntityIdentifier(groupType, qualify(prefix, group.asText()))));
} else if (groups.isTextual()) {
result.add(new EntityIdentifier(groupType, qualify(prefix, groups.asText())));
}
return result;
}
private static String qualify(String prefix, String value) {
return prefix == null || prefix.isEmpty() ? value : prefix + "|" + value;
}
private List<EntityIdentifier> mergeParents(TokenInfo identity, TokenInfo access) {
java.util.LinkedHashSet<EntityIdentifier> parents = new java.util.LinkedHashSet<>();
if (identity != null) {
parents.addAll(identity.parents());
}
if (access != null) {
parents.addAll(access.parents());
}
return new ArrayList<>(parents);
}
private ObjectNode mergeAccessContext(JsonNode existing, JsonNode claims) {
ObjectNode root;
try {
if (existing == null || existing.isNull()) {
root = objectMapper.createObjectNode();
} else if (existing.has("cedarJson")) {
JsonNode parsed = objectMapper.readTree(existing.path("cedarJson").asText());
if (!parsed.isObject()) {
throw VerifiedPermissionsService.validation("context.cedarJson must encode an object.");
}
root = (ObjectNode) parsed.deepCopy();
} else if (existing.has("contextMap")) {
root = contextMapToRaw(existing.get("contextMap"));
} else {
throw VerifiedPermissionsService.validation("context must contain cedarJson or contextMap.");
}
} catch (java.io.IOException e) {
throw VerifiedPermissionsService.validation("context.cedarJson isn't valid JSON.");
}
ObjectNode token = root.putObject("token");
claims.fields().forEachRemaining(entry -> {
if (!"cognito:groups".equals(entry.getKey()) && claimSupported(entry.getValue())) {
token.set(entry.getKey(), entry.getValue().deepCopy());
}
});
ObjectNode union = objectMapper.createObjectNode();
union.put("cedarJson", root.toString());
return union;
}
private ObjectNode contextMapToRaw(JsonNode map) {
ObjectNode result = objectMapper.createObjectNode();
map.fields().forEachRemaining(entry -> result.set(entry.getKey(), rawAttribute(entry.getValue())));
return result;
}
private JsonNode rawAttribute(JsonNode union) {
if (!union.isObject() || union.size() != 1) {
throw VerifiedPermissionsService.validation("Context attributes must contain one union member.");
}
var entry = union.fields().next();
return switch (entry.getKey()) {
case "boolean", "long", "string" -> entry.getValue().deepCopy();
case "set" -> {
var array = objectMapper.createArrayNode();
entry.getValue().forEach(v -> array.add(rawAttribute(v)));
yield array;
}
case "record" -> contextMapToRaw(entry.getValue());
default -> throw VerifiedPermissionsService.validation("Token context merge doesn't support attribute type " + entry.getKey() + ".");
};
}
private JsonNode decodeClaims(String token) {
String[] parts = token == null ? new String[0] : token.split("\\.", -1);
if (parts.length != 3) {
throw VerifiedPermissionsService.validation("Token isn't a well-formed JWT.");
}
try {
byte[] decoded = Base64.getUrlDecoder().decode(pad(parts[1]));
JsonNode claims = objectMapper.readTree(new String(decoded, StandardCharsets.UTF_8));
if (claims == null || !claims.isObject()) {
throw VerifiedPermissionsService.validation("Token claims aren't a JSON object.");
}
return claims;
} catch (IllegalArgumentException | java.io.IOException e) {
throw VerifiedPermissionsService.validation("Token payload isn't valid base64url JSON.");
}
}
private static void validateTimes(JsonNode claims) {
long now = Instant.now().getEpochSecond();
if (!claims.has("exp") || !claims.get("exp").canConvertToLong() || claims.get("exp").asLong() <= now) {
throw VerifiedPermissionsService.validation("Token is expired or has no valid exp claim.");
}
if (claims.has("nbf") && claims.get("nbf").canConvertToLong() && claims.get("nbf").asLong() > now) {
throw VerifiedPermissionsService.validation("Token isn't valid yet.");
}
}
private static String requiredClaim(JsonNode claims, String name) {
JsonNode value = claims.get(name);
if (value == null || !value.isValueNode() || value.asText().isEmpty()) {
throw VerifiedPermissionsService.validation("Token is missing required principal claim " + name + ".");
}
return value.asText();
}
private static boolean arrayContains(JsonNode array, String value) {
for (JsonNode item : array) {
if (value.equals(item.asText())) {
return true;
}
}
return false;
}
private static boolean audienceMatches(JsonNode actual, JsonNode accepted) {
if (actual == null) {
return false;
}
if (actual.isTextual()) {
return arrayContains(accepted, actual.asText());
}
if (actual.isArray()) {
for (JsonNode item : actual) {
if (arrayContains(accepted, item.asText())) {
return true;
}
}
}
return false;
}
private static boolean claimSupported(JsonNode value) {
if (value == null || value.isNull()) {
return false;
}
if (value.isTextual() || value.isBoolean() || value.isIntegralNumber()) {
return true;
}
if (value.isArray()) {
for (JsonNode item : value) {
if (!(item.isTextual() || item.isBoolean() || item.isIntegralNumber())) {
return false;
}
}
return true;
}
return false;
}
private static String pad(String value) {
return switch (value.length() % 4) {
case 2 -> value + "==";
case 3 -> value + "=";
default -> value;
};
}
private enum TokenKind { IDENTITY, ACCESS }
private record TokenInfo(IdentitySource source, JsonNode claims, EntityIdentifier principal,
List<EntityIdentifier> parents) {}
public record PreparedTokenRequest(ObjectNode request, EntityIdentifier principal) {}
}
@@ -0,0 +1,6 @@
package io.github.hectorvent.floci.services.verifiedpermissions.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public record EntityIdentifier(String entityType, String entityId) {}
@@ -0,0 +1,14 @@
package io.github.hectorvent.floci.services.verifiedpermissions.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@RegisterForReflection
public record IdempotencyRecord(
String operation,
String token,
String requestFingerprint,
String resourceId,
String policyStoreId,
Instant createdAt) {}
@@ -0,0 +1,21 @@
package io.github.hectorvent.floci.services.verifiedpermissions.model;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@RegisterForReflection
public record IdentitySource(
String policyStoreId,
String identitySourceId,
String principalEntityType,
JsonNode configuration,
Instant createdDate,
Instant lastUpdatedDate) {
public IdentitySource updated(String nextPrincipalEntityType, JsonNode nextConfiguration, Instant updatedAt) {
return new IdentitySource(policyStoreId, identitySourceId, nextPrincipalEntityType,
nextConfiguration, createdDate, updatedAt);
}
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.services.verifiedpermissions.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@RegisterForReflection
public record Policy(
String policyStoreId,
String policyId,
String name,
String policyType,
String statement,
String description,
String policyTemplateId,
EntityIdentifier principal,
EntityIdentifier resource,
String effect,
Instant createdDate,
Instant lastUpdatedDate) {
public Policy updated(String nextName, String nextStatement, String nextDescription, Instant updatedAt) {
return new Policy(policyStoreId, policyId, nextName, policyType, nextStatement, nextDescription,
policyTemplateId, principal, resource, effect, createdDate, updatedAt);
}
}
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.services.verifiedpermissions.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
@RegisterForReflection
public record PolicyStore(
String policyStoreId,
String arn,
String validationMode,
String deletionProtection,
String description,
String encryptionKeyArn,
Map<String, String> encryptionContext,
Map<String, String> tags,
String schema,
Instant schemaCreatedDate,
Instant schemaLastUpdatedDate,
Instant createdDate,
Instant lastUpdatedDate) {
public PolicyStore {
encryptionContext = encryptionContext == null ? new LinkedHashMap<>() : new LinkedHashMap<>(encryptionContext);
tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags);
}
public PolicyStore withSchema(String nextSchema, Instant created, Instant updated) {
return new PolicyStore(policyStoreId, arn, validationMode, deletionProtection, description,
encryptionKeyArn, encryptionContext, tags, nextSchema, created, updated, createdDate, updated);
}
public PolicyStore withSettings(String mode, String deletion, String nextDescription, Instant updated) {
return new PolicyStore(policyStoreId, arn, mode, deletion, nextDescription, encryptionKeyArn, encryptionContext, tags,
schema, schemaCreatedDate, schemaLastUpdatedDate, createdDate, updated);
}
public PolicyStore withTags(Map<String, String> nextTags, Instant updated) {
return new PolicyStore(policyStoreId, arn, validationMode, deletionProtection, description,
encryptionKeyArn, encryptionContext, nextTags, schema, schemaCreatedDate, schemaLastUpdatedDate, createdDate, updated);
}
}
@@ -0,0 +1,19 @@
package io.github.hectorvent.floci.services.verifiedpermissions.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@RegisterForReflection
public record PolicyStoreAlias(
String aliasName,
String aliasArn,
String policyStoreId,
String state,
Instant createdAt,
Instant deleteAfter) {
public PolicyStoreAlias pendingDeletion(Instant deleteAfter) {
return new PolicyStoreAlias(aliasName, aliasArn, policyStoreId, "PendingDeletion", createdAt, deleteAfter);
}
}
@@ -0,0 +1,20 @@
package io.github.hectorvent.floci.services.verifiedpermissions.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
@RegisterForReflection
public record PolicyTemplate(
String policyStoreId,
String policyTemplateId,
String name,
String statement,
String description,
Instant createdDate,
Instant lastUpdatedDate) {
public PolicyTemplate updated(String nextName, String nextStatement, String nextDescription, Instant updatedAt) {
return new PolicyTemplate(policyStoreId, policyTemplateId, nextName, nextStatement, nextDescription,
createdDate, updatedAt);
}
}