diff --git a/.dockerignore b/.dockerignore
index 83238f2ce0..9360c05d9d 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -14,3 +14,4 @@
!native/**
!.mvn/**
!mvnw
+!sidecars/cedar/**
diff --git a/.github/workflows/build-images.yml b/.github/workflows/build-images.yml
index a9ff01bd94..6d7d564456 100644
--- a/.github/workflows/build-images.yml
+++ b/.github/workflows/build-images.yml
@@ -42,6 +42,12 @@ on:
jvm-digest-ref:
description: Immutable JVM image reference
value: ${{ jobs.publish.outputs.jvm-digest-ref }}
+ cedar-ref:
+ description: Commit-tagged Cedar sidecar image reference
+ value: ${{ jobs.publish.outputs.cedar-ref }}
+ cedar-digest-ref:
+ description: Immutable Cedar sidecar image reference
+ value: ${{ jobs.publish.outputs.cedar-digest-ref }}
native-ref:
description: Commit-tagged native image reference when publish-native is true
value: ${{ jobs.publish.outputs.native-ref }}
@@ -259,6 +265,8 @@ jobs:
compat-digest-ref: ${{ steps.provenance.outputs.compat-digest-ref }}
jvm-ref: ${{ steps.provenance.outputs.jvm-ref }}
jvm-digest-ref: ${{ steps.provenance.outputs.jvm-digest-ref }}
+ cedar-ref: ${{ steps.provenance.outputs.cedar-ref }}
+ cedar-digest-ref: ${{ steps.provenance.outputs.cedar-digest-ref }}
native-ref: ${{ steps.provenance.outputs.native-ref }}
native-digest-ref: ${{ steps.provenance.outputs.native-digest-ref }}
@@ -334,6 +342,29 @@ jobs:
cache-from: type=gha,scope=floci-jvm
cache-to: type=gha,scope=floci-jvm,mode=max
+ - name: Build and publish Cedar sidecar image
+ id: cedar
+ uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
+ env:
+ SOURCE_DATE_EPOCH: ${{ steps.metadata.outputs.source-date-epoch }}
+ with:
+ context: .
+ file: sidecars/cedar/Dockerfile
+ platforms: linux/amd64,linux/arm64
+ push: true
+ tags: ${{ needs.prepare.outputs.image }}:${{ needs.prepare.outputs.image-tag }}-cedar
+ labels: |
+ org.opencontainers.image.version=${{ needs.prepare.outputs.product-version }}
+ org.opencontainers.image.revision=${{ needs.prepare.outputs.source-sha }}
+ org.opencontainers.image.vcs-ref=${{ needs.prepare.outputs.source-sha }}
+ org.opencontainers.image.created=${{ steps.metadata.outputs.created }}
+ org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
+ version=${{ needs.prepare.outputs.product-version }}
+ build-date=${{ steps.metadata.outputs.created }}
+ vcs-ref=${{ needs.prepare.outputs.source-sha }}
+ cache-from: type=gha,scope=floci-cedar
+ cache-to: type=gha,scope=floci-cedar,mode=max
+
- name: Build and publish native image
id: native
if: inputs.publish-native
@@ -390,6 +421,7 @@ jobs:
- name: Record image provenance
id: provenance
env:
+ CEDAR_DIGEST: ${{ steps.cedar.outputs.digest }}
COMPAT_DIGEST: ${{ steps.compat.outputs.digest }}
CREATED: ${{ steps.metadata.outputs.created }}
IMAGE: ${{ needs.prepare.outputs.image }}
@@ -408,6 +440,8 @@ jobs:
run: |
jvm_ref="$IMAGE:$IMAGE_TAG"
jvm_digest_ref="$IMAGE@$JVM_DIGEST"
+ cedar_ref="$IMAGE:$IMAGE_TAG-cedar"
+ cedar_digest_ref="$IMAGE@$CEDAR_DIGEST"
native_ref="$IMAGE:$IMAGE_TAG-native"
compat_ref="$IMAGE:$IMAGE_TAG-native-compat"
native_digest_ref="$IMAGE@$NATIVE_DIGEST"
@@ -427,7 +461,10 @@ jobs:
--arg jvmRef "$jvm_ref" \
--arg jvmDigest "$JVM_DIGEST" \
--arg jvmDigestRef "$jvm_digest_ref" \
- '{source: {sha: $sourceSha, requestedRef: $requestedSourceRef, repository: $repository}, workflow: {runId: $runId, attempt: $runAttempt, url: $runUrl}, created: $created, imageTag: $imageTag, productVersion: $productVersion, images: {jvm: {ref: $jvmRef, digest: $jvmDigest, digestRef: $jvmDigestRef, dockerfile: "docker/Dockerfile"}}, platforms: ["linux/amd64", "linux/arm64"]}' \
+ --arg cedarRef "$cedar_ref" \
+ --arg cedarDigest "$CEDAR_DIGEST" \
+ --arg cedarDigestRef "$cedar_digest_ref" \
+ '{source: {sha: $sourceSha, requestedRef: $requestedSourceRef, repository: $repository}, workflow: {runId: $runId, attempt: $runAttempt, url: $runUrl}, created: $created, imageTag: $imageTag, productVersion: $productVersion, images: {jvm: {ref: $jvmRef, digest: $jvmDigest, digestRef: $jvmDigestRef, dockerfile: "docker/Dockerfile"}, cedar: {ref: $cedarRef, digest: $cedarDigest, digestRef: $cedarDigestRef, dockerfile: "sidecars/cedar/Dockerfile"}}, platforms: ["linux/amd64", "linux/arm64"]}' \
> floci-image-provenance.json
if [[ "$PUBLISH_NATIVE" == "true" ]]; then
@@ -447,6 +484,8 @@ jobs:
{
echo "jvm-ref=$jvm_ref"
echo "jvm-digest-ref=$jvm_digest_ref"
+ echo "cedar-ref=$cedar_ref"
+ echo "cedar-digest-ref=$cedar_digest_ref"
if [[ "$PUBLISH_NATIVE" == "true" ]]; then
echo "native-ref=$native_ref"
echo "native-digest-ref=$native_digest_ref"
@@ -464,6 +503,7 @@ jobs:
echo "| Image tag | Immutable digest reference |"
echo "| --- | --- |"
echo "| \`$jvm_ref\` | \`$jvm_digest_ref\` |"
+ echo "| \`$cedar_ref\` | \`$cedar_digest_ref\` |"
if [[ "$PUBLISH_NATIVE" == "true" ]]; then
echo "| \`$native_ref\` | \`$native_digest_ref\` |"
echo "| \`$compat_ref\` | \`$compat_digest_ref\` |"
diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml
index 59bc128d99..d12a55baea 100644
--- a/.github/workflows/compatibility.yml
+++ b/.github/workflows/compatibility.yml
@@ -4,6 +4,7 @@ on:
pull_request:
paths:
- 'src/**'
+ - 'sidecars/cedar/**'
- 'pom.xml'
- 'docker/Dockerfile.native-package'
- 'docker/Dockerfile.compat'
@@ -124,6 +125,7 @@ jobs:
with:
sparse-checkout: |
compatibility-tests
+ sidecars/cedar
.github/ci
- name: Compare compat-terraform and compat-opentofu resource lists
@@ -298,6 +300,10 @@ jobs:
- name: Start floci
run: |
DOCKER_GID=$(stat -c '%g' /var/run/docker.sock)
+ EXTRA_ENV=""
+ if [ "${{ matrix.test }}" = "sdk-test-java" ]; then
+ EXTRA_ENV="-e FLOCI_SERVICES_VERIFIEDPERMISSIONS_CEDAR_URL=http://floci-cedar:8180"
+ fi
docker run -d --name floci --network compat-net \
-p 4566:4566 \
-v /var/run/docker.sock:/var/run/docker.sock \
@@ -307,6 +313,7 @@ jobs:
-e FLOCI_HOSTNAME=floci \
-e FLOCI_SERVICES_IOT_MQTT_ENABLED=true \
-e FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true \
+ $EXTRA_ENV \
-e FLOCI_TLS_ENABLED=true \
-e FLOCI_SERVICES_EC2_MOCK=true \
-e FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST=floci \
@@ -341,8 +348,24 @@ jobs:
with:
sparse-checkout: |
compatibility-tests
+ sidecars/cedar
.github/ci
+ - name: Build and start Cedar sidecar
+ if: matrix.test == 'sdk-test-java'
+ run: |
+ docker build -f sidecars/cedar/Dockerfile -t floci-cedar:test .
+ docker run -d --name floci-cedar --network compat-net -p 18180:8180 floci-cedar:test
+ for _ in $(seq 1 60); do
+ if curl --fail --silent http://127.0.0.1:18180/health >/dev/null; then
+ exit 0
+ fi
+ sleep 1
+ done
+ echo "::error::Cedar sidecar did not become healthy"
+ docker logs floci-cedar
+ exit 1
+
- uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
- name: Build test image
diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml
index 2cdd7db353..b8c0f5601a 100644
--- a/.github/workflows/nightly.yml
+++ b/.github/workflows/nightly.yml
@@ -8,6 +8,7 @@ name: Nightly
#
# Published tags:
# Native: floci/floci:nightly floci/floci:nightly-mmddyyyy
+# Cedar: floci/floci:nightly-cedar floci/floci:nightly-mmddyyyy-cedar
# Compat: floci/floci:nightly-compat floci/floci:nightly-mmddyyyy-compat
#
# Required secrets: DOCKERHUB_USERNAME, DOCKERHUB_TOKEN, AWS_ROLE_ARN
@@ -232,6 +233,30 @@ jobs:
cache-from: type=gha
cache-to: type=gha,mode=max
+ - name: Build and push Cedar sidecar nightly image
+ uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
+ env:
+ SOURCE_DATE_EPOCH: ${{ steps.source_date.outputs.epoch }}
+ with:
+ context: .
+ file: sidecars/cedar/Dockerfile
+ platforms: linux/amd64,linux/arm64
+ push: true
+ tags: |
+ floci/floci:nightly-cedar
+ floci/floci:nightly-${{ needs.prepare.outputs.version }}-cedar
+ public.ecr.aws/floci/floci:nightly-cedar
+ public.ecr.aws/floci/floci:nightly-${{ needs.prepare.outputs.version }}-cedar
+ labels: |
+ org.opencontainers.image.version=nightly-${{ needs.prepare.outputs.version }}
+ org.opencontainers.image.revision=${{ github.sha }}
+ org.opencontainers.image.created=${{ steps.created.outputs.created }}
+ version=nightly-${{ needs.prepare.outputs.version }}
+ build-date=${{ steps.created.outputs.created }}
+ vcs-ref=${{ github.sha }}
+ cache-from: type=gha,scope=floci-cedar
+ cache-to: type=gha,scope=floci-cedar,mode=max
+
- name: Build and push compat nightly image
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
env:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index cce1182a36..04a8576378 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -7,6 +7,8 @@ name: Release
# Published tags:
# Native: floci/floci:1.2.3 floci/floci:latest
# public.ecr.aws/floci/floci:1.2.3 public.ecr.aws/floci/floci:latest
+# Cedar: floci/floci:1.2.3-cedar floci/floci:latest-cedar
+# public.ecr.aws/floci/floci:1.2.3-cedar public.ecr.aws/floci/floci:latest-cedar
# Compat: floci/floci:1.2.3-compat floci/floci:latest-compat
# public.ecr.aws/floci/floci:1.2.3-compat public.ecr.aws/floci/floci:latest-compat
#
@@ -182,6 +184,32 @@ jobs:
cache-from: type=gha
cache-to: type=gha,mode=max
+ - name: Build and push Cedar sidecar multi-arch image
+ uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
+ env:
+ SOURCE_DATE_EPOCH: ${{ steps.source_date.outputs.epoch }}
+ with:
+ context: .
+ file: sidecars/cedar/Dockerfile
+ platforms: linux/amd64,linux/arm64
+ push: true
+ provenance: mode=max
+ sbom: true
+ tags: |
+ floci/floci:${{ steps.version.outputs.version }}-cedar
+ floci/floci:latest-cedar
+ public.ecr.aws/floci/floci:${{ steps.version.outputs.version }}-cedar
+ public.ecr.aws/floci/floci:latest-cedar
+ labels: |
+ org.opencontainers.image.version=${{ steps.version.outputs.version }}
+ org.opencontainers.image.revision=${{ github.sha }}
+ org.opencontainers.image.created=${{ steps.created.outputs.created }}
+ version=${{ steps.version.outputs.version }}
+ build-date=${{ steps.created.outputs.created }}
+ vcs-ref=${{ github.sha }}
+ cache-from: type=gha,scope=floci-cedar
+ cache-to: type=gha,scope=floci-cedar,mode=max
+
- name: Build and push compat multi-arch image
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
env:
diff --git a/README.md b/README.md
index fc24a07fd3..4f1ba22edc 100644
--- a/README.md
+++ b/README.md
@@ -238,7 +238,7 @@ Floci supports local emulation for application services, data services, eventing
| Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock Runtime, Bedrock AgentCore |
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core, Amazon Connect |
-| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Control Catalog, Control Tower, Service Catalog, AWS Marketplace |
+| Security and governance | AWS Network Firewall, AWS RAM, Service Quotas, WAF v2, GuardDuty, Amazon Inspector, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations, AWS Account Management, IAM Access Analyzer, IAM Identity Center (SSO Admin, OIDC, Access Portal, SCIM), Identity Store, Amazon Macie, Amazon Detective, Security Hub, Amazon Verified Permissions, Control Catalog, Control Tower, Service Catalog, AWS Marketplace |
| Cost and billing | AWS Budgets, Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 00c1f3b7ad..cfb5782809 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -491,6 +491,11 @@
software.amazon.awssdk
ssooidc
+
+
+ software.amazon.awssdk
+ verifiedpermissions
+
software.amazon.awssdk
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 5b2a5cfd11..60be856329 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -43,6 +43,7 @@ import software.amazon.awssdk.services.controlcatalog.ControlCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceentitlement.MarketplaceEntitlementClient;
+import software.amazon.awssdk.services.verifiedpermissions.VerifiedPermissionsClient;
import software.amazon.awssdk.services.inspector2.Inspector2Client;
import software.amazon.awssdk.services.securityhub.SecurityHubClient;
import software.amazon.awssdk.services.detective.DetectiveClient;
@@ -446,6 +447,14 @@ public final class TestFixtures {
.build();
}
+ public static VerifiedPermissionsClient verifiedPermissionsClient() {
+ return VerifiedPermissionsClient.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
public static DetectiveClient detectiveClient(String accountId) {
return DetectiveClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/VerifiedPermissionsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/VerifiedPermissionsTest.java
new file mode 100644
index 0000000000..f830bbe59d
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/VerifiedPermissionsTest.java
@@ -0,0 +1,124 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.verifiedpermissions.VerifiedPermissionsClient;
+import software.amazon.awssdk.services.verifiedpermissions.model.ActionIdentifier;
+import software.amazon.awssdk.services.verifiedpermissions.model.Decision;
+import software.amazon.awssdk.services.verifiedpermissions.model.EntitiesDefinition;
+import software.amazon.awssdk.services.verifiedpermissions.model.EntityIdentifier;
+import software.amazon.awssdk.services.verifiedpermissions.model.PolicyDefinition;
+import software.amazon.awssdk.services.verifiedpermissions.model.PolicyEffect;
+import software.amazon.awssdk.services.verifiedpermissions.model.PolicyType;
+import software.amazon.awssdk.services.verifiedpermissions.model.SchemaDefinition;
+import software.amazon.awssdk.services.verifiedpermissions.model.StaticPolicyDefinition;
+import software.amazon.awssdk.services.verifiedpermissions.model.ValidationException;
+import software.amazon.awssdk.services.verifiedpermissions.model.ValidationMode;
+import software.amazon.awssdk.services.verifiedpermissions.model.ValidationSettings;
+
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+@DisplayName("Amazon Verified Permissions")
+class VerifiedPermissionsTest {
+
+ @Test
+ @DisplayName("policy store, schema, policies, aliases and Cedar authorization use AWS SDK v2")
+ void lifecycleAndAuthorizationUseAwsSdk() {
+ assumeFalse(TestFixtures.isRealAws(), "Creates emulator-only policy data");
+
+ try (VerifiedPermissionsClient avp = TestFixtures.verifiedPermissionsClient()) {
+ String policyStoreId = avp.createPolicyStore(request -> request
+ .validationSettings(ValidationSettings.builder().mode(ValidationMode.OFF).build())
+ .tags(Map.of("project", "floci")))
+ .policyStoreId();
+
+ var store = avp.getPolicyStore(request -> request.policyStoreId(policyStoreId).tags(true));
+ assertThat(store.policyStoreId()).isEqualTo(policyStoreId);
+ assertThat(store.tags()).containsEntry("project", "floci");
+
+ String schema = """
+ {"Demo":{"entityTypes":{
+ "User":{"shape":{"type":"Record","attributes":{"tenant":{"type":"String","required":true}}}},
+ "Document":{"shape":{"type":"Record","attributes":{"tenant":{"type":"String","required":true}}}}
+ },"actions":{"read":{"appliesTo":{"principalTypes":["User"],"resourceTypes":["Document"]}}}}}
+ """;
+ avp.putSchema(request -> request.policyStoreId(policyStoreId)
+ .definition(SchemaDefinition.builder().cedarJson(schema).build()));
+
+ String statement = "permit(principal, action == Demo::Action::\"read\", resource) "
+ + "when { principal.tenant == resource.tenant };";
+ String policyId = avp.createPolicy(request -> request
+ .policyStoreId(policyStoreId)
+ .name("name/tenant-reader")
+ .definition(PolicyDefinition.builder().staticValue(StaticPolicyDefinition.builder()
+ .statement(statement).description("tenant reader").build()).build()))
+ .policyId();
+
+ assertThat(avp.getPolicy(request -> request.policyStoreId(policyStoreId).policyId("name/tenant-reader"))
+ .policyId()).isEqualTo(policyId);
+ assertThat(avp.listPolicies(request -> request.policyStoreId(policyStoreId)).policies())
+ .anySatisfy(policy -> {
+ assertThat(policy.policyId()).isEqualTo(policyId);
+ assertThat(policy.policyType()).isEqualTo(PolicyType.STATIC);
+ assertThat(policy.effect()).isEqualTo(PolicyEffect.PERMIT);
+ });
+
+ String entities = """
+ [
+ {"uid":{"type":"Demo::User","id":"alice"},"attrs":{"tenant":"t1"},"parents":[]},
+ {"uid":{"type":"Demo::Document","id":"doc1"},"attrs":{"tenant":"t1"},"parents":[]}
+ ]
+ """;
+ var decision = avp.isAuthorized(request -> request
+ .policyStoreId(policyStoreId)
+ .principal(EntityIdentifier.builder().entityType("Demo::User").entityId("alice").build())
+ .action(ActionIdentifier.builder().actionType("Demo::Action").actionId("read").build())
+ .resource(EntityIdentifier.builder().entityType("Demo::Document").entityId("doc1").build())
+ .entities(EntitiesDefinition.builder().cedarJson(entities).build()));
+ assertThat(decision.decision()).isEqualTo(Decision.ALLOW);
+ assertThat(decision.determiningPolicies()).extracting(p -> p.policyId()).contains(policyId);
+
+ String alias = "policy-store-alias/" + TestFixtures.uniqueName("avp");
+ avp.createPolicyStoreAlias(request -> request.aliasName(alias).policyStoreId(policyStoreId));
+ assertThat(avp.getPolicyStore(request -> request.policyStoreId(alias)).policyStoreId())
+ .isEqualTo(policyStoreId);
+ avp.deletePolicyStoreAlias(request -> request.aliasName(alias).deletionMode(software.amazon.awssdk.services.verifiedpermissions.model.DeletionMode.HARD_DELETE));
+
+ String token = "sdk-idempotency-123";
+ String first = avp.createPolicyStore(request -> request.clientToken(token)
+ .validationSettings(ValidationSettings.builder().mode(ValidationMode.OFF).build()))
+ .policyStoreId();
+ String replay = avp.createPolicyStore(request -> request.clientToken(token)
+ .validationSettings(ValidationSettings.builder().mode(ValidationMode.OFF).build()))
+ .policyStoreId();
+ assertThat(replay).isEqualTo(first);
+ assertThatThrownBy(() -> avp.createPolicyStore(request -> request.clientToken(token)
+ .validationSettings(ValidationSettings.builder().mode(ValidationMode.STRICT).build())))
+ .isInstanceOf(software.amazon.awssdk.services.verifiedpermissions.model.ConflictException.class);
+
+ avp.deletePolicy(request -> request.policyStoreId(policyStoreId).policyId(policyId));
+ avp.deletePolicyStore(request -> request.policyStoreId(policyStoreId));
+ }
+ }
+
+ @Test
+ @DisplayName("STRICT validation rejects policies that do not match the schema")
+ void strictValidationUsesCedarSchema() {
+ assumeFalse(TestFixtures.isRealAws(), "Creates emulator-only policy data");
+
+ try (VerifiedPermissionsClient avp = TestFixtures.verifiedPermissionsClient()) {
+ String store = avp.createPolicyStore(request -> request
+ .validationSettings(ValidationSettings.builder().mode(ValidationMode.STRICT).build()))
+ .policyStoreId();
+ assertThatThrownBy(() -> avp.createPolicy(request -> request
+ .policyStoreId(store)
+ .definition(PolicyDefinition.builder().staticValue(StaticPolicyDefinition.builder()
+ .statement("permit(principal, action, resource);").build()).build())))
+ .isInstanceOf(ValidationException.class);
+ }
+ }
+}
diff --git a/docker/Dockerfile.native-package b/docker/Dockerfile.native-package
index 8e3061eb64..2d32e65cbc 100644
--- a/docker/Dockerfile.native-package
+++ b/docker/Dockerfile.native-package
@@ -19,7 +19,6 @@ COPY --chmod=755 docker/localstack-parity.sh docker/healthcheck.sh /usr/local/bi
ARG VERSION=latest
ENV FLOCI_VERSION=${VERSION}
ENV FLOCI_STORAGE_PERSISTENT_PATH=/app/data
-
COPY --chmod=755 --chown=1001:root native/${TARGETARCH}/ /app/
LABEL org.opencontainers.image.title="Floci" \
diff --git a/docs/services/index.md b/docs/services/index.md
index 5fd8dd7002..b171d81282 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -52,6 +52,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Identity Store](identitystore.md) | `POST /` + `X-Amz-Target: AWSIdentityStore.*` | JSON 1.1 | 19 |
| [Amazon Macie](macie2.md) | `/admin`, `/macie`, `/admin/configuration` | REST JSON | 6 |
| [Amazon Inspector](inspector2.md) | `/delegatedadminaccounts/*`, `/status/batch/get`, `/enable`, `/organizationconfiguration/*` | REST JSON | 7 |
+| [Amazon Verified Permissions](verifiedpermissions.md) | `POST /` + `X-Amz-Target: VerifiedPermissions.*` | JSON 1.0 | 34 |
| [Security Hub](securityhub.md) | `/organization/*`, `/accounts`, `/findingAggregator/*`, `/configurationPolicy*`, `/tags/*` | REST JSON | 22 |
| [Amazon Detective](detective.md) | `/orgs/*`, `/graphs/list`, `/graph/*` | REST JSON | 8 |
| [Amazon Connect](connect.md) | `/instance`, `/instance/{instanceId}/*`, `/tags/*` | REST JSON | 15 |
diff --git a/docs/services/verifiedpermissions.md b/docs/services/verifiedpermissions.md
new file mode 100644
index 0000000000..5119b38b90
--- /dev/null
+++ b/docs/services/verifiedpermissions.md
@@ -0,0 +1,143 @@
+# Amazon Verified Permissions
+
+**Protocol:** JSON 1.0 (`X-Amz-Target: VerifiedPermissions.*`)
+**Endpoint:** `POST http://localhost:4566/`
+**Signing name:** `verifiedpermissions`
+
+Floci implements the Amazon Verified Permissions control plane and authorization APIs with
+persistent policy stores, schemas, policies, policy templates, policy store aliases, identity
+sources, tags, and idempotency state. Authorization decisions are evaluated with the official
+Cedar Java engine rather than a service-specific policy shortcut.
+
+Policy stores support `OFF` and `STRICT` validation. In `STRICT` mode, Floci parses the stored
+Cedar JSON schema and validates new or updated static policies and policy templates before
+storing them. Static and template-linked policies participate in `IsAuthorized` and batch
+authorization decisions, including Cedar entity hierarchies, attributes, tags, context values,
+and the standard Cedar extension values accepted by the AVP API model.
+
+Policy store aliases resolve anywhere AVP accepts a policy store ID. Soft-deleted aliases remain
+reserved in `PendingDeletion` state for 24 hours and stop resolving to the policy store. Hard
+delete removes the alias immediately. Create operations that accept `clientToken` persist an
+8-hour idempotency record and reject token reuse with different request parameters.
+
+Identity sources support Amazon Cognito user pools and generic OpenID Connect issuers.
+`IsAuthorizedWithToken` and `BatchIsAuthorizedWithToken` validate JWT signatures through the
+issuer's OIDC discovery and JWKS endpoints, check token lifetime and configured audiences or
+client IDs, and project token claims into Cedar principal entities or `context.token` according
+to the AVP token type.
+
+## Supported Actions
+
+
+| Action | Description |
+| --- | --- |
+| `CreatePolicyStore` | Creates a policy store with validation, deletion protection, tags, encryption settings, and idempotency |
+| `GetPolicyStore` | Returns policy store validation, encryption, deletion-protection, and optional tag state |
+| `UpdatePolicyStore` | Updates validation mode, deletion protection, and description |
+| `DeletePolicyStore` | Deletes an unprotected policy store and its child resources; aliases are rejected as identifiers |
+| `ListPolicyStores` | Lists policy stores with pagination |
+| `PutSchema` | Creates, replaces, or removes the Cedar JSON schema |
+| `GetSchema` | Returns the current Cedar JSON schema and namespace metadata |
+| `CreatePolicyTemplate` | Creates a Cedar policy template with persisted idempotency state |
+| `GetPolicyTemplate` | Returns a policy template and supports `name/` aliases |
+| `UpdatePolicyTemplate` | Updates a Cedar policy template and name or description metadata |
+| `DeletePolicyTemplate` | Deletes an unused policy template |
+| `ListPolicyTemplates` | Lists policy templates with pagination |
+| `CreatePolicy` | Creates static or template-linked Cedar policies with persisted idempotency state |
+| `GetPolicy` | Returns static or template-linked policy details and supports `name/` aliases |
+| `UpdatePolicy` | Updates the mutable fields of a static policy while preserving effect, principal, and resource scope |
+| `DeletePolicy` | Deletes a policy |
+| `ListPolicies` | Lists policies with policy type, template, principal, and resource filtering and pagination |
+| `CreateIdentitySource` | Creates a Cognito or OIDC identity source with persisted idempotency state |
+| `GetIdentitySource` | Returns an identity source and its normalized Cognito or OIDC configuration |
+| `UpdateIdentitySource` | Replaces an identity source configuration without changing the provider family |
+| `DeleteIdentitySource` | Deletes an identity source |
+| `ListIdentitySources` | Lists identity sources with principal-entity-type filtering and pagination |
+| `BatchGetPolicy` | Gets up to 100 policies and reports per-item not-found errors |
+| `IsAuthorized` | Evaluates Cedar policies against supplied principal, action, resource, entities, and context |
+| `BatchIsAuthorized` | Evaluates up to 30 Cedar authorization requests that share a principal or resource |
+| `IsAuthorizedWithToken` | Validates an identity or access token and evaluates the resulting Cedar request |
+| `BatchIsAuthorizedWithToken` | Evaluates up to 30 authorization requests using an identity or access token |
+| `CreatePolicyStoreAlias` | Creates an active alias for a policy store |
+| `GetPolicyStoreAlias` | Returns alias target and lifecycle state |
+| `ListPolicyStoreAliases` | Lists aliases with policy-store filtering and pagination |
+| `DeletePolicyStoreAlias` | Soft-deletes an alias for 24 hours or hard-deletes it immediately |
+| `TagResource` | Adds or replaces policy store tags |
+| `UntagResource` | Removes policy store tags |
+| `ListTagsForResource` | Returns policy store tags |
+
+
+## Cedar evaluation
+
+Cedar parsing, schema validation, and authorization run in a lazily started Cedar 4 sidecar. The
+main Floci JVM and native images do not include Cedar Java or its multi-platform native runtime.
+This follows the same isolation pattern as `floci-duck`: Floci starts the sidecar on the first
+Cedar-dependent AVP operation, probes its health endpoint, and reuses it until shutdown. A
+pre-configured sidecar URL can be supplied when Docker Compose or another supervisor owns the
+sidecar lifecycle.
+
+The sidecar is required by operations that parse or validate Cedar, including `PutSchema`,
+identity-source entity-type validation, policy and policy-template create/update paths, and all
+`IsAuthorized*` and `BatchIsAuthorized*` evaluation paths. Read-only control-plane operations that
+do not parse or evaluate Cedar do not start the sidecar. If Docker is unavailable and
+`FLOCI_SERVICES_VERIFIEDPERMISSIONS_CEDAR_URL` is not configured, a sidecar-dependent operation
+returns the modeled `InternalServerException` response with HTTP 500. Configure an externally
+managed sidecar URL when running Floci without access to Docker.
+
+The sidecar is stateless. Each authorization request includes the relevant policies, templates,
+entities, and context, so policy-store isolation does not depend on mutable shared sidecar state.
+It uses Cedar Java 4.10.0 to preserve the `CEDAR_4` behavior advertised by AVP. A matching
+`forbid` policy overrides matching `permit` policies through Cedar's normal decision semantics.
+
+`entities.cedarJson` is passed directly to Cedar. `entities.entityList` is translated to Cedar
+JSON and supports booleans, longs, strings, entity references, IP addresses, decimals,
+datetimes, durations, sets, records, entity parents, and entity tags. When duplicate entity
+identifiers are supplied in an entity list, the last definition wins.
+
+## Identity sources and tokens
+
+Cognito identity sources derive the OIDC issuer from the user pool ARN, enforce same-Region user
+pools, optional app client IDs, group entity mapping, and AVP's `|`
+principal identifier convention. OIDC identity sources support identity-token-only or
+access-token-only selection, accepted client IDs or audiences, principal ID claims, entity ID
+prefixes, and group claims.
+
+Token authorization uses the issuer discovery document and JWKS endpoint and currently verifies
+RS256 signatures. The token must contain a valid `exp`, must not be before `nbf`, and must match
+the configured token type and audience or client ID. Identity-token claims become principal
+attributes. Access-token claims are exposed under `context.token`.
+
+## Persistence and isolation
+
+Policy stores and all child resources use Floci's configured storage backend. Keys include the
+resolved AWS Region and are wrapped by the normal account-aware storage layer, preserving
+account and Region isolation. `/_floci/reset` clears policy stores, policies, templates,
+aliases, identity sources, and idempotency records with other resettable service state.
+
+## Limitations
+
+- Token verification currently supports RS256 JWT signatures. Other OIDC signing algorithms are
+ rejected rather than accepted without verification.
+- Identity source creation validates the configured issuer shape and AVP relationships, but does
+ not contact the issuer until a token authorization request requires OIDC discovery or JWKS.
+- The emulator applies state changes synchronously. AWS may expose short eventual-consistency
+ windows after some AVP mutations.
+- KMS-backed policy stores resolve and persist the configured KMS key ARN and encryption context,
+ but local policy bytes are not encrypted at rest by Floci's storage backend.
+
+## Configuration
+
+| Environment variable | Default | Description |
+| --- | --- | --- |
+| `FLOCI_SERVICES_VERIFIEDPERMISSIONS_ENABLED` | `true` | Enables Amazon Verified Permissions |
+| `FLOCI_SERVICES_VERIFIEDPERMISSIONS_CEDAR_URL` | unset | Uses an externally managed Cedar sidecar URL and skips container management |
+| `FLOCI_SERVICES_VERIFIEDPERMISSIONS_CEDAR_IMAGE` | `floci/floci:latest-cedar` | Image used for the lazily managed Cedar 4 sidecar |
+
+## Examples
+
+```bash
+aws --endpoint-url http://localhost:4566 verifiedpermissions create-policy-store \
+ --validation-settings mode=OFF
+
+aws --endpoint-url http://localhost:4566 verifiedpermissions list-policy-stores
+```
diff --git a/mkdocs.yml b/mkdocs.yml
index 689f0ff3a5..7ac4c3369e 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -130,6 +130,7 @@ nav:
- Amazon Inspector: services/inspector2.md
- Security Hub: services/securityhub.md
- Amazon Detective: services/detective.md
+ - Amazon Verified Permissions: services/verifiedpermissions.md
- Control Catalog: services/controlcatalog.md
- AWS Marketplace: services/marketplace.md
- Control Tower: services/controltower.md
diff --git a/pom.xml b/pom.xml
index e441cca3ef..e24db825d7 100644
--- a/pom.xml
+++ b/pom.xml
@@ -326,6 +326,15 @@
+
+
+ com.cedarpolicy
+ cedar-java
+ 4.10.0
+ uber
+ test
+
+
io.quarkus
@@ -445,6 +454,23 @@
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+ 3.6.1
+
+
+ add-cedar-sidecar-test-source
+ generate-test-sources
+ add-test-source
+
+
+ sidecars/cedar/src/main/java
+
+
+
+
+
org.apache.maven.plugins
maven-enforcer-plugin
diff --git a/sidecars/cedar/Dockerfile b/sidecars/cedar/Dockerfile
new file mode 100644
index 0000000000..a04b7d0c84
--- /dev/null
+++ b/sidecars/cedar/Dockerfile
@@ -0,0 +1,16 @@
+FROM maven:3.9.11-eclipse-temurin-25 AS build
+WORKDIR /build
+COPY sidecars/cedar/pom.xml ./pom.xml
+RUN mvn -B -DskipTests dependency:go-offline
+COPY sidecars/cedar/src ./src
+RUN mvn -B -DskipTests package
+
+FROM eclipse-temurin:25-jre
+RUN groupadd --system --gid 10001 floci \
+ && useradd --system --uid 10001 --gid 10001 --home-dir /nonexistent --shell /usr/sbin/nologin floci
+WORKDIR /app
+COPY --chown=10001:10001 --from=build /build/target/floci-cedar-sidecar-1.0.0.jar /app/sidecar.jar
+COPY --chown=10001:10001 --from=build /build/target/dependency /app/lib
+USER 10001:10001
+EXPOSE 8180
+ENTRYPOINT ["java", "-cp", "/app/sidecar.jar:/app/lib/*", "io.github.hectorvent.floci.cedar.CedarSidecarServer"]
diff --git a/sidecars/cedar/pom.xml b/sidecars/cedar/pom.xml
new file mode 100644
index 0000000000..18c64c6626
--- /dev/null
+++ b/sidecars/cedar/pom.xml
@@ -0,0 +1,57 @@
+
+
+ 4.0.0
+ io.github.hectorvent.floci
+ floci-cedar-sidecar
+ 1.0.0
+
+
+ 25
+ UTF-8
+ 4.10.0
+ 2.22.1
+ 3.6.1.Final
+
+
+
+
+ com.cedarpolicy
+ cedar-java
+ ${cedar.version}
+ uber
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
+
+ org.jboss.logging
+ jboss-logging
+ ${jboss.logging.version}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+ 3.9.0
+
+
+ copy-runtime-dependencies
+ package
+ copy-dependencies
+
+ runtime
+ ${project.build.directory}/dependency
+
+
+
+
+
+
+
diff --git a/sidecars/cedar/src/main/java/io/github/hectorvent/floci/cedar/CedarSidecarServer.java b/sidecars/cedar/src/main/java/io/github/hectorvent/floci/cedar/CedarSidecarServer.java
new file mode 100644
index 0000000000..3a181a151b
--- /dev/null
+++ b/sidecars/cedar/src/main/java/io/github/hectorvent/floci/cedar/CedarSidecarServer.java
@@ -0,0 +1,493 @@
+package io.github.hectorvent.floci.cedar;
+
+import com.cedarpolicy.BasicAuthorizationEngine;
+import com.cedarpolicy.model.AuthorizationRequest;
+import com.cedarpolicy.model.AuthorizationSuccessResponse;
+import com.cedarpolicy.model.Context;
+import com.cedarpolicy.model.ValidationRequest;
+import com.cedarpolicy.model.entity.Entities;
+import com.cedarpolicy.model.entity.Entity;
+import com.cedarpolicy.model.policy.LinkValue;
+import com.cedarpolicy.model.policy.PolicySet;
+import com.cedarpolicy.model.policy.TemplateLink;
+import com.cedarpolicy.model.schema.Schema;
+import com.cedarpolicy.value.CedarList;
+import com.cedarpolicy.value.CedarMap;
+import com.cedarpolicy.value.DateTime;
+import com.cedarpolicy.value.Decimal;
+import com.cedarpolicy.value.Duration;
+import com.cedarpolicy.value.EntityTypeName;
+import com.cedarpolicy.value.EntityUID;
+import com.cedarpolicy.value.IpAddress;
+import com.cedarpolicy.value.PrimBool;
+import com.cedarpolicy.value.PrimLong;
+import com.cedarpolicy.value.PrimString;
+import com.cedarpolicy.value.Value;
+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 com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import org.jboss.logging.Logger;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Executors;
+
+/** Stateless HTTP boundary around Cedar Java 4.x for Floci Verified Permissions. */
+public final class CedarSidecarServer {
+ private static final Logger LOG = Logger.getLogger(CedarSidecarServer.class);
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final BasicAuthorizationEngine ENGINE = new BasicAuthorizationEngine();
+
+ private CedarSidecarServer() {
+ }
+
+ public static void main(String[] args) throws IOException {
+ int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "8180"));
+ start(port);
+ }
+
+ public static HttpServer start(int port) throws IOException {
+ HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", port), 0);
+ server.createContext("/health", exchange -> respondText(exchange, 200, "ok"));
+ server.createContext("/v1/entity-type/validate", exchange -> handleJson(exchange, CedarSidecarServer::validateEntityType));
+ server.createContext("/v1/schema/validate", exchange -> handleJson(exchange, CedarSidecarServer::validateSchema));
+ server.createContext("/v1/policy/parse", exchange -> handleJson(exchange, CedarSidecarServer::parsePolicy));
+ server.createContext("/v1/policy/validate", exchange -> handleJson(exchange, CedarSidecarServer::validatePolicy));
+ server.createContext("/v1/authorize", exchange -> handleJson(exchange, CedarSidecarServer::authorize));
+ server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
+ server.start();
+ LOG.infov("Floci Cedar sidecar listening on port {0}", port);
+ return server;
+ }
+
+ private static JsonNode validateEntityType(JsonNode body) throws Exception {
+ String value = requiredText(body, "entityType");
+ if (EntityTypeName.parse(value).isEmpty()) {
+ throw new IllegalArgumentException("Invalid Cedar entity type: " + value);
+ }
+ return MAPPER.createObjectNode().put("valid", true);
+ }
+
+ private static JsonNode validateSchema(JsonNode body) throws Exception {
+ String schema = requiredText(body, "schema");
+ Schema.parse(Schema.JsonOrCedar.Json, schema);
+ return MAPPER.createObjectNode().put("valid", true);
+ }
+
+ private static JsonNode parsePolicy(JsonNode body) throws Exception {
+ String statement = requiredText(body, "statement");
+ boolean template = body.path("template").asBoolean(false);
+ com.cedarpolicy.model.policy.Policy policy = template
+ ? com.cedarpolicy.model.policy.Policy.parsePolicyTemplate(statement)
+ : com.cedarpolicy.model.policy.Policy.parseStaticPolicy(statement);
+ JsonNode ast;
+ if (template) {
+ PolicySet set = new PolicySet(Set.of(), Set.of(policy));
+ JsonNode templates = MAPPER.readTree(set.toJson()).path("templates");
+ if (!templates.isObject() || templates.isEmpty()) {
+ throw new IllegalArgumentException("Cedar template AST is empty");
+ }
+ ast = templates.elements().next();
+ } else {
+ ast = MAPPER.readTree(policy.toJson());
+ }
+ ObjectNode response = MAPPER.createObjectNode();
+ response.put("effect", policy.effect().name().equalsIgnoreCase("PERMIT") ? "Permit" : "Forbid");
+ response.set("ast", ast);
+ return response;
+ }
+
+ private static JsonNode validatePolicy(JsonNode body) throws Exception {
+ Schema schema = Schema.parse(Schema.JsonOrCedar.Json, requiredText(body, "schema"));
+ String statement = requiredText(body, "statement");
+ boolean template = body.path("template").asBoolean(false);
+ com.cedarpolicy.model.policy.Policy policy = template
+ ? com.cedarpolicy.model.policy.Policy.parsePolicyTemplate(statement)
+ : com.cedarpolicy.model.policy.Policy.parseStaticPolicy(statement);
+ PolicySet set = template ? new PolicySet(Set.of(), Set.of(policy)) : new PolicySet(Set.of(policy));
+ var result = ENGINE.validate(new ValidationRequest(schema, set));
+ if (!result.validationPassed()) {
+ throw new IllegalArgumentException("The Cedar policy failed STRICT schema validation: " + result);
+ }
+ return MAPPER.createObjectNode().put("valid", true);
+ }
+
+ private static JsonNode authorize(JsonNode body) throws Exception {
+ JsonNode request = requiredObject(body, "request");
+ EntityUID principal = euid(request.get("principal"), "principal");
+ EntityUID action = actionEuid(request.get("action"));
+ EntityUID resource = euid(request.get("resource"), "resource");
+ Entities entities = entities(request.get("entities"));
+ Context context = context(request.get("context"));
+ PolicySet policies = policySet(body.path("policies"), body.path("templates"));
+
+ var authorizationResponse = ENGINE.isAuthorized(new AuthorizationRequest(principal, action, resource, context), policies, entities);
+ AuthorizationSuccessResponse response = authorizationResponse.success.orElseThrow(() ->
+ new IllegalArgumentException("Cedar authorization failed."));
+ ObjectNode out = MAPPER.createObjectNode();
+ out.put("decision", response.isAllowed() ? "ALLOW" : "DENY");
+ ArrayNode reasons = out.putArray("determiningPolicyIds");
+ response.getReason().stream().sorted().forEach(reasons::add);
+ ArrayNode errors = out.putArray("errors");
+ response.getErrors().stream().map(Object::toString).forEach(errors::add);
+ return out;
+ }
+
+ private static PolicySet policySet(JsonNode storedPolicies, JsonNode templates) {
+ Set staticPolicies = new LinkedHashSet<>();
+ Set cedarTemplates = new LinkedHashSet<>();
+ List links = new ArrayList<>();
+ if (templates.isObject()) {
+ templates.fields().forEachRemaining(entry -> {
+ JsonNode template = entry.getValue();
+ cedarTemplates.add(new com.cedarpolicy.model.policy.Policy(requiredText(template, "statement"), entry.getKey()));
+ });
+ }
+ if (storedPolicies.isArray()) {
+ for (JsonNode policy : storedPolicies) {
+ String policyType = requiredText(policy, "policyType");
+ String policyId = requiredText(policy, "policyId");
+ if ("STATIC".equals(policyType)) {
+ staticPolicies.add(new com.cedarpolicy.model.policy.Policy(requiredText(policy, "statement"), policyId));
+ continue;
+ }
+ List values = new ArrayList<>();
+ if (!policy.path("principal").isMissingNode() && !policy.path("principal").isNull()) {
+ values.add(new LinkValue("?principal", euid(policy.get("principal"), "principal")));
+ }
+ if (!policy.path("resource").isMissingNode() && !policy.path("resource").isNull()) {
+ values.add(new LinkValue("?resource", euid(policy.get("resource"), "resource")));
+ }
+ links.add(new TemplateLink(requiredText(policy, "policyTemplateId"), policyId, values));
+ }
+ }
+ return new PolicySet(staticPolicies, cedarTemplates, links);
+ }
+
+ private static Entities entities(JsonNode definition) throws Exception {
+ if (definition == null || definition.isNull()) {
+ return new Entities();
+ }
+ if (!definition.isObject() || definition.size() != 1) {
+ throw new IllegalArgumentException("entities must contain exactly one union member.");
+ }
+ JsonNode raw;
+ if (definition.has("cedarJson")) {
+ if (!definition.get("cedarJson").isTextual()) {
+ throw new IllegalArgumentException("entities.cedarJson must be a string.");
+ }
+ raw = MAPPER.readTree(definition.get("cedarJson").asText());
+ } else if (definition.has("entityList")) {
+ if (!definition.get("entityList").isArray()) {
+ throw new IllegalArgumentException("entities.entityList must be an array.");
+ }
+ raw = toCedarEntities((ArrayNode) definition.get("entityList"));
+ } else {
+ throw new IllegalArgumentException("entities must contain cedarJson or entityList.");
+ }
+ return entitiesFromCedarJson(raw);
+ }
+
+ private static Entities entitiesFromCedarJson(JsonNode raw) {
+ if (!raw.isArray()) {
+ throw new IllegalArgumentException("entities.cedarJson must encode an array.");
+ }
+ Set result = new LinkedHashSet<>();
+ for (JsonNode node : raw) {
+ if (!node.isObject()) {
+ throw new IllegalArgumentException("Each Cedar entity must be an object.");
+ }
+ result.add(new Entity(euid(node.get("uid"), "uid"), cedarValueMap(node.get("attrs"), "attrs"),
+ cedarParents(node.get("parents")), cedarValueMap(node.get("tags"), "tags")));
+ }
+ return new Entities(result);
+ }
+
+ private static ArrayNode toCedarEntities(ArrayNode input) {
+ ArrayNode output = MAPPER.createArrayNode();
+ Map lastByUid = new LinkedHashMap<>();
+ for (JsonNode entity : input) {
+ JsonNode identifier = requiredObject(entity, "identifier");
+ ObjectNode cedar = MAPPER.createObjectNode();
+ cedar.set("uid", cedarEntity(identifier));
+ ObjectNode attrs = cedar.putObject("attrs");
+ JsonNode attributes = entity.get("attributes");
+ if (attributes != null && !attributes.isNull()) {
+ 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()) {
+ parentInput.forEach(parent -> parents.add(cedarEntity(parent)));
+ }
+ ObjectNode tags = cedar.putObject("tags");
+ JsonNode tagInput = entity.get("tags");
+ if (tagInput != null && !tagInput.isNull()) {
+ tagInput.fields().forEachRemaining(entry -> tags.set(entry.getKey(), cedarAttribute(entry.getValue())));
+ }
+ lastByUid.put(requiredText(identifier, "entityType") + "\u0000" + requiredText(identifier, "entityId"), cedar);
+ }
+ lastByUid.values().forEach(output::add);
+ return output;
+ }
+
+ private static Map cedarValueMap(JsonNode node, String field) {
+ if (node == null || node.isNull()) {
+ return Map.of();
+ }
+ if (!node.isObject()) {
+ throw new IllegalArgumentException("Entity " + field + " must be an object.");
+ }
+ Map values = new LinkedHashMap<>();
+ node.fields().forEachRemaining(entry -> values.put(entry.getKey(), valueFromCedarJson(entry.getValue())));
+ return values;
+ }
+
+ private static Set cedarParents(JsonNode node) {
+ if (node == null || node.isNull()) {
+ return Set.of();
+ }
+ if (!node.isArray()) {
+ throw new IllegalArgumentException("Entity parents must be an array.");
+ }
+ Set parents = new LinkedHashSet<>();
+ node.forEach(parent -> parents.add(euid(parent, "parent")));
+ return parents;
+ }
+
+ private static JsonNode cedarAttribute(JsonNode union) {
+ if (union == null || !union.isObject() || union.size() != 1) {
+ throw new IllegalArgumentException("Attribute values must contain exactly one union member.");
+ }
+ Map.Entry member = union.fields().next();
+ return switch (member.getKey()) {
+ case "boolean" -> MAPPER.getNodeFactory().booleanNode(member.getValue().asBoolean());
+ case "long" -> MAPPER.getNodeFactory().numberNode(member.getValue().asLong());
+ case "string" -> MAPPER.getNodeFactory().textNode(member.getValue().asText());
+ case "entityIdentifier" -> explicitEntity(member.getValue());
+ 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" -> {
+ ArrayNode set = MAPPER.createArrayNode();
+ member.getValue().forEach(value -> set.add(cedarAttribute(value)));
+ yield set;
+ }
+ case "record" -> {
+ ObjectNode record = MAPPER.createObjectNode();
+ member.getValue().fields().forEachRemaining(entry -> record.set(entry.getKey(), cedarAttribute(entry.getValue())));
+ yield record;
+ }
+ default -> throw new IllegalArgumentException("Unsupported attribute union member: " + member.getKey());
+ };
+ }
+
+ private static Context context(JsonNode definition) throws Exception {
+ if (definition == null || definition.isNull()) {
+ return new Context();
+ }
+ if (!definition.isObject() || definition.size() != 1) {
+ throw new IllegalArgumentException("context must contain exactly one union member.");
+ }
+ if (definition.has("cedarJson")) {
+ JsonNode raw = MAPPER.readTree(requiredText(definition, "cedarJson"));
+ if (!raw.isObject()) {
+ throw new IllegalArgumentException("context.cedarJson must encode an object.");
+ }
+ return new Context(valueMapFromCedarJson(raw));
+ }
+ if (definition.has("contextMap")) {
+ JsonNode raw = definition.get("contextMap");
+ Map values = new LinkedHashMap<>();
+ raw.fields().forEachRemaining(entry -> values.put(entry.getKey(), valueFromUnion(entry.getValue())));
+ return new Context(values);
+ }
+ throw new IllegalArgumentException("context must contain cedarJson or contextMap.");
+ }
+
+ private static Map valueMapFromCedarJson(JsonNode object) {
+ Map result = new LinkedHashMap<>();
+ object.fields().forEachRemaining(entry -> result.put(entry.getKey(), valueFromCedarJson(entry.getValue())));
+ return result;
+ }
+
+ private static Value valueFromCedarJson(JsonNode value) {
+ if (value.isBoolean()) {
+ return new PrimBool(value.asBoolean());
+ }
+ if (value.isIntegralNumber()) {
+ return new PrimLong(value.asLong());
+ }
+ if (value.isTextual()) {
+ return new PrimString(value.asText());
+ }
+ if (value.isArray()) {
+ List values = new ArrayList<>();
+ value.forEach(item -> values.add(valueFromCedarJson(item)));
+ return new CedarList(values);
+ }
+ if (value.isObject()) {
+ if (value.has("__entity")) {
+ return euid(value.get("__entity"), "__entity");
+ }
+ if (value.has("__extn")) {
+ JsonNode ext = value.get("__extn");
+ return extensionValue(ext.path("fn").asText(), ext.path("arg").asText());
+ }
+ return new CedarMap(valueMapFromCedarJson(value));
+ }
+ throw new IllegalArgumentException("Unsupported Cedar JSON value.");
+ }
+
+ private static Value valueFromUnion(JsonNode union) {
+ if (union == null || !union.isObject() || union.size() != 1) {
+ throw new IllegalArgumentException("Context attribute values must contain exactly one union member.");
+ }
+ Map.Entry member = union.fields().next();
+ return switch (member.getKey()) {
+ case "boolean" -> new PrimBool(member.getValue().asBoolean());
+ case "long" -> new PrimLong(member.getValue().asLong());
+ case "string" -> new PrimString(member.getValue().asText());
+ case "entityIdentifier" -> euid(member.getValue(), "entityIdentifier");
+ case "ipaddr" -> new IpAddress(member.getValue().asText());
+ case "decimal" -> new Decimal(member.getValue().asText());
+ case "datetime" -> new DateTime(member.getValue().asText());
+ case "duration" -> new Duration(member.getValue().asText());
+ case "set" -> {
+ List list = new ArrayList<>();
+ member.getValue().forEach(item -> list.add(valueFromUnion(item)));
+ yield new CedarList(list);
+ }
+ case "record" -> {
+ Map map = new LinkedHashMap<>();
+ member.getValue().fields().forEachRemaining(entry -> map.put(entry.getKey(), valueFromUnion(entry.getValue())));
+ yield new CedarMap(map);
+ }
+ default -> throw new IllegalArgumentException("Unsupported attribute union member: " + member.getKey());
+ };
+ }
+
+ private static Value extensionValue(String function, String arg) {
+ return switch (function) {
+ case "ip" -> new IpAddress(arg);
+ case "decimal" -> new Decimal(arg);
+ case "datetime" -> new DateTime(arg);
+ case "duration" -> new Duration(arg);
+ default -> throw new IllegalArgumentException("Unsupported Cedar extension: " + function);
+ };
+ }
+
+ private static EntityUID actionEuid(JsonNode node) {
+ if (node == null || !node.isObject()) {
+ throw new IllegalArgumentException("action is required.");
+ }
+ return euid(requiredText(node, "actionType"), requiredText(node, "actionId"));
+ }
+
+ private static EntityUID euid(JsonNode node, String field) {
+ if (node == null || !node.isObject()) {
+ throw new IllegalArgumentException(field + " is required.");
+ }
+ String type = node.has("entityType") ? requiredText(node, "entityType") : requiredText(node, "type");
+ String id = node.has("entityId") ? requiredText(node, "entityId") : requiredText(node, "id");
+ return euid(type, id);
+ }
+
+ private static EntityUID euid(String type, String id) {
+ EntityTypeName entityType = EntityTypeName.parse(type)
+ .orElseThrow(() -> new IllegalArgumentException("Invalid Cedar entity type: " + type));
+ return entityType.of(id);
+ }
+
+ private static ObjectNode cedarEntity(JsonNode identifier) {
+ ObjectNode node = MAPPER.createObjectNode();
+ node.put("type", identifier.has("entityType") ? requiredText(identifier, "entityType") : requiredText(identifier, "type"));
+ node.put("id", identifier.has("entityId") ? requiredText(identifier, "entityId") : requiredText(identifier, "id"));
+ return node;
+ }
+
+ private static ObjectNode explicitEntity(JsonNode identifier) {
+ ObjectNode out = MAPPER.createObjectNode();
+ out.set("__entity", cedarEntity(identifier));
+ return out;
+ }
+
+ private static ObjectNode extension(String fn, String arg) {
+ ObjectNode root = MAPPER.createObjectNode();
+ ObjectNode ext = root.putObject("__extn");
+ ext.put("fn", fn);
+ ext.put("arg", arg);
+ return root;
+ }
+
+ private static String requiredText(JsonNode node, String field) {
+ JsonNode value = node == null ? null : node.get(field);
+ if (value == null || !value.isTextual() || value.asText().isEmpty()) {
+ throw new IllegalArgumentException(field + " is required.");
+ }
+ return value.asText();
+ }
+
+ private static JsonNode requiredObject(JsonNode node, String field) {
+ JsonNode value = node == null ? null : node.get(field);
+ if (value == null || !value.isObject()) {
+ throw new IllegalArgumentException(field + " is required.");
+ }
+ return value;
+ }
+
+ private static void handleJson(HttpExchange exchange, JsonHandler handler) throws IOException {
+ if (!"POST".equals(exchange.getRequestMethod())) {
+ respondJson(exchange, 405, error("Method not allowed"));
+ return;
+ }
+ try {
+ JsonNode body = MAPPER.readTree(exchange.getRequestBody());
+ respondJson(exchange, 200, handler.handle(body));
+ } catch (IllegalArgumentException | com.cedarpolicy.model.exception.AuthException e) {
+ respondJson(exchange, 400, error(safeMessage(e)));
+ } catch (Exception e) {
+ respondJson(exchange, 500, error(safeMessage(e)));
+ }
+ }
+
+ private static ObjectNode error(String message) {
+ return MAPPER.createObjectNode().put("error", message);
+ }
+
+ private static void respondJson(HttpExchange exchange, int status, JsonNode body) throws IOException {
+ byte[] bytes = MAPPER.writeValueAsBytes(body);
+ exchange.getResponseHeaders().set("Content-Type", "application/json");
+ exchange.sendResponseHeaders(status, bytes.length);
+ exchange.getResponseBody().write(bytes);
+ exchange.close();
+ }
+
+ private static void respondText(HttpExchange exchange, int status, String body) throws IOException {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ exchange.sendResponseHeaders(status, bytes.length);
+ exchange.getResponseBody().write(bytes);
+ exchange.close();
+ }
+
+ private static String safeMessage(Exception e) {
+ String message = e.getMessage();
+ return message == null || message.isBlank() ? e.getClass().getSimpleName() : message;
+ }
+
+ @FunctionalInterface
+ private interface JsonHandler {
+ JsonNode handle(JsonNode body) throws Exception;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 3a0201017c..8e16db4c42 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -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 cedarUrl();
+
+ @WithDefault("floci/floci:latest-cedar")
+ String cedarImage();
+ }
+
interface RamServiceConfig {
@WithDefault("true")
boolean enabled();
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
index afa7aa2eb2..5c48f6ca7a 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonController.java
@@ -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
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
index 08b0e3da5b..02758f0bc6 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java
@@ -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),
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarAuthorizationEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarAuthorizationEvaluator.java
new file mode 100644
index 0000000000..2537818604
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarAuthorizationEvaluator.java
@@ -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 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 storedPolicies,
+ Map 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 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 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 determiningPolicyIds, List errors) {}
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarClient.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarClient.java
new file mode 100644
index 0000000000..1d7801f298
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarClient.java
@@ -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 policies,
+ Map 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 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 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 determiningPolicyIds, List errors) {}
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarManager.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarManager.java
new file mode 100644
index 0000000000..3d25cad6c8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarManager.java
@@ -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 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 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;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsJsonHandler.java
new file mode 100644
index 0000000000..87238bfc78
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsJsonHandler.java
@@ -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 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 schemaNamespaces(String schema) {
+ if (schema == null) {
+ return List.of();
+ }
+ try {
+ JsonNode parsed = objectMapper.readTree(schema);
+ if (!parsed.isObject()) {
+ return List.of();
+ }
+ java.util.ArrayList 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 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() : "";
+ String nextResource = item.has("resource") ? item.get("resource").toString() : "";
+ 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 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 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 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 values) {
+ ObjectNode out = objectMapper.createObjectNode();
+ ObjectNode tags = out.putObject("tags");
+ values.forEach(tags::put);
+ return out;
+ }
+
+ private Map stringMap(JsonNode node) {
+ if (!node.isObject()) {
+ throw VerifiedPermissionsService.validation("tags is required.");
+ }
+ Map 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 stringList(JsonNode node) {
+ if (!node.isArray()) {
+ throw VerifiedPermissionsService.validation("tagKeys is required.");
+ }
+ java.util.ArrayList 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;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifier.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifier.java
new file mode 100644
index 0000000000..7c1fb02052
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifier.java
@@ -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 jwksCache = new ConcurrentHashMap<>();
+ private final Map unknownKidRefreshes = new ConcurrentHashMap<>();
+ private final Map 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 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 refreshed = fetchJwks(issuer);
+ unknownKidRefreshes.put(issuer, now);
+ jwksCache.put(issuer, new CachedJwks(refreshed, now));
+ return refreshed.get(kid);
+ }
+ }
+
+ Map 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 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 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);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsService.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsService.java
new file mode 100644
index 0000000000..264deadfdc
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsService.java
@@ -0,0 +1,1164 @@
+package io.github.hectorvent.floci.services.verifiedpermissions;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.PaginatedResult;
+import io.github.hectorvent.floci.core.common.Pagination;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.common.Resettable;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageFactory;
+import io.github.hectorvent.floci.services.kms.KmsService;
+import io.github.hectorvent.floci.services.verifiedpermissions.model.EntityIdentifier;
+import io.github.hectorvent.floci.services.verifiedpermissions.model.IdempotencyRecord;
+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 java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+
+@ApplicationScoped
+public class VerifiedPermissionsService implements Resettable {
+ static final Duration ALIAS_SOFT_DELETE_RETENTION = Duration.ofHours(24);
+ private static final Pattern STORE_ID = Pattern.compile("[A-Za-z0-9-/_]{1,200}");
+ private static final Pattern ALIAS_NAME = Pattern.compile("policy-store-alias/[A-Za-z0-9-/_]*");
+ private static final int MAX_TAGS = 200;
+ private static final int MAX_ALIASES_PER_POLICY_STORE = 10;
+ private static final int MAX_POLICY_STATEMENT_LENGTH = 10_000;
+
+ private final StorageBackend policyStores;
+ private final StorageBackend aliases;
+ private final StorageBackend policies;
+ private final StorageBackend policyTemplates;
+ private final StorageBackend idempotency;
+ private final StorageBackend identitySources;
+ private final RegionResolver regionResolver;
+ private final KmsService kmsService;
+ private final ObjectMapper objectMapper;
+ private final CedarSidecarClient cedarClient;
+
+ @Inject
+ public VerifiedPermissionsService(StorageFactory storageFactory, RegionResolver regionResolver,
+ ObjectMapper objectMapper, KmsService kmsService,
+ CedarSidecarClient cedarClient) {
+ this(storageFactory.create("verifiedpermissions", "verifiedpermissions-policy-stores.json",
+ new TypeReference