Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Franklin G. Mendoza2d512591208d
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 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>ssooidc</artifactId>
</dependency>
+ <!-- Amazon Verified Permissions client -->
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>verifiedpermissions</artifactId>
+ </dependency>
<!-- AppSync client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
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
+
+<!-- floci:actions:start -->
+| 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 |
+<!-- floci:actions:end -->
+
+## 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 `<user-pool-id>|<subject>`
+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 @@
</exclusions>
</dependency>
+ <!-- Cedar is test-only in the Floci process. Production evaluation runs in the sidecar. -->
+ <dependency>
+ <groupId>com.cedarpolicy</groupId>
+ <artifactId>cedar-java</artifactId>
+ <version>4.10.0</version>
+ <classifier>uber</classifier>
+ <scope>test</scope>
+ </dependency>
+
<!-- Testing -->
<dependency>
<groupId>io.quarkus</groupId>
@@ -445,6 +454,23 @@
</systemPropertyVariables>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>3.6.1</version>
+ <executions>
+ <execution>
+ <id>add-cedar-sidecar-test-source</id>
+ <phase>generate-test-sources</phase>
+ <goals><goal>add-test-source</goal></goals>
+ <configuration>
+ <sources>
+ <source>sidecars/cedar/src/main/java</source>
+ </sources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
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 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>io.github.hectorvent.floci</groupId>
+ <artifactId>floci-cedar-sidecar</artifactId>
+ <version>1.0.0</version>
+
+ <properties>
+ <maven.compiler.release>25</maven.compiler.release>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <cedar.version>4.10.0</cedar.version>
+ <jackson.version>2.22.1</jackson.version>
+ <jboss.logging.version>3.6.1.Final</jboss.logging.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.cedarpolicy</groupId>
+ <artifactId>cedar-java</artifactId>
+ <version>${cedar.version}</version>
+ <classifier>uber</classifier>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>${jackson.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.logging</groupId>
+ <artifactId>jboss-logging</artifactId>
+ <version>${jboss.logging.version}</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <version>3.9.0</version>
+ <executions>
+ <execution>
+ <id>copy-runtime-dependencies</id>
+ <phase>package</phase>
+ <goals><goal>copy-dependencies</goal></goals>
+ <configuration>
+ <includeScope>runtime</includeScope>
+ <outputDirectory>${project.build.directory}/dependency</outputDirectory>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
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<com.cedarpolicy.model.policy.Policy> staticPolicies = new LinkedHashSet<>();
+ Set<com.cedarpolicy.model.policy.Policy> cedarTemplates = new LinkedHashSet<>();
+ List<TemplateLink> 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<LinkValue> 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<Entity> 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<String, ObjectNode> 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<String, Value> 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<String, Value> values = new LinkedHashMap<>();
+ node.fields().forEachRemaining(entry -> values.put(entry.getKey(), valueFromCedarJson(entry.getValue())));
+ return values;
+ }
+
+ private static Set<EntityUID> cedarParents(JsonNode node) {
+ if (node == null || node.isNull()) {
+ return Set.of();
+ }
+ if (!node.isArray()) {
+ throw new IllegalArgumentException("Entity parents must be an array.");
+ }
+ Set<EntityUID> 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<String, JsonNode> 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<String, Value> 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<String, Value> valueMapFromCedarJson(JsonNode object) {
+ Map<String, Value> 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<Value> 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<String, JsonNode> 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<Value> list = new ArrayList<>();
+ member.getValue().forEach(item -> list.add(valueFromUnion(item)));
+ yield new CedarList(list);
+ }
+ case "record" -> {
+ Map<String, Value> 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<String> 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<EntityIdentifier> parents) {
+ ArrayNode cedarEntities;
+ try {
+ if (entitiesDefinition == null || entitiesDefinition.isNull()) {
+ cedarEntities = objectMapper.createArrayNode();
+ } else if (entitiesDefinition.has("cedarJson")) {
+ JsonNode parsed = objectMapper.readTree(entitiesDefinition.path("cedarJson").asText());
+ if (!parsed.isArray()) {
+ throw VerifiedPermissionsService.validation("entities.cedarJson must encode an array.");
+ }
+ cedarEntities = (ArrayNode) parsed.deepCopy();
+ } else if (entitiesDefinition.has("entityList") && entitiesDefinition.get("entityList").isArray()) {
+ cedarEntities = toCedarEntities((ArrayNode) entitiesDefinition.get("entityList"));
+ } else {
+ throw VerifiedPermissionsService.validation("entities must contain cedarJson or entityList.");
+ }
+ ObjectNode entity = objectMapper.createObjectNode();
+ entity.set("uid", cedarEntity(principal));
+ ObjectNode attrs = entity.putObject("attrs");
+ if (identityClaims != null && identityClaims.isObject()) {
+ identityClaims.fields().forEachRemaining(entry -> {
+ if (!isGroupClaim(entry.getKey()) && claimCanBeCedar(entry.getValue())) {
+ attrs.set(entry.getKey(), entry.getValue().deepCopy());
+ }
+ });
+ }
+ ArrayNode parentArray = entity.putArray("parents");
+ parents.forEach(parent -> parentArray.add(cedarEntity(parent)));
+ cedarEntities.add(entity);
+ ObjectNode union = objectMapper.createObjectNode();
+ union.put("cedarJson", cedarEntities.toString());
+ return union;
+ } catch (JsonProcessingException e) {
+ throw VerifiedPermissionsService.validation("entities.cedarJson is invalid JSON.");
+ }
+ }
+
+ public EvaluationResult evaluate(JsonNode request, List<Policy> storedPolicies,
+ Map<String, PolicyTemplate> templates) {
+ CedarSidecarClient.EvaluationResult result = cedarClient.authorize(request, storedPolicies, templates);
+ return new EvaluationResult(result.decision(), result.determiningPolicyIds(), result.errors());
+ }
+
+ private static boolean isGroupClaim(String name) {
+ return "cognito:groups".equals(name) || "groups".equals(name);
+ }
+
+ private static boolean claimCanBeCedar(JsonNode value) {
+ if (value == null || value.isNull()) {
+ return false;
+ }
+ if (value.isTextual() || value.isBoolean() || value.isIntegralNumber()) {
+ return true;
+ }
+ if (value.isArray()) {
+ for (JsonNode item : value) {
+ if (!claimCanBeCedar(item) || item.isContainerNode()) {
+ return false;
+ }
+ }
+ return true;
+ }
+ if (value.isObject()) {
+ var iterator = value.elements();
+ while (iterator.hasNext()) {
+ if (!claimCanBeCedar(iterator.next())) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private ArrayNode toCedarEntities(ArrayNode input) {
+ ArrayNode output = objectMapper.createArrayNode();
+ Map<String, ObjectNode> lastByUid = new LinkedHashMap<>();
+ for (JsonNode entity : input) {
+ if (!entity.isObject()) {
+ throw VerifiedPermissionsService.validation("Each entityList item must be an object.");
+ }
+ EntityIdentifier id = identifier(entity.get("identifier"), "identifier");
+ ObjectNode cedar = objectMapper.createObjectNode();
+ cedar.set("uid", cedarEntity(id));
+ ObjectNode attrs = cedar.putObject("attrs");
+ JsonNode attributes = entity.get("attributes");
+ if (attributes != null && !attributes.isNull()) {
+ if (!attributes.isObject()) {
+ throw VerifiedPermissionsService.validation("entity attributes must be an object.");
+ }
+ attributes.fields().forEachRemaining(entry -> attrs.set(entry.getKey(), cedarAttribute(entry.getValue())));
+ }
+ ArrayNode parents = cedar.putArray("parents");
+ JsonNode parentInput = entity.get("parents");
+ if (parentInput != null && !parentInput.isNull()) {
+ if (!parentInput.isArray()) {
+ throw VerifiedPermissionsService.validation("entity parents must be an array.");
+ }
+ parentInput.forEach(parent -> parents.add(cedarEntity(identifier(parent, "parent"))));
+ }
+ ObjectNode tags = cedar.putObject("tags");
+ JsonNode tagInput = entity.get("tags");
+ if (tagInput != null && !tagInput.isNull()) {
+ if (!tagInput.isObject()) {
+ throw VerifiedPermissionsService.validation("entity tags must be an object.");
+ }
+ tagInput.fields().forEachRemaining(entry -> tags.set(entry.getKey(), cedarAttribute(entry.getValue())));
+ }
+ lastByUid.put(id.entityType() + "\u0000" + id.entityId(), cedar);
+ }
+ lastByUid.values().forEach(output::add);
+ return output;
+ }
+
+ private JsonNode cedarAttribute(JsonNode union) {
+ if (union == null || !union.isObject() || union.size() != 1) {
+ throw VerifiedPermissionsService.validation("Attribute values must contain exactly one union member.");
+ }
+ Map.Entry<String, JsonNode> member = union.fields().next();
+ return switch (member.getKey()) {
+ case "boolean" -> objectMapper.getNodeFactory().booleanNode(member.getValue().asBoolean());
+ case "long" -> objectMapper.getNodeFactory().numberNode(member.getValue().asLong());
+ case "string" -> objectMapper.getNodeFactory().textNode(member.getValue().asText());
+ case "entityIdentifier" -> explicitEntity(identifier(member.getValue(), "entityIdentifier"));
+ case "ipaddr" -> extension("ip", member.getValue().asText());
+ case "decimal" -> extension("decimal", member.getValue().asText());
+ case "datetime" -> extension("datetime", member.getValue().asText());
+ case "duration" -> extension("duration", member.getValue().asText());
+ case "set" -> {
+ if (!member.getValue().isArray()) {
+ throw VerifiedPermissionsService.validation("set must be an array.");
+ }
+ ArrayNode set = objectMapper.createArrayNode();
+ member.getValue().forEach(value -> set.add(cedarAttribute(value)));
+ yield set;
+ }
+ case "record" -> {
+ if (!member.getValue().isObject()) {
+ throw VerifiedPermissionsService.validation("record must be an object.");
+ }
+ ObjectNode record = objectMapper.createObjectNode();
+ member.getValue().fields().forEachRemaining(entry -> record.set(entry.getKey(), cedarAttribute(entry.getValue())));
+ yield record;
+ }
+ default -> throw VerifiedPermissionsService.validation("Unsupported attribute union member: " + member.getKey());
+ };
+ }
+
+ private ObjectNode explicitEntity(EntityIdentifier id) {
+ ObjectNode out = objectMapper.createObjectNode();
+ out.set("__entity", cedarEntity(id));
+ return out;
+ }
+
+ private ObjectNode cedarEntity(EntityIdentifier id) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("type", id.entityType());
+ node.put("id", id.entityId());
+ return node;
+ }
+
+ private ObjectNode extension(String fn, String arg) {
+ ObjectNode root = objectMapper.createObjectNode();
+ ObjectNode ext = root.putObject("__extn");
+ ext.put("fn", fn);
+ ext.put("arg", arg);
+ return root;
+ }
+
+ private static EntityIdentifier identifier(JsonNode node, String field) {
+ if (node == null || !node.isObject()) {
+ throw VerifiedPermissionsService.validation(field + " is required.");
+ }
+ String type = VerifiedPermissionsService.requiredText(node, node.has("entityType") ? "entityType" : "type");
+ String id = VerifiedPermissionsService.requiredText(node, node.has("entityId") ? "entityId" : "id");
+ return new EntityIdentifier(type, id);
+ }
+
+ public record EvaluationResult(String decision, List<String> determiningPolicyIds, List<String> errors) {}
+}
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<Policy> policies,
+ Map<String, PolicyTemplate> templates) {
+ ObjectNode body = mapper.createObjectNode();
+ body.set("request", request.deepCopy());
+ ArrayNode policyArray = body.putArray("policies");
+ policies.forEach(policy -> policyArray.add(mapper.valueToTree(policy)));
+ ObjectNode templateObject = body.putObject("templates");
+ templates.forEach((id, template) -> templateObject.set(id, mapper.valueToTree(template)));
+ JsonNode response = post("/v1/authorize", body, "authorization");
+ return new EvaluationResult(
+ response.path("decision").asText(),
+ stringList(response.path("determiningPolicyIds")),
+ stringList(response.path("errors")));
+ }
+
+ private List<String> stringList(JsonNode node) {
+ if (!node.isArray()) {
+ return List.of();
+ }
+ return java.util.stream.StreamSupport.stream(node.spliterator(), false)
+ .map(JsonNode::asText)
+ .toList();
+ }
+
+ private JsonNode post(String path, JsonNode body, String operation) {
+ try {
+ String baseUrl = manager.ensureReady();
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create(baseUrl + path))
+ .timeout(Duration.ofSeconds(30))
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(body)))
+ .build();
+ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+ JsonNode responseBody = response.body() == null || response.body().isBlank()
+ ? mapper.createObjectNode() : mapper.readTree(response.body());
+ if (response.statusCode() == 400) {
+ throw VerifiedPermissionsService.validation(responseBody.path("error").asText("Cedar " + operation + " failed."));
+ }
+ if (response.statusCode() != 200) {
+ throw new AwsException("InternalServerException",
+ "Cedar sidecar " + operation + " failed with HTTP " + response.statusCode() + ".", 500);
+ }
+ return responseBody;
+ } catch (AwsException e) {
+ throw e;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new AwsException("InternalServerException", "Cedar sidecar " + operation + " was interrupted.", 500);
+ } catch (Exception e) {
+ throw new AwsException("InternalServerException",
+ "Failed to call Cedar sidecar for " + operation + ": " + safeMessage(e), 500);
+ }
+ }
+
+ private static String safeMessage(Exception e) {
+ String message = e.getMessage();
+ return message == null || message.isBlank() ? e.getClass().getSimpleName() : message;
+ }
+
+ public record ParsedPolicy(String effect, JsonNode ast) {}
+ public record EvaluationResult(String decision, List<String> determiningPolicyIds, List<String> errors) {}
+}
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<String> configured = config.services().verifiedpermissions().cedarUrl();
+ if (configured.isPresent() && !configured.get().isBlank()) {
+ String url = trimTrailingSlash(configured.get());
+ if (probeHealth(url)) {
+ resolvedUrl = url;
+ LOG.infov("Cedar sidecar is available at pre-configured URL: {0}", url);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public synchronized String ensureReady() {
+ if (resolvedUrl != null) {
+ if (containerId == null || probeHealth(resolvedUrl)) {
+ return resolvedUrl;
+ }
+ discardStaleManagedEndpoint();
+ }
+ Optional<String> configured = config.services().verifiedpermissions().cedarUrl();
+ if (configured.isPresent() && !configured.get().isBlank()) {
+ resolvedUrl = trimTrailingSlash(configured.get());
+ LOG.infov("Using pre-configured Cedar sidecar URL: {0}", resolvedUrl);
+ return resolvedUrl;
+ }
+ startContainer();
+ return resolvedUrl;
+ }
+
+ private void discardStaleManagedEndpoint() {
+ String staleUrl = resolvedUrl;
+ String staleContainerId = containerId;
+ resolvedUrl = null;
+ containerId = null;
+ LOG.warnv("Cedar sidecar at {0} is no longer healthy; restarting the managed container", staleUrl);
+ if (staleContainerId != null) {
+ try {
+ lifecycleManager.stopAndRemove(staleContainerId, null);
+ } catch (Exception e) {
+ LOG.debugv(e, "Failed to remove stale Cedar sidecar container {0}", staleContainerId);
+ }
+ }
+ }
+
+ private void startContainer() {
+ String image = config.services().verifiedpermissions().cedarImage();
+ LOG.infov("Starting Cedar sidecar container using image {0}", image);
+ String containerName = ContainerStorageHelper.dockerName(config, CONTAINER_NAME);
+ lifecycleManager.removeIfExists(containerName);
+
+ ContainerSpec spec = containerBuilder.newContainer(image)
+ .withName(containerName)
+ .withDynamicPort(CEDAR_PORT)
+ .withDockerNetwork(config.services().dockerNetwork())
+ .withEmbeddedDns()
+ .withLogRotation()
+ .build();
+ ContainerInfo info = lifecycleManager.createAndStart(spec);
+ EndpointInfo endpoint = info.getEndpoint(CEDAR_PORT);
+ containerId = info.containerId();
+ String url = "http://" + endpoint;
+ waitForHealth(url);
+ resolvedUrl = url;
+ LOG.infov("Cedar sidecar is ready at {0}", resolvedUrl);
+ }
+
+ private boolean probeHealth(String baseUrl) {
+ try {
+ HttpURLConnection connection = (HttpURLConnection) URI.create(baseUrl + "/health").toURL().openConnection();
+ connection.setConnectTimeout(500);
+ connection.setReadTimeout(500);
+ return connection.getResponseCode() == 200;
+ } catch (Exception e) {
+ LOG.debugv(e, "Cedar sidecar health probe failed for {0}", baseUrl);
+ return false;
+ }
+ }
+
+ private void waitForHealth(String baseUrl) {
+ long deadline = System.currentTimeMillis() + HEALTH_POLL_MAX_MS;
+ while (System.currentTimeMillis() < deadline) {
+ if (probeHealth(baseUrl)) {
+ return;
+ }
+ try {
+ Thread.sleep(HEALTH_POLL_INTERVAL_MS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new IllegalStateException("Interrupted while waiting for Cedar sidecar", e);
+ }
+ }
+ throw new IllegalStateException("Cedar sidecar did not become healthy within " + HEALTH_POLL_MAX_MS + " ms");
+ }
+
+ void onStop(@Observes ShutdownEvent event) {
+ if (containerId == null) {
+ return;
+ }
+ LOG.info("Stopping Cedar sidecar container");
+ lifecycleManager.stopAndRemove(containerId, null);
+ }
+
+ private static String trimTrailingSlash(String url) {
+ return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
+ }
+}
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<PolicyStore> result) {
+ ObjectNode out = objectMapper.createObjectNode();
+ ArrayNode list = out.putArray("policyStores");
+ for (PolicyStore store : result.items()) {
+ ObjectNode item = list.addObject();
+ item.put("arn", store.arn());
+ time(item, "createdDate", store.createdDate());
+ time(item, "lastUpdatedDate", store.lastUpdatedDate());
+ item.put("policyStoreId", store.policyStoreId());
+ if (store.description() != null) {
+ item.put("description", store.description());
+ }
+ }
+ if (result.nextToken() != null) {
+ out.put("nextToken", result.nextToken());
+ }
+ return out;
+ }
+
+ private ObjectNode schemaPut(PolicyStore store) {
+ ObjectNode out = objectMapper.createObjectNode();
+ time(out, "createdDate", store.schemaCreatedDate());
+ time(out, "lastUpdatedDate", store.schemaLastUpdatedDate());
+ out.put("policyStoreId", store.policyStoreId());
+ ArrayNode namespaces = out.putArray("namespaces");
+ schemaNamespaces(store.schema()).forEach(namespaces::add);
+ return out;
+ }
+
+ private ObjectNode schemaGet(PolicyStore store) {
+ ObjectNode out = schemaPut(store);
+ out.put("schema", store.schema());
+ return out;
+ }
+
+ private List<String> schemaNamespaces(String schema) {
+ if (schema == null) {
+ return List.of();
+ }
+ try {
+ JsonNode parsed = objectMapper.readTree(schema);
+ if (!parsed.isObject()) {
+ return List.of();
+ }
+ java.util.ArrayList<String> names = new java.util.ArrayList<>();
+ parsed.fieldNames().forEachRemaining(names::add);
+ names.sort(String::compareTo);
+ return names;
+ } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
+ throw new IllegalStateException("Stored Verified Permissions schema is not valid JSON", e);
+ }
+ }
+
+
+
+ private ObjectNode identitySourceWrite(IdentitySource source) {
+ ObjectNode out = objectMapper.createObjectNode();
+ time(out, "createdDate", source.createdDate());
+ out.put("identitySourceId", source.identitySourceId());
+ time(out, "lastUpdatedDate", source.lastUpdatedDate());
+ out.put("policyStoreId", source.policyStoreId());
+ return out;
+ }
+
+ private ObjectNode identitySourceDetail(IdentitySource source) {
+ ObjectNode out = identitySourceWrite(source);
+ out.put("principalEntityType", source.principalEntityType());
+ out.set("configuration", source.configuration().deepCopy());
+ if (source.configuration().has("cognitoUserPoolConfiguration")) {
+ JsonNode cognito = source.configuration().get("cognitoUserPoolConfiguration");
+ ObjectNode details = out.putObject("details");
+ ArrayNode clients = details.putArray("clientIds");
+ if (cognito.path("clientIds").isArray()) {
+ cognito.path("clientIds").forEach(clients::add);
+ }
+ details.put("discoveryUrl", cognito.path("issuer").asText() + "/.well-known/openid-configuration");
+ details.put("openIdIssuer", "COGNITO");
+ details.put("userPoolArn", cognito.path("userPoolArn").asText());
+ }
+ return out;
+ }
+
+ private ObjectNode identitySourceList(PaginatedResult<IdentitySource> result) {
+ ObjectNode out = objectMapper.createObjectNode();
+ ArrayNode list = out.putArray("identitySources");
+ for (IdentitySource source : result.items()) {
+ list.add(identitySourceDetail(source));
+ }
+ if (result.nextToken() != null) {
+ out.put("nextToken", result.nextToken());
+ }
+ return out;
+ }
+
+ private ObjectNode isAuthorizedWithToken(JsonNode request, String region) {
+ VerifiedPermissionsTokenService.PreparedTokenRequest prepared = tokenService.prepare(request, region);
+ ObjectNode out = isAuthorized(prepared.request(), region);
+ addEntity(out, "principal", prepared.principal());
+ return out;
+ }
+
+ private ObjectNode batchIsAuthorizedWithToken(JsonNode request, String region) {
+ String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
+ service.getPolicyStore(storeIdentifier, region);
+ JsonNode requests = request.get("requests");
+ if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 30) {
+ throw VerifiedPermissionsService.validation("requests must contain between 1 and 30 items.");
+ }
+ ObjectNode out = objectMapper.createObjectNode();
+ ArrayNode results = out.putArray("results");
+ io.github.hectorvent.floci.services.verifiedpermissions.model.EntityIdentifier principal = null;
+ for (JsonNode item : requests) {
+ ObjectNode single = objectMapper.createObjectNode();
+ single.put("policyStoreId", storeIdentifier);
+ if (request.has("identityToken")) {
+ single.set("identityToken", request.get("identityToken"));
+ }
+ if (request.has("accessToken")) {
+ single.set("accessToken", request.get("accessToken"));
+ }
+ if (request.has("entities")) {
+ single.set("entities", request.get("entities"));
+ }
+ if (item.has("action")) {
+ single.set("action", item.get("action"));
+ }
+ if (item.has("resource")) {
+ single.set("resource", item.get("resource"));
+ }
+ if (item.has("context")) {
+ single.set("context", item.get("context"));
+ }
+ VerifiedPermissionsTokenService.PreparedTokenRequest prepared = tokenService.prepare(single, region);
+ if (principal == null) {
+ principal = prepared.principal();
+ }
+ CedarAuthorizationEvaluator.EvaluationResult evaluation = authorizationEvaluator.evaluate(prepared.request(),
+ service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
+ ObjectNode result = authorizationResult(evaluation);
+ result.set("request", item.deepCopy());
+ results.add(result);
+ }
+ addEntity(out, "principal", principal);
+ return out;
+ }
+
+ private ObjectNode isAuthorized(JsonNode request, String region) {
+ String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
+ service.getPolicyStore(storeIdentifier, region);
+ CedarAuthorizationEvaluator.EvaluationResult result = authorizationEvaluator.evaluate(request,
+ service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
+ return authorizationResult(result);
+ }
+
+ private ObjectNode batchIsAuthorized(JsonNode request, String region) {
+ String storeIdentifier = VerifiedPermissionsService.requiredText(request, "policyStoreId");
+ service.getPolicyStore(storeIdentifier, region);
+ JsonNode requests = request.get("requests");
+ if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 30) {
+ throw VerifiedPermissionsService.validation("requests must contain between 1 and 30 items.");
+ }
+ validateBatchSharedDimension(requests);
+ ObjectNode out = objectMapper.createObjectNode();
+ ArrayNode results = out.putArray("results");
+ for (JsonNode batchRequest : requests) {
+ ObjectNode evaluationRequest = batchRequest.deepCopy();
+ if (request.has("entities")) {
+ evaluationRequest.set("entities", request.get("entities"));
+ }
+ CedarAuthorizationEvaluator.EvaluationResult result = authorizationEvaluator.evaluate(evaluationRequest,
+ service.policiesForStore(storeIdentifier, region), service.templatesForStore(storeIdentifier, region));
+ ObjectNode item = authorizationResult(result);
+ item.set("request", batchRequest.deepCopy());
+ results.add(item);
+ }
+ return out;
+ }
+
+ private void validateBatchSharedDimension(JsonNode requests) {
+ String principal = null;
+ String resource = null;
+ boolean principalsSame = true;
+ boolean resourcesSame = true;
+ for (JsonNode item : requests) {
+ String nextPrincipal = item.has("principal") ? item.get("principal").toString() : "<absent>";
+ String nextResource = item.has("resource") ? item.get("resource").toString() : "<absent>";
+ if (principal == null) {
+ principal = nextPrincipal;
+ } else {
+ principalsSame &= principal.equals(nextPrincipal);
+ }
+ if (resource == null) {
+ resource = nextResource;
+ } else {
+ resourcesSame &= resource.equals(nextResource);
+ }
+ }
+ if (!principalsSame && !resourcesSame) {
+ throw VerifiedPermissionsService.validation("BatchIsAuthorized requires either the same principal or the same resource in every request.");
+ }
+ }
+
+ private ObjectNode authorizationResult(CedarAuthorizationEvaluator.EvaluationResult result) {
+ ObjectNode out = objectMapper.createObjectNode();
+ out.put("decision", result.decision());
+ ArrayNode determining = out.putArray("determiningPolicies");
+ result.determiningPolicyIds().forEach(id -> determining.addObject().put("policyId", id));
+ ArrayNode errors = out.putArray("errors");
+ result.errors().forEach(message -> errors.addObject().put("errorDescription", message));
+ return out;
+ }
+
+ private ObjectNode policyTemplateDetail(PolicyTemplate template) {
+ ObjectNode out = objectMapper.createObjectNode();
+ time(out, "createdDate", template.createdDate());
+ time(out, "lastUpdatedDate", template.lastUpdatedDate());
+ out.put("policyStoreId", template.policyStoreId());
+ out.put("policyTemplateId", template.policyTemplateId());
+ out.put("statement", template.statement());
+ if (template.description() != null) {
+ out.put("description", template.description());
+ }
+ if (template.name() != null) {
+ out.put("name", template.name());
+ }
+ return out;
+ }
+
+ private ObjectNode policyTemplateUpdate(PolicyTemplate template) {
+ ObjectNode out = objectMapper.createObjectNode();
+ time(out, "createdDate", template.createdDate());
+ time(out, "lastUpdatedDate", template.lastUpdatedDate());
+ out.put("policyStoreId", template.policyStoreId());
+ out.put("policyTemplateId", template.policyTemplateId());
+ return out;
+ }
+
+ private ObjectNode policyTemplateList(PaginatedResult<PolicyTemplate> result) {
+ ObjectNode out = objectMapper.createObjectNode();
+ ArrayNode list = out.putArray("policyTemplates");
+ for (PolicyTemplate template : result.items()) {
+ ObjectNode item = list.addObject();
+ time(item, "createdDate", template.createdDate());
+ time(item, "lastUpdatedDate", template.lastUpdatedDate());
+ item.put("policyStoreId", template.policyStoreId());
+ item.put("policyTemplateId", template.policyTemplateId());
+ if (template.description() != null) {
+ item.put("description", template.description());
+ }
+ if (template.name() != null) {
+ item.put("name", template.name());
+ }
+ }
+ if (result.nextToken() != null) {
+ out.put("nextToken", result.nextToken());
+ }
+ return out;
+ }
+
+ private ObjectNode policyCreateOrUpdate(Policy policy, String region) {
+ ObjectNode out = objectMapper.createObjectNode();
+ time(out, "createdDate", policy.createdDate());
+ time(out, "lastUpdatedDate", policy.lastUpdatedDate());
+ out.put("policyId", policy.policyId());
+ out.put("policyStoreId", policy.policyStoreId());
+ out.put("policyType", policy.policyType());
+ out.put("effect", policy.effect());
+ VerifiedPermissionsService.PolicyMetadata metadata = service.policyMetadata(policy, region);
+ ArrayNode actions = out.putArray("actions");
+ metadata.actions().forEach(action -> {
+ ObjectNode node = actions.addObject();
+ node.put("actionType", action.entityType());
+ node.put("actionId", action.entityId());
+ });
+ addEntity(out, "principal", metadata.principal());
+ addEntity(out, "resource", metadata.resource());
+ return out;
+ }
+
+ private ObjectNode policyDetail(Policy policy, String region) {
+ ObjectNode out = policyCreateOrUpdate(policy, region);
+ if (policy.name() != null) {
+ out.put("name", policy.name());
+ }
+ out.set("definition", policyDefinition(policy));
+ return out;
+ }
+
+ private ObjectNode policyDefinition(Policy policy) {
+ ObjectNode definition = objectMapper.createObjectNode();
+ if ("STATIC".equals(policy.policyType())) {
+ ObjectNode body = definition.putObject("static");
+ body.put("statement", policy.statement());
+ if (policy.description() != null) {
+ body.put("description", policy.description());
+ }
+ } else {
+ ObjectNode body = definition.putObject("templateLinked");
+ body.put("policyTemplateId", policy.policyTemplateId());
+ addEntity(body, "principal", policy.principal());
+ addEntity(body, "resource", policy.resource());
+ }
+ return definition;
+ }
+
+ private ObjectNode policyList(PaginatedResult<Policy> result, String region) {
+ ObjectNode out = objectMapper.createObjectNode();
+ ArrayNode list = out.putArray("policies");
+ for (Policy policy : result.items()) {
+ ObjectNode item = policyDetail(policy, region);
+ list.add(item);
+ }
+ if (result.nextToken() != null) {
+ out.put("nextToken", result.nextToken());
+ }
+ return out;
+ }
+
+ private ObjectNode batchGetPolicy(JsonNode request, String region) {
+ JsonNode requests = request.get("requests");
+ if (requests == null || !requests.isArray() || requests.isEmpty() || requests.size() > 100) {
+ throw VerifiedPermissionsService.validation("requests must contain between 1 and 100 items.");
+ }
+ ObjectNode out = objectMapper.createObjectNode();
+ ArrayNode results = out.putArray("results");
+ ArrayNode errors = out.putArray("errors");
+ for (JsonNode item : requests) {
+ String store = VerifiedPermissionsService.requiredText(item, "policyStoreId");
+ String policy = VerifiedPermissionsService.requiredText(item, "policyId");
+ try {
+ results.add(policyDetail(service.getPolicy(store, policy, region), region));
+ } catch (io.github.hectorvent.floci.core.common.AwsException e) {
+ ObjectNode error = errors.addObject();
+ error.put("policyStoreId", store);
+ error.put("policyId", policy);
+ boolean alias = store.startsWith("policy-store-alias/");
+ if (alias) {
+ error.put("code", "POLICY_STORE_ALIAS_NOT_FOUND");
+ } else if ("ResourceNotFoundException".equals(e.getErrorCode()) && !storeExists(store, region)) {
+ error.put("code", "POLICY_STORE_NOT_FOUND");
+ } else {
+ error.put("code", "POLICY_NOT_FOUND");
+ }
+ error.put("message", e.getMessage());
+ }
+ }
+ return out;
+ }
+
+ private boolean storeExists(String id, String region) {
+ try { service.getPolicyStore(id, region); return true; }
+ catch (io.github.hectorvent.floci.core.common.AwsException e) { return false; }
+ }
+
+ private static void addEntity(ObjectNode out, String field, io.github.hectorvent.floci.services.verifiedpermissions.model.EntityIdentifier entity) {
+ if (entity == null) {
+ return;
+ }
+ ObjectNode node = out.putObject(field);
+ node.put("entityType", entity.entityType());
+ node.put("entityId", entity.entityId());
+ }
+
+ private ObjectNode aliasCreate(PolicyStoreAlias alias) {
+ ObjectNode out = objectMapper.createObjectNode();
+ out.put("aliasArn", alias.aliasArn());
+ out.put("aliasName", alias.aliasName());
+ time(out, "createdAt", alias.createdAt());
+ out.put("policyStoreId", alias.policyStoreId());
+ return out;
+ }
+
+ private ObjectNode aliasDetail(PolicyStoreAlias alias) {
+ ObjectNode out = aliasCreate(alias);
+ out.put("state", alias.state());
+ return out;
+ }
+
+ private ObjectNode aliasList(PaginatedResult<PolicyStoreAlias> result) {
+ ObjectNode out = objectMapper.createObjectNode();
+ ArrayNode list = out.putArray("policyStoreAliases");
+ result.items().forEach(a -> list.add(aliasDetail(a)));
+ if (result.nextToken() != null) {
+ out.put("nextToken", result.nextToken());
+ }
+ return out;
+ }
+
+ private ObjectNode tags(Map<String, String> values) {
+ ObjectNode out = objectMapper.createObjectNode();
+ ObjectNode tags = out.putObject("tags");
+ values.forEach(tags::put);
+ return out;
+ }
+
+ private Map<String, String> stringMap(JsonNode node) {
+ if (!node.isObject()) {
+ throw VerifiedPermissionsService.validation("tags is required.");
+ }
+ Map<String, String> out = new java.util.LinkedHashMap<>();
+ node.fields().forEachRemaining(e -> {
+ if (!e.getValue().isTextual()) {
+ throw VerifiedPermissionsService.validation("Tag values must be strings.");
+ }
+ out.put(e.getKey(), e.getValue().asText());
+ });
+ return out;
+ }
+
+ private List<String> stringList(JsonNode node) {
+ if (!node.isArray()) {
+ throw VerifiedPermissionsService.validation("tagKeys is required.");
+ }
+ java.util.ArrayList<String> out = new java.util.ArrayList<>();
+ node.forEach(v -> {
+ if (!v.isTextual()) {
+ throw VerifiedPermissionsService.validation("tagKeys must contain strings.");
+ }
+ out.add(v.asText());
+ });
+ return out;
+ }
+
+ private static void time(ObjectNode node, String field, Instant value) {
+ if (value != null) {
+ node.put(field, value.toString());
+ }
+ }
+
+ private Response ok(JsonNode body) { return Response.ok(body).build(); }
+ private Response empty() { return Response.ok(objectMapper.createObjectNode()).build(); }
+ private ObjectNode error(String type, String message) {
+ ObjectNode node = objectMapper.createObjectNode();
+ node.put("__type", type);
+ node.put("message", message);
+ return node;
+ }
+}
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<String, CachedJwks> jwksCache = new ConcurrentHashMap<>();
+ private final Map<String, Instant> unknownKidRefreshes = new ConcurrentHashMap<>();
+ private final Map<String, Object> issuerLocks = new ConcurrentHashMap<>();
+
+ @Inject
+ public VerifiedPermissionsOidcSignatureVerifier(ObjectMapper objectMapper) {
+ this(objectMapper, SystemDefaultDnsResolver.INSTANCE);
+ }
+
+ VerifiedPermissionsOidcSignatureVerifier(ObjectMapper objectMapper, DnsResolver dnsResolver) {
+ this.objectMapper = objectMapper;
+ DnsResolver validatingResolver = new PublicOnlyDnsResolver(dnsResolver);
+ ConnectionConfig connectionConfig = ConnectionConfig.custom()
+ .setConnectTimeout(Timeout.of(HTTP_TIMEOUT))
+ .setSocketTimeout(Timeout.of(HTTP_TIMEOUT))
+ .build();
+ PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
+ .setDnsResolver(validatingResolver)
+ .setDefaultConnectionConfig(connectionConfig)
+ .build();
+ RequestConfig requestConfig = RequestConfig.custom()
+ .setConnectionRequestTimeout(Timeout.of(HTTP_TIMEOUT))
+ .setResponseTimeout(Timeout.of(HTTP_TIMEOUT))
+ .setRedirectsEnabled(false)
+ .build();
+ this.httpClient = HttpClients.custom()
+ .setConnectionManager(connectionManager)
+ .setDefaultRequestConfig(requestConfig)
+ .disableRedirectHandling()
+ .disableAutomaticRetries()
+ .disableCookieManagement()
+ .build();
+ }
+
+ public void verify(String token, String issuer) throws VerificationException {
+ validatePublicHttpsUri(issuer, "OIDC issuer");
+ String[] parts = token == null ? new String[0] : token.split("\\.", -1);
+ if (parts.length != 3) {
+ throw new VerificationException("Token is not a well-formed JWT");
+ }
+ JsonNode header = decodeJson(parts[0]);
+ String alg = header.path("alg").asText("");
+ if (!"RS256".equals(alg)) {
+ throw new VerificationException("Unsupported token signing algorithm: " + (alg.isEmpty() ? "none" : alg));
+ }
+ String kid = header.path("kid").asText(null);
+ if (kid == null || kid.isBlank()) {
+ throw new VerificationException("Token header has no kid");
+ }
+ RSAPublicKey key = resolveKey(issuer, kid);
+ if (key == null) {
+ throw new VerificationException("No JWKS key matches kid '" + kid + "' for issuer " + issuer);
+ }
+ if (!signatureValid(parts[0] + "." + parts[1], parts[2], key)) {
+ throw new VerificationException("Token signature is invalid");
+ }
+ }
+ RSAPublicKey resolveKey(String issuer, String kid) throws VerificationException {
+ Object lock = issuerLocks.computeIfAbsent(issuer, ignored -> new Object());
+ synchronized (lock) {
+ Instant now = Instant.now();
+ CachedJwks cached = jwksCache.get(issuer);
+ if (cached == null || cached.expired()) {
+ Map<String, RSAPublicKey> fetched = fetchJwks(issuer);
+ jwksCache.put(issuer, new CachedJwks(fetched, now));
+ if (!fetched.containsKey(kid)) {
+ unknownKidRefreshes.put(issuer, now);
+ }
+ return fetched.get(kid);
+ }
+
+ RSAPublicKey cachedKey = cached.keysByKid().get(kid);
+ if (cachedKey != null) {
+ return cachedKey;
+ }
+
+ Instant lastRefresh = unknownKidRefreshes.get(issuer);
+ if (lastRefresh != null && now.isBefore(lastRefresh.plus(UNKNOWN_KID_REFRESH_COOLDOWN))) {
+ return null;
+ }
+
+ Map<String, RSAPublicKey> refreshed = fetchJwks(issuer);
+ unknownKidRefreshes.put(issuer, now);
+ jwksCache.put(issuer, new CachedJwks(refreshed, now));
+ return refreshed.get(kid);
+ }
+ }
+
+ Map<String, RSAPublicKey> fetchJwks(String issuer) throws VerificationException {
+ String discoveryUrl = issuer.replaceAll("/+$", "") + "/.well-known/openid-configuration";
+ JsonNode discovery = getJson(discoveryUrl, "OIDC discovery document");
+ String jwksUri = discovery.path("jwks_uri").asText(null);
+ if (jwksUri == null || jwksUri.isBlank()) {
+ throw new VerificationException("OIDC discovery document has no jwks_uri");
+ }
+ validatePublicHttpsUri(jwksUri, "JWKS document");
+ JsonNode jwks = getJson(jwksUri, "JWKS document");
+ JsonNode keys = jwks.path("keys");
+ if (!keys.isArray()) {
+ throw new VerificationException("JWKS document has no keys array");
+ }
+ Map<String, RSAPublicKey> result = new ConcurrentHashMap<>();
+ for (JsonNode jwk : keys) {
+ String kty = jwk.path("kty").asText("");
+ String keyId = jwk.path("kid").asText(null);
+ if (!"RSA".equals(kty) || keyId == null || keyId.isBlank()) {
+ continue;
+ }
+ String modulus = jwk.path("n").asText(null);
+ String exponent = jwk.path("e").asText(null);
+ if (modulus == null || exponent == null) {
+ continue;
+ }
+ try {
+ result.put(keyId, toRsaPublicKey(modulus, exponent));
+ } catch (GeneralSecurityException | IllegalArgumentException e) {
+ LOG.debugv("Skipping unparsable OIDC key {0}: {1}", keyId, e.getMessage());
+ }
+ }
+ return result;
+ }
+
+ private JsonNode getJson(String url, String description) throws VerificationException {
+ URI uri = validatePublicHttpsUri(url, description);
+ HttpClientContext context = HttpClientContext.create();
+ try {
+ return httpClient.execute(ClassicRequestBuilder.get(uri).build(), context, response -> {
+ if (response.getCode() >= 300 && response.getCode() < 400) {
+ throw new VerificationException("Redirects aren't allowed while fetching " + description);
+ }
+ if (response.getCode() != HttpStatus.SC_OK) {
+ throw new VerificationException("Fetching " + description + " returned HTTP " + response.getCode());
+ }
+ byte[] body;
+ if (response.getEntity() == null) {
+ body = new byte[0];
+ } else {
+ try (InputStream input = response.getEntity().getContent()) {
+ body = readBoundedBody(input, response.getEntity().getContentLength(), description);
+ }
+ }
+ try {
+ return objectMapper.readTree(body);
+ } catch (Exception e) {
+ throw new VerificationException(description + " is not valid JSON", e);
+ }
+ });
+ } catch (VerificationException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new VerificationException("Failed to fetch " + description, e);
+ }
+ }
+
+ static byte[] readBoundedBody(InputStream input, long contentLength, String description)
+ throws IOException, VerificationException {
+ if (contentLength > MAX_OIDC_DOCUMENT_BYTES) {
+ throw new VerificationException(description + " exceeds the maximum allowed response size");
+ }
+ byte[] body = input.readNBytes(MAX_OIDC_DOCUMENT_BYTES + 1);
+ if (body.length > MAX_OIDC_DOCUMENT_BYTES) {
+ throw new VerificationException(description + " exceeds the maximum allowed response size");
+ }
+ return body;
+ }
+
+ static URI validatePublicHttpsUri(String value, String description) throws VerificationException {
+ URI uri;
+ try {
+ uri = URI.create(value);
+ } catch (IllegalArgumentException e) {
+ throw new VerificationException("Invalid " + description + " URL", e);
+ }
+ if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getHost().isBlank()
+ || uri.getUserInfo() != null) {
+ throw new VerificationException(description + " must use a public HTTPS URL");
+ }
+ String host = uri.getHost();
+ boolean literalAddress = host.indexOf(':') >= 0 || host.matches("[0-9]{1,3}(?:\\.[0-9]{1,3}){3}");
+ if (literalAddress && isBlockedPublicAddress(InetAddress.ofLiteral(host))) {
+ throw new VerificationException(description + " resolves to a non-public address");
+ }
+ return uri;
+ }
+
+ private static RSAPublicKey toRsaPublicKey(String n, String e) throws GeneralSecurityException {
+ BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(pad(n)));
+ BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(pad(e)));
+ return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, exponent));
+ }
+
+ private static boolean signatureValid(String signingInput, String encodedSignature, RSAPublicKey key) {
+ try {
+ Signature signature = Signature.getInstance("SHA256withRSA");
+ signature.initVerify(key);
+ signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
+ return signature.verify(Base64.getUrlDecoder().decode(pad(encodedSignature)));
+ } catch (GeneralSecurityException | IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ private JsonNode decodeJson(String segment) throws VerificationException {
+ try {
+ JsonNode node = objectMapper.readTree(Base64.getUrlDecoder().decode(pad(segment)));
+ if (node == null || !node.isObject()) {
+ throw new VerificationException("Token header is not valid JSON");
+ }
+ return node;
+ } catch (IllegalArgumentException | java.io.IOException e) {
+ throw new VerificationException("Token header is not valid JSON", e);
+ }
+ }
+
+ private static String pad(String value) {
+ return switch (value.length() % 4) {
+ case 2 -> value + "==";
+ case 3 -> value + "=";
+ default -> value;
+ };
+ }
+
+ @PreDestroy
+ @Override
+ public void close() {
+ try {
+ httpClient.close();
+ } catch (Exception e) {
+ LOG.debugv("Could not close Verified Permissions OIDC client: {0}", e.getMessage());
+ }
+ }
+
+ private record CachedJwks(Map<String, RSAPublicKey> keysByKid, Instant fetchedAt) {
+ boolean expired() {
+ return Instant.now().isAfter(fetchedAt.plus(CACHE_TTL));
+ }
+ }
+
+ private record PublicOnlyDnsResolver(DnsResolver delegate) implements DnsResolver {
+ @Override
+ public InetAddress[] resolve(String host) throws UnknownHostException {
+ InetAddress[] addresses = delegate.resolve(host);
+ if (addresses == null || addresses.length == 0) {
+ throw new UnknownHostException("OIDC host has no addresses: " + host);
+ }
+ for (InetAddress address : addresses) {
+ if (isBlockedPublicAddress(address)) {
+ throw new UnknownHostException("OIDC host resolves to a non-public address: " + host);
+ }
+ }
+ return addresses.clone();
+ }
+
+ @Override
+ public String resolveCanonicalHostname(String host) {
+ return host;
+ }
+ }
+
+ static boolean isBlockedPublicAddress(InetAddress address) {
+ if (address.isAnyLocalAddress() || address.isLoopbackAddress()
+ || address.isLinkLocalAddress() || address.isSiteLocalAddress()
+ || address.isMulticastAddress()) {
+ return true;
+ }
+ byte[] bytes = address.getAddress();
+ if (bytes.length == 4) {
+ return blockedIpv4(bytes, 0);
+ }
+ if (bytes.length == 16) {
+ if (ipv4Mapped(bytes)) {
+ return blockedIpv4(bytes, 12);
+ }
+ int first = Byte.toUnsignedInt(bytes[0]);
+ boolean uniqueLocal = (first & 0xfe) == 0xfc;
+ boolean documentation = first == 0x20
+ && Byte.toUnsignedInt(bytes[1]) == 0x01
+ && Byte.toUnsignedInt(bytes[2]) == 0x0d
+ && Byte.toUnsignedInt(bytes[3]) == 0xb8;
+ return uniqueLocal || documentation;
+ }
+ return true;
+ }
+
+ private static boolean ipv4Mapped(byte[] bytes) {
+ for (int i = 0; i < 10; i++) {
+ if (bytes[i] != 0) {
+ return false;
+ }
+ }
+ return bytes[10] == (byte) 0xff && bytes[11] == (byte) 0xff;
+ }
+
+ private static boolean blockedIpv4(byte[] bytes, int offset) {
+ int first = Byte.toUnsignedInt(bytes[offset]);
+ int second = Byte.toUnsignedInt(bytes[offset + 1]);
+ int third = Byte.toUnsignedInt(bytes[offset + 2]);
+ return first == 0
+ || first == 10
+ || first == 127
+ || (first == 100 && second >= 64 && second <= 127)
+ || (first == 169 && second == 254)
+ || (first == 172 && second >= 16 && second <= 31)
+ || (first == 192 && second == 168)
+ || (first == 192 && second == 0 && third == 0)
+ || (first == 192 && second == 0 && third == 2)
+ || (first == 198 && (second == 18 || second == 19))
+ || (first == 198 && second == 51 && third == 100)
+ || (first == 203 && second == 0 && third == 113)
+ || first >= 224;
+ }
+
+ public static class VerificationException extends RuntimeException {
+ public VerificationException(String message) {
+ super(message);
+ }
+
+ public VerificationException(String message, Throwable cause) {
+ super(message, cause);
+ }
+ }
+}
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<String, PolicyStore> policyStores;
+ private final StorageBackend<String, PolicyStoreAlias> aliases;
+ private final StorageBackend<String, Policy> policies;
+ private final StorageBackend<String, PolicyTemplate> policyTemplates;
+ private final StorageBackend<String, IdempotencyRecord> idempotency;
+ private final StorageBackend<String, IdentitySource> 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<Map<String, PolicyStore>>() {}),
+ storageFactory.create("verifiedpermissions", "verifiedpermissions-policy-store-aliases.json",
+ new TypeReference<Map<String, PolicyStoreAlias>>() {}),
+ storageFactory.create("verifiedpermissions", "verifiedpermissions-policies.json",
+ new TypeReference<Map<String, Policy>>() {}),
+ storageFactory.create("verifiedpermissions", "verifiedpermissions-policy-templates.json",
+ new TypeReference<Map<String, PolicyTemplate>>() {}),
+ storageFactory.create("verifiedpermissions", "verifiedpermissions-idempotency.json",
+ new TypeReference<Map<String, IdempotencyRecord>>() {}),
+ storageFactory.create("verifiedpermissions", "verifiedpermissions-identity-sources.json",
+ new TypeReference<Map<String, IdentitySource>>() {}),
+ regionResolver, objectMapper, kmsService, cedarClient);
+ }
+
+ VerifiedPermissionsService(StorageBackend<String, PolicyStore> policyStores,
+ StorageBackend<String, PolicyStoreAlias> aliases,
+ StorageBackend<String, Policy> policies,
+ StorageBackend<String, PolicyTemplate> policyTemplates,
+ StorageBackend<String, IdempotencyRecord> idempotency,
+ StorageBackend<String, IdentitySource> identitySources,
+ RegionResolver regionResolver, ObjectMapper objectMapper, KmsService kmsService,
+ CedarSidecarClient cedarClient) {
+ this.policyStores = policyStores;
+ this.aliases = aliases;
+ this.policies = policies;
+ this.policyTemplates = policyTemplates;
+ this.idempotency = idempotency;
+ this.identitySources = identitySources;
+ this.regionResolver = regionResolver;
+ this.kmsService = kmsService;
+ this.objectMapper = objectMapper;
+ this.cedarClient = cedarClient;
+ }
+
+ public synchronized PolicyStore createPolicyStore(JsonNode request, String region) {
+ IdempotencyRecord replay = findIdempotent("CreatePolicyStore", request, region);
+ if (replay != null) {
+ return getPolicyStore(replay.resourceId(), region);
+ }
+ JsonNode settings = requiredObject(request, "validationSettings");
+ String mode = requiredText(settings, "mode");
+ validateMode(mode);
+ String deletionProtection = text(request, "deletionProtection", "DISABLED");
+ validateDeletionProtection(deletionProtection);
+ String description = text(request, "description", null);
+ validateDescription(description);
+ Map<String, String> tags = stringMap(request.get("tags"));
+ validateTags(tags);
+ Encryption encryption = parseEncryption(request.get("encryptionSettings"), region);
+
+ String id = "PS" + UUID.randomUUID().toString().replace("-", "").substring(0, 20);
+ Instant now = Instant.now();
+ PolicyStore store = new PolicyStore(id, storeArn(region, id), mode, deletionProtection,
+ description, encryption.keyArn(), encryption.context(), tags, null, null, null, now, now);
+ policyStores.put(storeKey(region, id), store);
+ rememberIdempotent("CreatePolicyStore", request, region, id, id);
+ return store;
+ }
+
+ public PolicyStore getPolicyStore(String identifier, String region) {
+ String id = resolveStoreId(identifier, region, true);
+ return policyStores.get(storeKey(region, id))
+ .orElseThrow(() -> notFound("Policy store not found: " + identifier));
+ }
+
+ public synchronized PolicyStore updatePolicyStore(JsonNode request, String region) {
+ PolicyStore current = getPolicyStore(requiredText(request, "policyStoreId"), region);
+ JsonNode settings = requiredObject(request, "validationSettings");
+ String mode = requiredText(settings, "mode");
+ validateMode(mode);
+ String deletionProtection = request.has("deletionProtection")
+ ? requiredText(request, "deletionProtection") : current.deletionProtection();
+ validateDeletionProtection(deletionProtection);
+ String description = request.has("description") ? request.path("description").asText() : current.description();
+ validateDescription(description);
+ PolicyStore updated = current.withSettings(mode, deletionProtection, description, Instant.now());
+ policyStores.put(storeKey(region, updated.policyStoreId()), updated);
+ return updated;
+ }
+
+ public synchronized void deletePolicyStore(String identifier, String region) {
+ String id = resolveStoreId(identifier, region, false);
+ PolicyStore store = policyStores.get(storeKey(region, id)).orElse(null);
+ if (store == null) {
+ return;
+ }
+ if ("ENABLED".equals(store.deletionProtection())) {
+ throw new AwsException("InvalidStateException", "The policy store can't be deleted because deletion protection is enabled.", 400);
+ }
+ policyStores.delete(storeKey(region, store.policyStoreId()));
+ aliases.scan(k -> k.startsWith(region + ":")).stream()
+ .filter(a -> a.policyStoreId().equals(store.policyStoreId()))
+ .forEach(a -> aliases.delete(aliasKey(region, a.aliasName())));
+ policies.keys().stream().filter(k -> k.startsWith(region + ":" + store.policyStoreId() + ":"))
+ .toList().forEach(policies::delete);
+ policyTemplates.keys().stream().filter(k -> k.startsWith(region + ":" + store.policyStoreId() + ":"))
+ .toList().forEach(policyTemplates::delete);
+ identitySources.keys().stream().filter(k -> k.startsWith(region + ":" + store.policyStoreId() + ":"))
+ .toList().forEach(identitySources::delete);
+ }
+
+ public PaginatedResult<PolicyStore> listPolicyStores(JsonNode request, String region) {
+ List<PolicyStore> stores = policyStores.scan(k -> k.startsWith(region + ":")).stream()
+ .sorted(Comparator.comparing(PolicyStore::policyStoreId)).toList();
+ return Pagination.paginate(stores, PolicyStore::policyStoreId,
+ optionalInt(request, "maxResults"), text(request, "nextToken", null), 10, 50, "ValidationException");
+ }
+
+ public synchronized PolicyStore putSchema(JsonNode request, String region) {
+ PolicyStore store = getPolicyStore(requiredText(request, "policyStoreId"), region);
+ JsonNode definition = requiredObject(request, "definition");
+ if (!definition.has("cedarJson") || !definition.get("cedarJson").isTextual()) {
+ throw validation("definition.cedarJson is required.");
+ }
+ String schema = definition.get("cedarJson").asText();
+ validateSchemaJson(schema);
+ Instant now = Instant.now();
+ Instant created = store.schemaCreatedDate() == null ? now : store.schemaCreatedDate();
+ PolicyStore updated = store.withSchema("{}".equals(schema.trim()) ? null : schema,
+ "{}".equals(schema.trim()) ? null : created,
+ "{}".equals(schema.trim()) ? null : now);
+ policyStores.put(storeKey(region, store.policyStoreId()), updated);
+ return updated;
+ }
+
+ public PolicyStore getSchema(String identifier, String region) {
+ PolicyStore store = getPolicyStore(identifier, region);
+ if (store.schema() == null) {
+ throw notFound("Schema not found for policy store: " + store.policyStoreId());
+ }
+ return store;
+ }
+
+
+
+ public synchronized IdentitySource createIdentitySource(JsonNode request, String region) {
+ IdempotencyRecord replay = findIdempotent("CreateIdentitySource", request, region);
+ if (replay != null) {
+ return getIdentitySource(replay.policyStoreId(), replay.resourceId(), region);
+ }
+ PolicyStore store = getPolicyStore(requiredText(request, "policyStoreId"), region);
+ JsonNode configuration = normalizeIdentityConfiguration(requiredObject(request, "configuration"), region);
+ String principalEntityType = text(request, "principalEntityType", "AWS::Cognito");
+ validateEntityType(principalEntityType, "principalEntityType");
+ String issuer = identityIssuer(configuration);
+ boolean duplicate = identitySources.scan(k -> k.startsWith(region + ":" + store.policyStoreId() + ":")).stream()
+ .anyMatch(existing -> issuer.equals(identityIssuer(existing.configuration())));
+ if (duplicate) {
+ throw conflict("An identity source for this issuer already exists in the policy store.");
+ }
+ Instant now = Instant.now();
+ String id = "IS" + compactId();
+ IdentitySource source = new IdentitySource(store.policyStoreId(), id, principalEntityType,
+ configuration.deepCopy(), now, now);
+ identitySources.put(identitySourceKey(region, store.policyStoreId(), id), source);
+ rememberIdempotent("CreateIdentitySource", request, region, id, store.policyStoreId());
+ return source;
+ }
+
+ public IdentitySource getIdentitySource(String storeIdentifier, String identitySourceId, String region) {
+ PolicyStore store = getPolicyStore(storeIdentifier, region);
+ return identitySources.get(identitySourceKey(region, store.policyStoreId(), identitySourceId))
+ .orElseThrow(() -> notFound("Identity source not found: " + identitySourceId));
+ }
+
+ public synchronized IdentitySource updateIdentitySource(JsonNode request, String region) {
+ IdentitySource current = getIdentitySource(requiredText(request, "policyStoreId"),
+ requiredText(request, "identitySourceId"), region);
+ JsonNode update = requiredObject(request, "updateConfiguration");
+ JsonNode normalized = normalizeIdentityConfiguration(update, region);
+ String oldKind = identityConfigurationKind(current.configuration());
+ String newKind = identityConfigurationKind(normalized);
+ if (!oldKind.equals(newKind)) {
+ throw validation("The identity provider type can't be changed by UpdateIdentitySource.");
+ }
+ String principalType = request.has("principalEntityType")
+ ? request.path("principalEntityType").asText() : current.principalEntityType();
+ validateEntityType(principalType, "principalEntityType");
+ String issuer = identityIssuer(normalized);
+ boolean duplicate = identitySources.scan(k -> k.startsWith(region + ":" + current.policyStoreId() + ":")).stream()
+ .anyMatch(existing -> !existing.identitySourceId().equals(current.identitySourceId())
+ && issuer.equals(identityIssuer(existing.configuration())));
+ if (duplicate) {
+ throw conflict("An identity source for this issuer already exists in the policy store.");
+ }
+ IdentitySource updated = current.updated(principalType, normalized.deepCopy(), Instant.now());
+ identitySources.put(identitySourceKey(region, current.policyStoreId(), current.identitySourceId()), updated);
+ return updated;
+ }
+
+ public synchronized void deleteIdentitySource(String storeIdentifier, String identitySourceId, String region) {
+ IdentitySource source = getIdentitySource(storeIdentifier, identitySourceId, region);
+ identitySources.delete(identitySourceKey(region, source.policyStoreId(), source.identitySourceId()));
+ }
+
+ public PaginatedResult<IdentitySource> listIdentitySources(JsonNode request, String region) {
+ PolicyStore store = getPolicyStore(requiredText(request, "policyStoreId"), region);
+ JsonNode filters = request.get("filters");
+ validateIdentityFilters(filters);
+ List<IdentitySource> items = identitySources.scan(k -> k.startsWith(region + ":" + store.policyStoreId() + ":")).stream()
+ .filter(source -> matchesIdentityFilters(source, filters))
+ .sorted(Comparator.comparing(IdentitySource::identitySourceId)).toList();
+ return Pagination.paginate(items, IdentitySource::identitySourceId, optionalInt(request, "maxResults"),
+ text(request, "nextToken", null), 10, 50, "ValidationException");
+ }
+
+ public List<IdentitySource> identitySourcesForStore(String storeIdentifier, String region) {
+ PolicyStore store = getPolicyStore(storeIdentifier, region);
+ return identitySources.scan(k -> k.startsWith(region + ":" + store.policyStoreId() + ":"));
+ }
+
+ public synchronized PolicyTemplate createPolicyTemplate(JsonNode request, String region) {
+ IdempotencyRecord replay = findIdempotent("CreatePolicyTemplate", request, region);
+ if (replay != null) {
+ return getPolicyTemplate(replay.policyStoreId(), replay.resourceId(), region);
+ }
+ PolicyStore store = getPolicyStore(requiredText(request, "policyStoreId"), region);
+ String statement = requiredText(request, "statement");
+ validatePolicyStatement(statement);
+ validateTemplate(statement);
+ validateStrictPolicy(store, statement, true);
+ String name = optionalName(request, "name");
+ ensureTemplateNameAvailable(region, store.policyStoreId(), name, null);
+ String description = text(request, "description", null);
+ validateDescription(description);
+ String id = "PT" + compactId();
+ Instant now = Instant.now();
+ PolicyTemplate template = new PolicyTemplate(store.policyStoreId(), id, name, statement,
+ description, now, now);
+ policyTemplates.put(templateKey(region, store.policyStoreId(), id), template);
+ rememberIdempotent("CreatePolicyTemplate", request, region, id, store.policyStoreId());
+ return template;
+ }
+
+ public PolicyTemplate getPolicyTemplate(String storeIdentifier, String templateIdentifier, String region) {
+ PolicyStore store = getPolicyStore(storeIdentifier, region);
+ String id = resolveTemplateId(region, store.policyStoreId(), templateIdentifier);
+ return policyTemplates.get(templateKey(region, store.policyStoreId(), id))
+ .orElseThrow(() -> notFound("Policy template not found: " + templateIdentifier));
+ }
+
+ public synchronized PolicyTemplate updatePolicyTemplate(JsonNode request, String region) {
+ PolicyTemplate current = getPolicyTemplate(requiredText(request, "policyStoreId"),
+ requiredText(request, "policyTemplateId"), region);
+ String statement = requiredText(request, "statement");
+ validatePolicyStatement(statement);
+ validateTemplate(statement);
+ ensureProtectedScopeUnchanged(current.statement(), statement, true);
+ PolicyStore store = getPolicyStore(current.policyStoreId(), region);
+ validateStrictPolicy(store, statement, true);
+ String name = request.has("name") ? normalizeOptionalName(request.get("name").asText()) : current.name();
+ ensureTemplateNameAvailable(region, current.policyStoreId(), name, current.policyTemplateId());
+ String description = request.has("description") ? request.path("description").asText() : current.description();
+ validateDescription(description);
+ PolicyTemplate updated = current.updated(name, statement, description, Instant.now());
+ policyTemplates.put(templateKey(region, current.policyStoreId(), current.policyTemplateId()), updated);
+ return updated;
+ }
+
+ public synchronized void deletePolicyTemplate(String storeIdentifier, String templateIdentifier, String region) {
+ PolicyTemplate template = getPolicyTemplate(storeIdentifier, templateIdentifier, region);
+ policies.keys().stream()
+ .filter(k -> k.startsWith(region + ":" + template.policyStoreId() + ":"))
+ .filter(k -> policies.get(k).map(p -> template.policyTemplateId().equals(p.policyTemplateId())).orElse(false))
+ .toList()
+ .forEach(policies::delete);
+ policyTemplates.delete(templateKey(region, template.policyStoreId(), template.policyTemplateId()));
+ }
+
+ public PaginatedResult<PolicyTemplate> listPolicyTemplates(JsonNode request, String region) {
+ PolicyStore store = getPolicyStore(requiredText(request, "policyStoreId"), region);
+ List<PolicyTemplate> items = policyTemplates.scan(k -> k.startsWith(region + ":" + store.policyStoreId() + ":")).stream()
+ .sorted(Comparator.comparing(PolicyTemplate::policyTemplateId)).toList();
+ return Pagination.paginate(items, PolicyTemplate::policyTemplateId, optionalInt(request, "maxResults"),
+ text(request, "nextToken", null), 10, 50, "ValidationException");
+ }
+
+ public synchronized Policy createPolicy(JsonNode request, String region) {
+ IdempotencyRecord replay = findIdempotent("CreatePolicy", request, region);
+ if (replay != null) {
+ return getPolicy(replay.policyStoreId(), replay.resourceId(), region);
+ }
+ PolicyStore store = getPolicyStore(requiredText(request, "policyStoreId"), region);
+ JsonNode definition = requiredObject(request, "definition");
+ String name = optionalName(request, "name");
+ ensurePolicyNameAvailable(region, store.policyStoreId(), name, null);
+ Instant now = Instant.now();
+ Policy policy;
+ if (definition.has("static") && definition.get("static").isObject() && definition.size() == 1) {
+ JsonNode body = definition.get("static");
+ String statement = requiredText(body, "statement");
+ validatePolicyStatement(statement);
+ String description = text(body, "description", null);
+ validateDescription(description);
+ String effect = validateStaticPolicy(statement);
+ validateStrictPolicy(store, statement, false);
+ policy = new Policy(store.policyStoreId(), "SP" + compactId(), name, "STATIC", statement,
+ description, null, null, null, effect, now, now);
+ } else if (definition.has("templateLinked") && definition.get("templateLinked").isObject() && definition.size() == 1) {
+ JsonNode body = definition.get("templateLinked");
+ PolicyTemplate template = getPolicyTemplate(store.policyStoreId(), requiredText(body, "policyTemplateId"), region);
+ EntityIdentifier principal = entityIdentifier(body.get("principal"));
+ EntityIdentifier resource = entityIdentifier(body.get("resource"));
+ validateTemplateSlots(template.statement(), principal, resource);
+ policy = new Policy(store.policyStoreId(), "LP" + compactId(), name, "TEMPLATE_LINKED", null, null,
+ template.policyTemplateId(), principal, resource, templateEffect(template.statement()), now, now);
+ } else {
+ throw validation("definition must contain exactly one of static or templateLinked.");
+ }
+ policies.put(policyKey(region, store.policyStoreId(), policy.policyId()), policy);
+ rememberIdempotent("CreatePolicy", request, region, policy.policyId(), store.policyStoreId());
+ return policy;
+ }
+
+ public Policy getPolicy(String storeIdentifier, String policyIdentifier, String region) {
+ PolicyStore store = getPolicyStore(storeIdentifier, region);
+ String id = resolvePolicyId(region, store.policyStoreId(), policyIdentifier);
+ return policies.get(policyKey(region, store.policyStoreId(), id))
+ .orElseThrow(() -> notFound("Policy not found: " + policyIdentifier));
+ }
+
+ public synchronized Policy updatePolicy(JsonNode request, String region) {
+ Policy current = getPolicy(requiredText(request, "policyStoreId"), requiredText(request, "policyId"), region);
+ if (!"STATIC".equals(current.policyType())) {
+ throw validation("Only static policies can be updated.");
+ }
+
+ String statement = current.statement();
+ String description = current.description();
+ JsonNode definition = request.get("definition");
+ if (definition != null && !definition.isNull()) {
+ if (!definition.isObject() || !definition.has("static")
+ || !definition.get("static").isObject() || definition.size() != 1) {
+ throw validation("definition must contain exactly one static member when updating a policy.");
+ }
+ JsonNode body = definition.get("static");
+ statement = requiredText(body, "statement");
+ validatePolicyStatement(statement);
+ String effect = validateStaticPolicy(statement);
+ if (!effect.equals(current.effect())) {
+ throw validation("The policy effect can't be changed by UpdatePolicy.");
+ }
+ ensureProtectedScopeUnchanged(current.statement(), statement, false);
+ PolicyStore store = getPolicyStore(current.policyStoreId(), region);
+ validateStrictPolicy(store, statement, false);
+ if (body.has("description")) {
+ description = body.path("description").asText();
+ }
+ }
+ validateDescription(description);
+ String name = request.has("name") ? normalizeOptionalName(request.get("name").asText()) : current.name();
+ ensurePolicyNameAvailable(region, current.policyStoreId(), name, current.policyId());
+ Policy updated = current.updated(name, statement, description, Instant.now());
+ policies.put(policyKey(region, current.policyStoreId(), current.policyId()), updated);
+ return updated;
+ }
+
+ public synchronized void deletePolicy(String storeIdentifier, String policyIdentifier, String region) {
+ PolicyStore store = getPolicyStore(storeIdentifier, region);
+ String policyId = resolvePolicyIdOrNull(region, store.policyStoreId(), policyIdentifier);
+ if (policyId != null) {
+ policies.delete(policyKey(region, store.policyStoreId(), policyId));
+ }
+ }
+
+ public PaginatedResult<Policy> listPolicies(JsonNode request, String region) {
+ PolicyStore store = getPolicyStore(requiredText(request, "policyStoreId"), region);
+ JsonNode filter = request.get("filter");
+ List<Policy> items = policies.scan(k -> k.startsWith(region + ":" + store.policyStoreId() + ":")).stream()
+ .filter(p -> matchesPolicyFilter(p, filter))
+ .sorted(Comparator.comparing(Policy::policyId)).toList();
+ return Pagination.paginate(items, Policy::policyId, optionalInt(request, "maxResults"),
+ text(request, "nextToken", null), 10, 50, "ValidationException");
+ }
+
+ public List<Policy> policiesForStore(String policyStoreId, String region) {
+ PolicyStore store = getPolicyStore(policyStoreId, region);
+ return policies.scan(k -> k.startsWith(region + ":" + store.policyStoreId() + ":"));
+ }
+
+ public PolicyTemplate templateForPolicy(Policy policy, String region) {
+ return getPolicyTemplate(policy.policyStoreId(), policy.policyTemplateId(), region);
+ }
+
+ public Map<String, PolicyTemplate> templatesForStore(String policyStoreId, String region) {
+ PolicyStore store = getPolicyStore(policyStoreId, region);
+ Map<String, PolicyTemplate> result = new LinkedHashMap<>();
+ policyTemplates.scan(k -> k.startsWith(region + ":" + store.policyStoreId() + ":"))
+ .forEach(t -> result.put(t.policyTemplateId(), t));
+ return result;
+ }
+
+ public synchronized PolicyStoreAlias createAlias(JsonNode request, String region) {
+ purgeExpiredAliases(region);
+ String aliasName = requiredText(request, "aliasName");
+ validateAliasName(aliasName);
+ String storeId = requiredText(request, "policyStoreId");
+ if (storeId.startsWith("policy-store-alias/")) {
+ throw validation("policyStoreId must be a policy store ID when creating an alias.");
+ }
+ PolicyStore store = getPolicyStore(storeId, region);
+ String key = aliasKey(region, aliasName);
+ PolicyStoreAlias existing = aliases.get(key).orElse(null);
+ if (existing != null) {
+ if ("Active".equals(existing.state()) && existing.policyStoreId().equals(store.policyStoreId())) {
+ return existing;
+ }
+ throw conflict("A policy store alias with this name already exists.");
+ }
+ long aliasCount = aliases.scan(k -> k.startsWith(region + ":")).stream()
+ .filter(a -> a.policyStoreId().equals(store.policyStoreId()))
+ .count();
+ if (aliasCount >= MAX_ALIASES_PER_POLICY_STORE) {
+ throw new AwsException("ServiceQuotaExceededException",
+ "The policy store alias quota has been exceeded for policy store " + store.policyStoreId() + ".", 400);
+ }
+ PolicyStoreAlias alias = new PolicyStoreAlias(aliasName, aliasArn(region, aliasName),
+ store.policyStoreId(), "Active", Instant.now(), null);
+ aliases.put(key, alias);
+ return alias;
+ }
+
+ public PolicyStoreAlias getAlias(String aliasName, String region) {
+ purgeExpiredAliases(region);
+ validateAliasName(aliasName);
+ return aliases.get(aliasKey(region, aliasName))
+ .orElseThrow(() -> notFound("Policy store alias not found: " + aliasName));
+ }
+
+ public PaginatedResult<PolicyStoreAlias> listAliases(JsonNode request, String region) {
+ purgeExpiredAliases(region);
+ String filterStoreId = null;
+ JsonNode filter = request.get("filter");
+ if (filter != null && !filter.isNull()) {
+ filterStoreId = requiredText(filter, "policyStoreId");
+ getPolicyStore(filterStoreId, region);
+ }
+ String finalFilterStoreId = filterStoreId;
+ List<PolicyStoreAlias> items = aliases.scan(k -> k.startsWith(region + ":")).stream()
+ .filter(a -> finalFilterStoreId == null || finalFilterStoreId.equals(a.policyStoreId()))
+ .sorted(Comparator.comparing(PolicyStoreAlias::aliasName)).toList();
+ return Pagination.paginate(items, PolicyStoreAlias::aliasName,
+ optionalInt(request, "maxResults"), text(request, "nextToken", null), 5, 50, "ValidationException");
+ }
+
+ public synchronized void deleteAlias(JsonNode request, String region) {
+ purgeExpiredAliases(region);
+ String aliasName = requiredText(request, "aliasName");
+ validateAliasName(aliasName);
+ String mode = text(request, "deletionMode", "SoftDelete");
+ if (!"SoftDelete".equals(mode) && !"HardDelete".equals(mode)) {
+ throw validation("deletionMode must be SoftDelete or HardDelete.");
+ }
+ String key = aliasKey(region, aliasName);
+ PolicyStoreAlias alias = aliases.get(key).orElse(null);
+ if (alias == null) {
+ return;
+ }
+ if ("HardDelete".equals(mode)) {
+ aliases.delete(key);
+ return;
+ }
+ aliases.put(key, alias.pendingDeletion(Instant.now().plus(ALIAS_SOFT_DELETE_RETENTION)));
+ }
+
+ public synchronized void tagResource(String arn, Map<String, String> tags, String region) {
+ validateTags(tags);
+ PolicyStore store = storeByArn(arn, region);
+ Map<String, String> merged = new LinkedHashMap<>(store.tags());
+ merged.putAll(tags);
+ validateTags(merged);
+ PolicyStore updated = store.withTags(merged, Instant.now());
+ policyStores.put(storeKey(region, store.policyStoreId()), updated);
+ }
+
+ public synchronized void untagResource(String arn, List<String> tagKeys, String region) {
+ PolicyStore store = storeByArn(arn, region);
+ Map<String, String> tags = new LinkedHashMap<>(store.tags());
+ if (tagKeys != null) {
+ tagKeys.forEach(tags::remove);
+ }
+ PolicyStore updated = store.withTags(tags, Instant.now());
+ policyStores.put(storeKey(region, store.policyStoreId()), updated);
+ }
+
+ public Map<String, String> listTags(String arn, String region) {
+ return Map.copyOf(storeByArn(arn, region).tags());
+ }
+
+ String resolveStoreId(String identifier, String region, boolean aliasesAllowed) {
+ if (identifier == null || identifier.isBlank() || identifier.length() > 200 || !STORE_ID.matcher(identifier).matches()) {
+ throw validation("policyStoreId does not satisfy the required constraints.");
+ }
+ if (!identifier.startsWith("policy-store-alias/")) {
+ return identifier;
+ }
+ if (!aliasesAllowed) {
+ throw validation("A policy store alias cannot be used for this operation.");
+ }
+ PolicyStoreAlias alias = getAlias(identifier, region);
+ if (!"Active".equals(alias.state())) {
+ throw notFound("Policy store not found: " + identifier);
+ }
+ return alias.policyStoreId();
+ }
+
+ @Override
+ public void clear() {
+ policyStores.clear();
+ aliases.clear();
+ policies.clear();
+ policyTemplates.clear();
+ idempotency.clear();
+ identitySources.clear();
+ }
+
+
+ private JsonNode normalizeIdentityConfiguration(JsonNode configuration, String region) {
+ if (!configuration.isObject() || configuration.size() != 1) {
+ throw validation("configuration must contain exactly one union member.");
+ }
+ ObjectNode normalized = objectMapper.createObjectNode();
+ if (configuration.has("cognitoUserPoolConfiguration")) {
+ JsonNode source = configuration.get("cognitoUserPoolConfiguration");
+ if (!source.isObject()) {
+ throw validation("cognitoUserPoolConfiguration must be an object.");
+ }
+ ObjectNode cognito = source.deepCopy();
+ String arn = requiredText(cognito, "userPoolArn");
+ String[] arnParts = arn.split(":", 6);
+ if (arnParts.length != 6 || !"cognito-idp".equals(arnParts[2]) || !arnParts[5].startsWith("userpool/")) {
+ throw validation("userPoolArn must be a Cognito user pool ARN.");
+ }
+ if (!region.equals(arnParts[3])) {
+ throw validation("The Cognito user pool must be in the same Region as the policy store.");
+ }
+ String poolId = arnParts[5].substring("userpool/".length());
+ cognito.put("issuer", "https://cognito-idp." + arnParts[3] + ".amazonaws.com/" + poolId);
+ validateStringArray(cognito.get("clientIds"), "clientIds", 0, 1000);
+ JsonNode group = cognito.get("groupConfiguration");
+ if (group != null && !group.isNull()) {
+ validateEntityType(requiredText(group, "groupEntityType"), "groupEntityType");
+ }
+ normalized.set("cognitoUserPoolConfiguration", cognito);
+ return normalized;
+ }
+ if (configuration.has("openIdConnectConfiguration")) {
+ JsonNode source = configuration.get("openIdConnectConfiguration");
+ if (!source.isObject()) {
+ throw validation("openIdConnectConfiguration must be an object.");
+ }
+ ObjectNode oidc = source.deepCopy();
+ String issuer = requiredText(oidc, "issuer");
+ if (!issuer.startsWith("https://") || issuer.length() > 2048) {
+ throw validation("OIDC issuer must use HTTPS and be 2048 characters or fewer.");
+ }
+ JsonNode selection = requiredObject(oidc, "tokenSelection");
+ if (selection.size() != 1 || (!selection.has("accessTokenOnly") && !selection.has("identityTokenOnly"))) {
+ throw validation("tokenSelection must contain exactly one supported token type.");
+ }
+ JsonNode tokenConfig = selection.has("accessTokenOnly") ? selection.get("accessTokenOnly") : selection.get("identityTokenOnly");
+ String listName = selection.has("accessTokenOnly") ? "audiences" : "clientIds";
+ validateStringArray(tokenConfig.get(listName), listName,
+ selection.has("accessTokenOnly") ? 1 : 0,
+ selection.has("accessTokenOnly") ? 255 : 1000);
+ if (tokenConfig.has("principalIdClaim") && tokenConfig.path("principalIdClaim").asText().isBlank()) {
+ throw validation("principalIdClaim can't be empty.");
+ }
+ JsonNode group = oidc.get("groupConfiguration");
+ if (group != null && !group.isNull()) {
+ requiredText(group, "groupClaim");
+ validateEntityType(requiredText(group, "groupEntityType"), "groupEntityType");
+ }
+ normalized.set("openIdConnectConfiguration", oidc);
+ return normalized;
+ }
+ throw validation("configuration must contain cognitoUserPoolConfiguration or openIdConnectConfiguration.");
+ }
+
+ static String identityConfigurationKind(JsonNode configuration) {
+ return configuration.has("cognitoUserPoolConfiguration") ? "cognito" : "oidc";
+ }
+
+ static String identityIssuer(JsonNode configuration) {
+ JsonNode body = configuration.has("cognitoUserPoolConfiguration")
+ ? configuration.get("cognitoUserPoolConfiguration") : configuration.get("openIdConnectConfiguration");
+ return body.path("issuer").asText();
+ }
+
+ private void validateIdentityFilters(JsonNode filters) {
+ if (filters == null || filters.isNull()) {
+ return;
+ }
+ if (!filters.isArray() || filters.size() > 10) {
+ throw validation("filters must be an array with at most 10 items.");
+ }
+ for (JsonNode filter : filters) {
+ if (!filter.isObject()) {
+ throw validation("Each identity source filter must be an object.");
+ }
+ if (filter.has("principalEntityType")) {
+ validateEntityType(requiredText(filter, "principalEntityType"), "principalEntityType");
+ }
+ }
+ }
+
+ private static boolean matchesIdentityFilters(IdentitySource source, JsonNode filters) {
+ if (filters == null || filters.isNull()) {
+ return true;
+ }
+ for (JsonNode filter : filters) {
+ if (filter.has("principalEntityType")
+ && !filter.path("principalEntityType").asText().equals(source.principalEntityType())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void validateEntityType(String value, String field) {
+ if (value == null || value.isBlank() || value.length() > 200) {
+ throw validation(field + " does not satisfy the required constraints.");
+ }
+ cedarClient.validateEntityType(value);
+ }
+
+ private static void validateStringArray(JsonNode node, String field, int min, int max) {
+ if (node == null || node.isNull()) {
+ return;
+ }
+ if (!node.isArray() || node.size() < min || node.size() > max) {
+ throw validation(field + " has an invalid number of items.");
+ }
+ node.forEach(value -> {
+ if (!value.isTextual() || value.asText().isEmpty() || value.asText().length() > 255) {
+ throw validation(field + " must contain strings between 1 and 255 characters.");
+ }
+ });
+ }
+
+ private static String identitySourceKey(String region, String storeId, String identitySourceId) {
+ return region + ":" + storeId + ":" + identitySourceId;
+ }
+
+ private IdempotencyRecord findIdempotent(String operation, JsonNode request, String region) {
+ String token = text(request, "clientToken", null);
+ if (token == null) {
+ return null;
+ }
+ validateClientToken(token);
+ String key = idempotencyKey(region, operation, token);
+ IdempotencyRecord record = idempotency.get(key).orElse(null);
+ if (record == null) {
+ return null;
+ }
+ if (record.createdAt().plus(Duration.ofHours(8)).isBefore(Instant.now())) {
+ idempotency.delete(key);
+ return null;
+ }
+ String fingerprint = requestFingerprint(request);
+ if (!record.requestFingerprint().equals(fingerprint)) {
+ throw conflict("The clientToken was already used with different request parameters.");
+ }
+ return record;
+ }
+
+ private void rememberIdempotent(String operation, JsonNode request, String region, String resourceId, String storeId) {
+ String token = text(request, "clientToken", null);
+ if (token == null) {
+ return;
+ }
+ validateClientToken(token);
+ idempotency.put(idempotencyKey(region, operation, token),
+ new IdempotencyRecord(operation, token, requestFingerprint(request), resourceId, storeId, Instant.now()));
+ }
+
+ private String requestFingerprint(JsonNode request) {
+ JsonNode copy = request.deepCopy();
+ if (copy.isObject()) {
+ ((com.fasterxml.jackson.databind.node.ObjectNode) copy).remove("clientToken");
+ }
+ try {
+ return canonical(copy);
+ } catch (JsonProcessingException e) {
+ throw validation("Request cannot be canonicalized for idempotency.");
+ }
+ }
+
+ private String canonical(JsonNode node) throws JsonProcessingException {
+ if (node.isObject()) {
+ java.util.TreeMap<String, JsonNode> sorted = new java.util.TreeMap<>();
+ node.fields().forEachRemaining(e -> sorted.put(e.getKey(), e.getValue()));
+ StringBuilder b = new StringBuilder("{");
+ boolean first = true;
+ for (var e : sorted.entrySet()) {
+ if (!first) {
+ b.append(',');
+ }
+ first = false;
+ b.append(objectMapper.writeValueAsString(e.getKey())).append(':').append(canonical(e.getValue()));
+ }
+ return b.append('}').toString();
+ }
+ if (node.isArray()) {
+ StringBuilder b = new StringBuilder("[");
+ for (int i = 0; i < node.size(); i++) {
+ if (i > 0) {
+ b.append(',');
+ }
+ b.append(canonical(node.get(i)));
+ }
+ return b.append(']').toString();
+ }
+ return objectMapper.writeValueAsString(node);
+ }
+
+ private static void validateClientToken(String token) {
+ if (token.length() < 1 || token.length() > 64 || !token.matches("[A-Za-z0-9-]*")) {
+ throw validation("clientToken does not satisfy the required constraints.");
+ }
+ }
+
+ private Encryption parseEncryption(JsonNode settings, String region) {
+ if (settings == null || settings.isNull()) {
+ return new Encryption(null, Map.of());
+ }
+ if (!settings.isObject() || settings.size() != 1) {
+ throw validation("encryptionSettings must contain exactly one union member.");
+ }
+ if (settings.has("default")) {
+ return new Encryption(null, Map.of());
+ }
+ JsonNode kms = settings.get("kmsEncryptionSettings");
+ if (kms == null || !kms.isObject()) {
+ throw validation("encryptionSettings must contain default or kmsEncryptionSettings.");
+ }
+ String key = requiredText(kms, "key");
+ String keyArn = kmsService.describeKey(key, region).getArn();
+ Map<String, String> context = stringMap(kms.get("encryptionContext"));
+ return new Encryption(keyArn, context);
+ }
+
+
+ private static String idempotencyKey(String region, String operation, String token) {
+ return region + ":" + operation + ":" + token;
+ }
+
+ private record Encryption(String keyArn, Map<String, String> context) {}
+
+ private static String compactId() {
+ return UUID.randomUUID().toString().replace("-", "").substring(0, 20);
+ }
+
+ private static String policyKey(String region, String storeId, String policyId) {
+ return region + ":" + storeId + ":" + policyId;
+ }
+
+ private static String templateKey(String region, String storeId, String templateId) {
+ return region + ":" + storeId + ":" + templateId;
+ }
+
+ private String resolvePolicyId(String region, String storeId, String identifier) {
+ String resolved = resolvePolicyIdOrNull(region, storeId, identifier);
+ if (resolved == null) {
+ throw notFound("Policy not found: " + identifier);
+ }
+ return resolved;
+ }
+
+ private String resolvePolicyIdOrNull(String region, String storeId, String identifier) {
+ if (identifier == null || identifier.isBlank() || identifier.length() > 200
+ || !STORE_ID.matcher(identifier).matches()) {
+ throw validation("policyId does not satisfy the required constraints.");
+ }
+ if (!identifier.startsWith("name/")) {
+ return policies.get(policyKey(region, storeId, identifier)).isPresent() ? identifier : null;
+ }
+ return policies.scan(k -> k.startsWith(region + ":" + storeId + ":")).stream()
+ .filter(p -> identifier.equals(p.name())).map(Policy::policyId).findFirst().orElse(null);
+ }
+
+ private String resolveTemplateId(String region, String storeId, String identifier) {
+ if (identifier == null || identifier.isBlank()) {
+ throw validation("policyTemplateId is required.");
+ }
+ if (!identifier.startsWith("name/")) {
+ return identifier;
+ }
+ return policyTemplates.scan(k -> k.startsWith(region + ":" + storeId + ":")).stream()
+ .filter(t -> identifier.equals(t.name())).map(PolicyTemplate::policyTemplateId).findFirst()
+ .orElseThrow(() -> notFound("Policy template not found: " + identifier));
+ }
+
+ private static String optionalName(JsonNode request, String field) {
+ return request.has(field) ? normalizeOptionalName(request.get(field).asText()) : null;
+ }
+
+ private static String normalizeOptionalName(String value) {
+ if (value == null || value.isEmpty()) {
+ return null;
+ }
+ if (value.length() > 150 || !value.startsWith("name/") || !value.matches("[A-Za-z0-9-/_]*")) {
+ throw validation("Policy names must be prefixed with name/ and satisfy the documented constraints.");
+ }
+ return value;
+ }
+
+ private void ensurePolicyNameAvailable(String region, String storeId, String name, String exceptId) {
+ if (name == null) {
+ return;
+ }
+ boolean duplicate = policies.scan(k -> k.startsWith(region + ":" + storeId + ":")).stream()
+ .anyMatch(p -> name.equals(p.name()) && !p.policyId().equals(exceptId));
+ if (duplicate) {
+ throw conflict("A policy with this name already exists.");
+ }
+ }
+
+ private void ensureTemplateNameAvailable(String region, String storeId, String name, String exceptId) {
+ if (name == null) {
+ return;
+ }
+ boolean duplicate = policyTemplates.scan(k -> k.startsWith(region + ":" + storeId + ":")).stream()
+ .anyMatch(t -> name.equals(t.name()) && !t.policyTemplateId().equals(exceptId));
+ if (duplicate) {
+ throw conflict("A policy template with this name already exists.");
+ }
+ }
+
+ private static EntityIdentifier entityIdentifier(JsonNode node) {
+ if (node == null || node.isNull()) {
+ return null;
+ }
+ if (!node.isObject()) {
+ throw validation("Entity identifiers must be objects.");
+ }
+ return new EntityIdentifier(requiredText(node, "entityType"), requiredText(node, "entityId"));
+ }
+
+ private String validateStaticPolicy(String statement) {
+ return cedarClient.parsePolicy(statement, false).effect();
+ }
+
+ private void validateTemplate(String statement) {
+ cedarClient.parsePolicy(statement, true);
+ }
+
+ private String templateEffect(String statement) {
+ return cedarClient.parsePolicy(statement, true).effect();
+ }
+
+ private static void validateTemplateSlots(String statement, EntityIdentifier principal, EntityIdentifier resource) {
+ boolean needsPrincipal = statement.contains("?principal");
+ boolean needsResource = statement.contains("?resource");
+ if (needsPrincipal != (principal != null) || needsResource != (resource != null)) {
+ throw validation("Template-linked policy values must exactly satisfy the template slots.");
+ }
+ }
+
+ private void ensureProtectedScopeUnchanged(String oldStatement, String newStatement, boolean template) {
+ JsonNode before = protectedScopeAst(oldStatement, template);
+ JsonNode after = protectedScopeAst(newStatement, template);
+ if (!before.equals(after)) {
+ throw validation("The policy effect, principal, and resource scope can't be changed by an update.");
+ }
+ }
+
+ public PolicyMetadata policyMetadata(Policy policy, String region) {
+ JsonNode ast;
+ EntityIdentifier linkedPrincipal = null;
+ EntityIdentifier linkedResource = null;
+ if ("STATIC".equals(policy.policyType())) {
+ ast = staticPolicyAst(policy.statement());
+ } else {
+ PolicyTemplate template = getPolicyTemplate(policy.policyStoreId(), policy.policyTemplateId(), region);
+ ast = templatePolicyAst(template.statement());
+ linkedPrincipal = policy.principal();
+ linkedResource = policy.resource();
+ }
+ return new PolicyMetadata(actionEntities(ast.path("action")),
+ scopedEntity(ast.path("principal"), linkedPrincipal),
+ scopedEntity(ast.path("resource"), linkedResource));
+ }
+
+ private JsonNode protectedScopeAst(String statement, boolean template) {
+ JsonNode ast = template ? templatePolicyAst(statement) : staticPolicyAst(statement);
+ ObjectNode protectedScope = objectMapper.createObjectNode();
+ protectedScope.set("effect", ast.path("effect").deepCopy());
+ protectedScope.set("principal", ast.path("principal").deepCopy());
+ protectedScope.set("resource", ast.path("resource").deepCopy());
+ return protectedScope;
+ }
+
+ private JsonNode staticPolicyAst(String statement) {
+ return cedarClient.parsePolicy(statement, false).ast();
+ }
+
+ private JsonNode templatePolicyAst(String statement) {
+ return cedarClient.parsePolicy(statement, true).ast();
+ }
+
+ private static List<EntityIdentifier> actionEntities(JsonNode scope) {
+ List<EntityIdentifier> result = new ArrayList<>();
+ if (scope.has("entity")) {
+ result.add(cedarJsonEntity(scope.get("entity")));
+ } else if (scope.path("entities").isArray()) {
+ scope.path("entities").forEach(entity -> result.add(cedarJsonEntity(entity)));
+ }
+ return List.copyOf(result);
+ }
+
+ private static EntityIdentifier scopedEntity(JsonNode scope, EntityIdentifier slotValue) {
+ if (scope.has("entity")) {
+ return cedarJsonEntity(scope.get("entity"));
+ }
+ if (scope.has("slot")) {
+ return slotValue;
+ }
+ return null;
+ }
+
+ private static EntityIdentifier cedarJsonEntity(JsonNode entity) {
+ if (entity == null || !entity.isObject()) {
+ return null;
+ }
+ String type = entity.path("type").asText(null);
+ String id = entity.path("id").asText(null);
+ if (type == null || id == null) {
+ return null;
+ }
+ return new EntityIdentifier(type, id);
+ }
+
+ public record PolicyMetadata(List<EntityIdentifier> actions, EntityIdentifier principal, EntityIdentifier resource) {}
+
+ private static boolean matchesPolicyFilter(Policy policy, JsonNode filter) {
+ if (filter == null || filter.isNull()) {
+ return true;
+ }
+ if (filter.has("policyType") && !filter.path("policyType").asText().equals(policy.policyType())) {
+ return false;
+ }
+ if (filter.has("policyTemplateId") && !filter.path("policyTemplateId").asText().equals(policy.policyTemplateId())) {
+ return false;
+ }
+ if (filter.has("principal") && !matchesReference(policy.principal(), filter.get("principal"))) {
+ return false;
+ }
+ return !filter.has("resource") || matchesReference(policy.resource(), filter.get("resource"));
+ }
+
+ private static boolean matchesReference(EntityIdentifier entity, JsonNode reference) {
+ if (reference == null || !reference.isObject()) {
+ return false;
+ }
+ if (reference.has("unspecified")) {
+ return reference.path("unspecified").asBoolean(false) && entity == null;
+ }
+ JsonNode id = reference.get("identifier");
+ return entity != null && id != null && id.isObject()
+ && entity.entityType().equals(id.path("entityType").asText())
+ && entity.entityId().equals(id.path("entityId").asText());
+ }
+
+ private void ensureStrictSchemaPresent(PolicyStore store) {
+ if ("STRICT".equals(store.validationMode()) && store.schema() == null) {
+ throw validation("STRICT validation requires a schema before policies or templates can be stored.");
+ }
+ }
+
+ private void validateStrictPolicy(PolicyStore store, String statement, boolean template) {
+ ensureStrictSchemaPresent(store);
+ if (!"STRICT".equals(store.validationMode())) {
+ return;
+ }
+ cedarClient.validatePolicy(store.schema(), statement, template);
+ }
+
+ private static String safeMessage(Exception e) {
+ String message = e.getMessage();
+ return message == null || message.isBlank() ? e.getClass().getSimpleName() : message;
+ }
+
+ private PolicyStore storeByArn(String arn, String region) {
+ if (arn == null) {
+ throw validation("resourceArn is required.");
+ }
+ return policyStores.scan(k -> k.startsWith(region + ":")).stream()
+ .filter(s -> arn.equals(s.arn())).findFirst()
+ .orElseThrow(() -> notFound("Resource not found: " + arn));
+ }
+
+ private void purgeExpiredAliases(String region) {
+ Instant now = Instant.now();
+ aliases.scan(k -> k.startsWith(region + ":")).stream()
+ .filter(a -> "PendingDeletion".equals(a.state()) && a.deleteAfter() != null && !now.isBefore(a.deleteAfter()))
+ .forEach(a -> aliases.delete(aliasKey(region, a.aliasName())));
+ }
+
+ private String storeArn(String region, String id) {
+ return "arn:aws:verifiedpermissions:" + region + ":" + regionResolver.getAccountId() + ":policy-store/" + id;
+ }
+
+ private String aliasArn(String region, String aliasName) {
+ return "arn:aws:verifiedpermissions:" + region + ":" + regionResolver.getAccountId() + ":" + aliasName;
+ }
+
+ private static String storeKey(String region, String id) { return region + ":" + id; }
+ private static String aliasKey(String region, String name) { return region + ":" + name; }
+
+ private void validateSchemaJson(String schema) {
+ try {
+ JsonNode node = objectMapper.readTree(schema);
+ if (node == null || !node.isObject()) {
+ throw validation("The Cedar schema must be a JSON object.");
+ }
+ } catch (io.github.hectorvent.floci.core.common.AwsException e) {
+ throw e;
+ } catch (Exception e) {
+ throw validation("The Cedar schema is invalid: " + safeMessage(e));
+ }
+ cedarClient.validateSchema(schema);
+ }
+
+ private static Map<String, String> stringMap(JsonNode node) {
+ Map<String, String> result = new LinkedHashMap<>();
+ if (node == null || node.isNull()) {
+ return result;
+ }
+ if (!node.isObject()) {
+ throw validation("tags must be an object.");
+ }
+ node.fields().forEachRemaining(e -> {
+ if (!e.getValue().isTextual()) {
+ throw validation("Tag values must be strings.");
+ }
+ result.put(e.getKey(), e.getValue().asText());
+ });
+ return result;
+ }
+
+ private static void validateTags(Map<String, String> tags) {
+ if (tags.size() > MAX_TAGS) {
+ throw validation("A resource can have at most 200 tags.");
+ }
+ for (var tag : tags.entrySet()) {
+ if (tag.getKey() == null || tag.getKey().isEmpty() || tag.getKey().length() > 128 || tag.getValue().length() > 256) {
+ throw validation("A tag doesn't satisfy the required length constraints.");
+ }
+ }
+ }
+
+ private static void validateMode(String mode) {
+ if (!"OFF".equals(mode) && !"STRICT".equals(mode)) {
+ throw validation("mode must be OFF or STRICT.");
+ }
+ }
+ private static void validateDeletionProtection(String value) {
+ if (!"ENABLED".equals(value) && !"DISABLED".equals(value)) {
+ throw validation("deletionProtection must be ENABLED or DISABLED.");
+ }
+ }
+ private static void validatePolicyStatement(String value) {
+ if (value == null || value.isEmpty() || value.length() > MAX_POLICY_STATEMENT_LENGTH) {
+ throw validation("statement must contain between 1 and 10000 characters.");
+ }
+ }
+ private static void validateDescription(String value) {
+ if (value != null && value.length() > 150) {
+ throw validation("description must be 150 characters or fewer.");
+ }
+ }
+ private static void validateAliasName(String value) {
+ if (value == null || value.length() > 150 || !ALIAS_NAME.matcher(value).matches()) {
+ throw validation("aliasName does not satisfy the required constraints.");
+ }
+ }
+ static String requiredText(JsonNode node, String name) {
+ JsonNode value = node == null ? null : node.get(name);
+ if (value == null || !value.isTextual() || value.asText().isEmpty()) {
+ throw validation(name + " is required.");
+ }
+ return value.asText();
+ }
+ static JsonNode requiredObject(JsonNode node, String name) {
+ JsonNode value = node == null ? null : node.get(name);
+ if (value == null || !value.isObject()) {
+ throw validation(name + " is required.");
+ }
+ return value;
+ }
+ static String text(JsonNode node, String name, String defaultValue) {
+ JsonNode value = node == null ? null : node.get(name);
+ return value == null || value.isNull() ? defaultValue : value.asText();
+ }
+ static Integer optionalInt(JsonNode node, String name) {
+ JsonNode value = node == null ? null : node.get(name);
+ return value == null || value.isNull() ? null : value.asInt();
+ }
+ static AwsException validation(String message) { return new AwsException("ValidationException", message, 400); }
+ static AwsException notFound(String message) { return new AwsException("ResourceNotFoundException", message, 400); }
+ static AwsException conflict(String message) { return new AwsException("ConflictException", message, 400); }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsTokenService.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsTokenService.java
new file mode 100644
index 0000000000..2a3b3eb2fa
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsTokenService.java
@@ -0,0 +1,307 @@
+package io.github.hectorvent.floci.services.verifiedpermissions;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.services.verifiedpermissions.model.EntityIdentifier;
+import io.github.hectorvent.floci.services.verifiedpermissions.model.IdentitySource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.List;
+
+@ApplicationScoped
+public class VerifiedPermissionsTokenService {
+ private final VerifiedPermissionsService service;
+ private final CedarAuthorizationEvaluator evaluator;
+ private final VerifiedPermissionsOidcSignatureVerifier signatureVerifier;
+ private final ObjectMapper objectMapper;
+
+ @Inject
+ public VerifiedPermissionsTokenService(VerifiedPermissionsService service,
+ CedarAuthorizationEvaluator evaluator,
+ VerifiedPermissionsOidcSignatureVerifier signatureVerifier,
+ ObjectMapper objectMapper) {
+ this.service = service;
+ this.evaluator = evaluator;
+ this.signatureVerifier = signatureVerifier;
+ this.objectMapper = objectMapper;
+ }
+
+ public PreparedTokenRequest prepare(JsonNode request, String region) {
+ String store = VerifiedPermissionsService.requiredText(request, "policyStoreId");
+ String identityToken = VerifiedPermissionsService.text(request, "identityToken", null);
+ String accessToken = VerifiedPermissionsService.text(request, "accessToken", null);
+ if ((identityToken == null || identityToken.isBlank()) && (accessToken == null || accessToken.isBlank())) {
+ throw VerifiedPermissionsService.validation("You must specify identityToken, accessToken, or both.");
+ }
+
+ TokenInfo identity = identityToken == null ? null : validateToken(store, identityToken, TokenKind.IDENTITY, region);
+ TokenInfo access = accessToken == null ? null : validateToken(store, accessToken, TokenKind.ACCESS, region);
+ TokenInfo principalToken = identity != null ? identity : access;
+ if (identity != null && access != null
+ && (!identity.principal().equals(access.principal()) || !identity.source().identitySourceId().equals(access.source().identitySourceId()))) {
+ throw VerifiedPermissionsService.validation("identityToken and accessToken must identify the same principal and identity source.");
+ }
+
+ ObjectNode prepared = request.deepCopy();
+ prepared.remove(List.of("identityToken", "accessToken"));
+ ObjectNode principal = prepared.putObject("principal");
+ principal.put("entityType", principalToken.principal().entityType());
+ principal.put("entityId", principalToken.principal().entityId());
+ JsonNode identityClaims = identity == null ? null : identity.claims();
+ List<EntityIdentifier> parents = mergeParents(identity, access);
+ prepared.set("entities", evaluator.appendTokenPrincipal(prepared.get("entities"), principalToken.principal(), identityClaims, parents));
+ if (access != null) {
+ prepared.set("context", mergeAccessContext(prepared.get("context"), access.claims()));
+ }
+ return new PreparedTokenRequest(prepared, principalToken.principal());
+ }
+
+ private TokenInfo validateToken(String store, String token, TokenKind requestedKind, String region) {
+ JsonNode claims = decodeClaims(token);
+ String issuer = claims.path("iss").asText(null);
+ if (issuer == null || issuer.isBlank()) {
+ throw VerifiedPermissionsService.validation("Token has no issuer claim.");
+ }
+ IdentitySource source = service.identitySourcesForStore(store, region).stream()
+ .filter(candidate -> issuer.equals(VerifiedPermissionsService.identityIssuer(candidate.configuration())))
+ .findFirst().orElseThrow(() -> VerifiedPermissionsService.validation("No identity source matches the token issuer."));
+ try {
+ signatureVerifier.verify(token, issuer);
+ } catch (VerifiedPermissionsOidcSignatureVerifier.VerificationException e) {
+ throw VerifiedPermissionsService.validation("Token signature validation failed: " + e.getMessage());
+ }
+ validateTimes(claims);
+ JsonNode configuration = source.configuration();
+ if (configuration.has("cognitoUserPoolConfiguration")) {
+ return validateCognito(source, claims, requestedKind);
+ }
+ return validateOidc(source, claims, requestedKind);
+ }
+
+ private TokenInfo validateCognito(IdentitySource source, JsonNode claims, TokenKind requestedKind) {
+ String expectedUse = requestedKind == TokenKind.IDENTITY ? "id" : "access";
+ if (!expectedUse.equals(claims.path("token_use").asText())) {
+ throw VerifiedPermissionsService.validation("The submitted token has the wrong token_use claim.");
+ }
+ JsonNode config = source.configuration().get("cognitoUserPoolConfiguration");
+ JsonNode clients = config.path("clientIds");
+ if (clients.isArray() && !clients.isEmpty()) {
+ String actual = requestedKind == TokenKind.IDENTITY ? claims.path("aud").asText(null) : claims.path("client_id").asText(null);
+ if (actual == null || !arrayContains(clients, actual)) {
+ throw VerifiedPermissionsService.validation("The token client application isn't allowed by this identity source.");
+ }
+ }
+ String sub = requiredClaim(claims, "sub");
+ String poolId = config.path("userPoolArn").asText().substring(config.path("userPoolArn").asText().lastIndexOf('/') + 1);
+ EntityIdentifier principal = new EntityIdentifier(source.principalEntityType(), poolId + "|" + sub);
+ return new TokenInfo(source, claims, principal, groupParents(source, claims, poolId, "cognito:groups"));
+ }
+
+ private TokenInfo validateOidc(IdentitySource source, JsonNode claims, TokenKind requestedKind) {
+ JsonNode config = source.configuration().get("openIdConnectConfiguration");
+ JsonNode selection = config.path("tokenSelection");
+ boolean accessConfigured = selection.has("accessTokenOnly");
+ if ((requestedKind == TokenKind.ACCESS) != accessConfigured) {
+ throw VerifiedPermissionsService.validation("The token type isn't enabled for this OIDC identity source.");
+ }
+ JsonNode tokenConfig = accessConfigured ? selection.get("accessTokenOnly") : selection.get("identityTokenOnly");
+ JsonNode accepted = accessConfigured ? tokenConfig.path("audiences") : tokenConfig.path("clientIds");
+ if (accepted.isArray() && !accepted.isEmpty() && !audienceMatches(claims.get("aud"), accepted)) {
+ throw VerifiedPermissionsService.validation("The token audience isn't allowed by this identity source.");
+ }
+ String principalClaim = tokenConfig.path("principalIdClaim").asText("sub");
+ String principalId = requiredClaim(claims, principalClaim);
+ String prefix = config.path("entityIdPrefix").asText("");
+ String composed = prefix.isEmpty() ? principalId : prefix + "|" + principalId;
+ EntityIdentifier principal = new EntityIdentifier(source.principalEntityType(), composed);
+ String groupClaim = config.path("groupConfiguration").path("groupClaim").asText(null);
+ return new TokenInfo(source, claims, principal, groupClaim == null ? List.of() : groupParents(source, claims, prefix, groupClaim));
+ }
+
+ private List<EntityIdentifier> groupParents(IdentitySource source, JsonNode claims, String prefix, String claimName) {
+ JsonNode groupConfiguration = source.configuration().has("cognitoUserPoolConfiguration")
+ ? source.configuration().path("cognitoUserPoolConfiguration").path("groupConfiguration")
+ : source.configuration().path("openIdConnectConfiguration").path("groupConfiguration");
+ String groupType = groupConfiguration.path("groupEntityType").asText(null);
+ if (groupType == null) {
+ return List.of();
+ }
+ JsonNode groups = claims.get(claimName);
+ if (groups == null || groups.isNull()) {
+ return List.of();
+ }
+ List<EntityIdentifier> result = new ArrayList<>();
+ if (groups.isArray()) {
+ groups.forEach(group -> result.add(new EntityIdentifier(groupType, qualify(prefix, group.asText()))));
+ } else if (groups.isTextual()) {
+ result.add(new EntityIdentifier(groupType, qualify(prefix, groups.asText())));
+ }
+ return result;
+ }
+
+ private static String qualify(String prefix, String value) {
+ return prefix == null || prefix.isEmpty() ? value : prefix + "|" + value;
+ }
+
+ private List<EntityIdentifier> mergeParents(TokenInfo identity, TokenInfo access) {
+ java.util.LinkedHashSet<EntityIdentifier> parents = new java.util.LinkedHashSet<>();
+ if (identity != null) {
+ parents.addAll(identity.parents());
+ }
+ if (access != null) {
+ parents.addAll(access.parents());
+ }
+ return new ArrayList<>(parents);
+ }
+
+ private ObjectNode mergeAccessContext(JsonNode existing, JsonNode claims) {
+ ObjectNode root;
+ try {
+ if (existing == null || existing.isNull()) {
+ root = objectMapper.createObjectNode();
+ } else if (existing.has("cedarJson")) {
+ JsonNode parsed = objectMapper.readTree(existing.path("cedarJson").asText());
+ if (!parsed.isObject()) {
+ throw VerifiedPermissionsService.validation("context.cedarJson must encode an object.");
+ }
+ root = (ObjectNode) parsed.deepCopy();
+ } else if (existing.has("contextMap")) {
+ root = contextMapToRaw(existing.get("contextMap"));
+ } else {
+ throw VerifiedPermissionsService.validation("context must contain cedarJson or contextMap.");
+ }
+ } catch (java.io.IOException e) {
+ throw VerifiedPermissionsService.validation("context.cedarJson isn't valid JSON.");
+ }
+ ObjectNode token = root.putObject("token");
+ claims.fields().forEachRemaining(entry -> {
+ if (!"cognito:groups".equals(entry.getKey()) && claimSupported(entry.getValue())) {
+ token.set(entry.getKey(), entry.getValue().deepCopy());
+ }
+ });
+ ObjectNode union = objectMapper.createObjectNode();
+ union.put("cedarJson", root.toString());
+ return union;
+ }
+
+ private ObjectNode contextMapToRaw(JsonNode map) {
+ ObjectNode result = objectMapper.createObjectNode();
+ map.fields().forEachRemaining(entry -> result.set(entry.getKey(), rawAttribute(entry.getValue())));
+ return result;
+ }
+
+ private JsonNode rawAttribute(JsonNode union) {
+ if (!union.isObject() || union.size() != 1) {
+ throw VerifiedPermissionsService.validation("Context attributes must contain one union member.");
+ }
+ var entry = union.fields().next();
+ return switch (entry.getKey()) {
+ case "boolean", "long", "string" -> entry.getValue().deepCopy();
+ case "set" -> {
+ var array = objectMapper.createArrayNode();
+ entry.getValue().forEach(v -> array.add(rawAttribute(v)));
+ yield array;
+ }
+ case "record" -> contextMapToRaw(entry.getValue());
+ default -> throw VerifiedPermissionsService.validation("Token context merge doesn't support attribute type " + entry.getKey() + ".");
+ };
+ }
+
+ private JsonNode decodeClaims(String token) {
+ String[] parts = token == null ? new String[0] : token.split("\\.", -1);
+ if (parts.length != 3) {
+ throw VerifiedPermissionsService.validation("Token isn't a well-formed JWT.");
+ }
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(pad(parts[1]));
+ JsonNode claims = objectMapper.readTree(new String(decoded, StandardCharsets.UTF_8));
+ if (claims == null || !claims.isObject()) {
+ throw VerifiedPermissionsService.validation("Token claims aren't a JSON object.");
+ }
+ return claims;
+ } catch (IllegalArgumentException | java.io.IOException e) {
+ throw VerifiedPermissionsService.validation("Token payload isn't valid base64url JSON.");
+ }
+ }
+
+ private static void validateTimes(JsonNode claims) {
+ long now = Instant.now().getEpochSecond();
+ if (!claims.has("exp") || !claims.get("exp").canConvertToLong() || claims.get("exp").asLong() <= now) {
+ throw VerifiedPermissionsService.validation("Token is expired or has no valid exp claim.");
+ }
+ if (claims.has("nbf") && claims.get("nbf").canConvertToLong() && claims.get("nbf").asLong() > now) {
+ throw VerifiedPermissionsService.validation("Token isn't valid yet.");
+ }
+ }
+
+ private static String requiredClaim(JsonNode claims, String name) {
+ JsonNode value = claims.get(name);
+ if (value == null || !value.isValueNode() || value.asText().isEmpty()) {
+ throw VerifiedPermissionsService.validation("Token is missing required principal claim " + name + ".");
+ }
+ return value.asText();
+ }
+
+ private static boolean arrayContains(JsonNode array, String value) {
+ for (JsonNode item : array) {
+ if (value.equals(item.asText())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static boolean audienceMatches(JsonNode actual, JsonNode accepted) {
+ if (actual == null) {
+ return false;
+ }
+ if (actual.isTextual()) {
+ return arrayContains(accepted, actual.asText());
+ }
+ if (actual.isArray()) {
+ for (JsonNode item : actual) {
+ if (arrayContains(accepted, item.asText())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static boolean claimSupported(JsonNode value) {
+ if (value == null || value.isNull()) {
+ return false;
+ }
+ if (value.isTextual() || value.isBoolean() || value.isIntegralNumber()) {
+ return true;
+ }
+ if (value.isArray()) {
+ for (JsonNode item : value) {
+ if (!(item.isTextual() || item.isBoolean() || item.isIntegralNumber())) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private static String pad(String value) {
+ return switch (value.length() % 4) {
+ case 2 -> value + "==";
+ case 3 -> value + "=";
+ default -> value;
+ };
+ }
+
+ private enum TokenKind { IDENTITY, ACCESS }
+ private record TokenInfo(IdentitySource source, JsonNode claims, EntityIdentifier principal,
+ List<EntityIdentifier> parents) {}
+ public record PreparedTokenRequest(ObjectNode request, EntityIdentifier principal) {}
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/EntityIdentifier.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/EntityIdentifier.java
new file mode 100644
index 0000000000..81d5e2c1f4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/EntityIdentifier.java
@@ -0,0 +1,6 @@
+package io.github.hectorvent.floci.services.verifiedpermissions.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+public record EntityIdentifier(String entityType, String entityId) {}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/IdempotencyRecord.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/IdempotencyRecord.java
new file mode 100644
index 0000000000..ecfb237f47
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/IdempotencyRecord.java
@@ -0,0 +1,14 @@
+package io.github.hectorvent.floci.services.verifiedpermissions.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+public record IdempotencyRecord(
+ String operation,
+ String token,
+ String requestFingerprint,
+ String resourceId,
+ String policyStoreId,
+ Instant createdAt) {}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/IdentitySource.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/IdentitySource.java
new file mode 100644
index 0000000000..e67c5e80e6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/IdentitySource.java
@@ -0,0 +1,21 @@
+package io.github.hectorvent.floci.services.verifiedpermissions.model;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+public record IdentitySource(
+ String policyStoreId,
+ String identitySourceId,
+ String principalEntityType,
+ JsonNode configuration,
+ Instant createdDate,
+ Instant lastUpdatedDate) {
+
+ public IdentitySource updated(String nextPrincipalEntityType, JsonNode nextConfiguration, Instant updatedAt) {
+ return new IdentitySource(policyStoreId, identitySourceId, nextPrincipalEntityType,
+ nextConfiguration, createdDate, updatedAt);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/Policy.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/Policy.java
new file mode 100644
index 0000000000..2a3da7910c
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/Policy.java
@@ -0,0 +1,25 @@
+package io.github.hectorvent.floci.services.verifiedpermissions.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+public record Policy(
+ String policyStoreId,
+ String policyId,
+ String name,
+ String policyType,
+ String statement,
+ String description,
+ String policyTemplateId,
+ EntityIdentifier principal,
+ EntityIdentifier resource,
+ String effect,
+ Instant createdDate,
+ Instant lastUpdatedDate) {
+ public Policy updated(String nextName, String nextStatement, String nextDescription, Instant updatedAt) {
+ return new Policy(policyStoreId, policyId, nextName, policyType, nextStatement, nextDescription,
+ policyTemplateId, principal, resource, effect, createdDate, updatedAt);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyStore.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyStore.java
new file mode 100644
index 0000000000..ed345df98b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyStore.java
@@ -0,0 +1,44 @@
+package io.github.hectorvent.floci.services.verifiedpermissions.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+@RegisterForReflection
+public record PolicyStore(
+ String policyStoreId,
+ String arn,
+ String validationMode,
+ String deletionProtection,
+ String description,
+ String encryptionKeyArn,
+ Map<String, String> encryptionContext,
+ Map<String, String> tags,
+ String schema,
+ Instant schemaCreatedDate,
+ Instant schemaLastUpdatedDate,
+ Instant createdDate,
+ Instant lastUpdatedDate) {
+
+ public PolicyStore {
+ encryptionContext = encryptionContext == null ? new LinkedHashMap<>() : new LinkedHashMap<>(encryptionContext);
+ tags = tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags);
+ }
+
+ public PolicyStore withSchema(String nextSchema, Instant created, Instant updated) {
+ return new PolicyStore(policyStoreId, arn, validationMode, deletionProtection, description,
+ encryptionKeyArn, encryptionContext, tags, nextSchema, created, updated, createdDate, updated);
+ }
+
+ public PolicyStore withSettings(String mode, String deletion, String nextDescription, Instant updated) {
+ return new PolicyStore(policyStoreId, arn, mode, deletion, nextDescription, encryptionKeyArn, encryptionContext, tags,
+ schema, schemaCreatedDate, schemaLastUpdatedDate, createdDate, updated);
+ }
+
+ public PolicyStore withTags(Map<String, String> nextTags, Instant updated) {
+ return new PolicyStore(policyStoreId, arn, validationMode, deletionProtection, description,
+ encryptionKeyArn, encryptionContext, nextTags, schema, schemaCreatedDate, schemaLastUpdatedDate, createdDate, updated);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyStoreAlias.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyStoreAlias.java
new file mode 100644
index 0000000000..4d774905c0
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyStoreAlias.java
@@ -0,0 +1,19 @@
+package io.github.hectorvent.floci.services.verifiedpermissions.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+public record PolicyStoreAlias(
+ String aliasName,
+ String aliasArn,
+ String policyStoreId,
+ String state,
+ Instant createdAt,
+ Instant deleteAfter) {
+
+ public PolicyStoreAlias pendingDeletion(Instant deleteAfter) {
+ return new PolicyStoreAlias(aliasName, aliasArn, policyStoreId, "PendingDeletion", createdAt, deleteAfter);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyTemplate.java b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyTemplate.java
new file mode 100644
index 0000000000..8643d33d92
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/model/PolicyTemplate.java
@@ -0,0 +1,20 @@
+package io.github.hectorvent.floci.services.verifiedpermissions.model;
+
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+import java.time.Instant;
+
+@RegisterForReflection
+public record PolicyTemplate(
+ String policyStoreId,
+ String policyTemplateId,
+ String name,
+ String statement,
+ String description,
+ Instant createdDate,
+ Instant lastUpdatedDate) {
+ public PolicyTemplate updated(String nextName, String nextStatement, String nextDescription, Instant updatedAt) {
+ return new PolicyTemplate(policyStoreId, policyTemplateId, nextName, nextStatement, nextDescription,
+ createdDate, updatedAt);
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index a48ffec129..fc79e681c1 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -708,6 +708,10 @@ floci:
enabled: true
servicequotas:
enabled: true
+ verifiedpermissions:
+ enabled: true
+ # cedar-url: http://floci-cedar:8180 # set to skip sidecar container management
+ cedar-image: "floci/floci:latest-cedar"
ram:
enabled: true
codegurureviewer:
diff --git a/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarManagerTest.java
new file mode 100644
index 0000000000..93fd040ca0
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/CedarSidecarManagerTest.java
@@ -0,0 +1,74 @@
+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 org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Field;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+class CedarSidecarManagerTest {
+
+ @Test
+ void configuredUrlSkipsContainerManagement() {
+ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ EmulatorConfig.VerifiedPermissionsServiceConfig verifiedPermissions =
+ mock(EmulatorConfig.VerifiedPermissionsServiceConfig.class);
+
+ when(config.services()).thenReturn(services);
+ when(services.verifiedpermissions()).thenReturn(verifiedPermissions);
+ when(verifiedPermissions.cedarUrl()).thenReturn(Optional.of("http://cedar.internal:8180/"));
+
+ CedarSidecarManager manager = new CedarSidecarManager(containerBuilder, lifecycleManager, config);
+
+ assertEquals("http://cedar.internal:8180", manager.ensureReady());
+ verifyNoInteractions(containerBuilder, lifecycleManager);
+ }
+ @Test
+ void staleManagedEndpointIsDiscarded() throws Exception {
+ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
+ EmulatorConfig config = mock(EmulatorConfig.class);
+ EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
+ EmulatorConfig.VerifiedPermissionsServiceConfig verifiedPermissions =
+ mock(EmulatorConfig.VerifiedPermissionsServiceConfig.class);
+
+ when(config.services()).thenReturn(services);
+ when(services.verifiedpermissions()).thenReturn(verifiedPermissions);
+ when(verifiedPermissions.cedarUrl()).thenReturn(Optional.empty());
+
+ CedarSidecarManager manager = new CedarSidecarManager(containerBuilder, lifecycleManager, config);
+ setField(manager, "resolvedUrl", "http://127.0.0.1:1");
+ setField(manager, "containerId", "stale-cedar");
+
+ assertFalse(manager.isAvailable());
+ verify(lifecycleManager).stopAndRemove("stale-cedar", null);
+ assertNull(getField(manager, "resolvedUrl"));
+ assertNull(getField(manager, "containerId"));
+ }
+
+ private static void setField(Object target, String name, Object value) throws Exception {
+ Field field = target.getClass().getDeclaredField(name);
+ field.setAccessible(true);
+ field.set(target, value);
+ }
+
+ private static Object getField(Object target, String name) throws Exception {
+ Field field = target.getClass().getDeclaredField(name);
+ field.setAccessible(true);
+ return field.get(target);
+ }
+
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsIntegrationTest.java
new file mode 100644
index 0000000000..5dd9600a74
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsIntegrationTest.java
@@ -0,0 +1,375 @@
+package io.github.hectorvent.floci.services.verifiedpermissions;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.cedar.CedarSidecarServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasEntry;
+import static org.hamcrest.Matchers.matchesPattern;
+
+@QuarkusTest
+class VerifiedPermissionsIntegrationTest {
+ private static HttpServer cedarServer;
+ private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
+ private static final String AUTH = "AWS4-HMAC-SHA256 Credential=111122223333/20260101/us-east-1/verifiedpermissions/aws4_request";
+
+ @BeforeAll
+ static void configureRestAssured() throws Exception {
+ cedarServer = CedarSidecarServer.start(18180);
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @AfterAll
+ static void stopCedarSidecar() {
+ cedarServer.stop(0);
+ }
+
+ @Test
+ void policyStoreSchemaTagsAndAliases_followAwsJson10Contract() {
+ String policyStoreId = createStore("OFF", "DISABLED");
+
+ givenAws("GetPolicyStore", "{\"policyStoreId\":\"" + policyStoreId + "\",\"tags\":true}")
+ .then().statusCode(200)
+ .body("policyStoreId", equalTo(policyStoreId))
+ .body("arn", matchesPattern("arn:aws:verifiedpermissions:us-east-1:111122223333:policy-store/PS[A-Za-z0-9]+"))
+ .body("validationSettings.mode", equalTo("OFF"))
+ .body("cedarVersion", equalTo("CEDAR_4"))
+ .body("deletionProtection", equalTo("DISABLED"));
+
+ String schema = "{\\\"Demo\\\":{\\\"entityTypes\\\":{},\\\"actions\\\":{}}}";
+ givenAws("PutSchema", "{\"policyStoreId\":\"" + policyStoreId + "\",\"definition\":{\"cedarJson\":\"" + schema + "\"}}")
+ .then().statusCode(200).body("namespaces[0]", equalTo("Demo"));
+ givenAws("GetSchema", "{\"policyStoreId\":\"" + policyStoreId + "\"}")
+ .then().statusCode(200).body("policyStoreId", equalTo(policyStoreId));
+
+ String arn = givenAws("GetPolicyStore", "{\"policyStoreId\":\"" + policyStoreId + "\"}")
+ .then().statusCode(200).extract().path("arn");
+ givenAws("TagResource", "{\"resourceArn\":\"" + arn + "\",\"tags\":{\"project\":\"demo\"}}")
+ .then().statusCode(200);
+ givenAws("ListTagsForResource", "{\"resourceArn\":\"" + arn + "\"}")
+ .then().statusCode(200).body("tags", hasEntry("project", "demo"));
+
+ String alias = "policy-store-alias/demo-" + policyStoreId.substring(policyStoreId.length() - 6);
+ givenAws("CreatePolicyStoreAlias", "{\"aliasName\":\"" + alias + "\",\"policyStoreId\":\"" + policyStoreId + "\"}")
+ .then().statusCode(200).body("aliasName", equalTo(alias));
+ givenAws("GetPolicyStore", "{\"policyStoreId\":\"" + alias + "\"}")
+ .then().statusCode(200).body("policyStoreId", equalTo(policyStoreId));
+
+ givenAws("DeletePolicyStoreAlias", "{\"aliasName\":\"" + alias + "\"}")
+ .then().statusCode(200);
+ givenAws("GetPolicyStoreAlias", "{\"aliasName\":\"" + alias + "\"}")
+ .then().statusCode(200).body("state", equalTo("PendingDeletion"));
+ givenAws("GetPolicyStore", "{\"policyStoreId\":\"" + alias + "\"}")
+ .then().statusCode(400).body("__type", containsString("ResourceNotFoundException"));
+
+ givenAws("DeletePolicyStoreAlias", "{\"aliasName\":\"" + alias + "\",\"deletionMode\":\"HardDelete\"}")
+ .then().statusCode(200);
+ givenAws("GetPolicyStoreAlias", "{\"aliasName\":\"" + alias + "\"}")
+ .then().statusCode(400).body("__type", containsString("ResourceNotFoundException"));
+ }
+
+ @Test
+ void deletionProtectionAndDeleteAliasRestrictions_matchAwsBehavior() {
+ String protectedId = createStore("OFF", "ENABLED");
+ givenAws("DeletePolicyStore", "{\"policyStoreId\":\"" + protectedId + "\"}")
+ .then().statusCode(400).body("__type", containsString("InvalidStateException"));
+
+ String ordinary = createStore("OFF", "DISABLED");
+ String alias = "policy-store-alias/delete-check-" + ordinary.substring(ordinary.length() - 6);
+ givenAws("CreatePolicyStoreAlias", "{\"aliasName\":\"" + alias + "\",\"policyStoreId\":\"" + ordinary + "\"}")
+ .then().statusCode(200);
+ givenAws("DeletePolicyStore", "{\"policyStoreId\":\"" + alias + "\"}")
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ givenAws("DeletePolicyStore", "{\"policyStoreId\":\"" + ordinary + "\"}")
+ .then().statusCode(200);
+ givenAws("GetPolicyStoreAlias", "{\"aliasName\":\"" + alias + "\"}")
+ .then().statusCode(400).body("__type", containsString("ResourceNotFoundException"));
+ }
+
+ @Test
+ void protocolRejectsWrongValidationSettingsInvalidSchemasAndUnknownActions() {
+ givenAws("CreatePolicyStore", "{\"validationSettings\":{\"mode\":\"INVALID\"}}")
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+
+ String store = createStore("OFF", "DISABLED");
+ String malformedCedarSchema = "{\"Demo\":{\"entityTypes\":[]}}";
+ givenAws("PutSchema", objectJson(Map.of(
+ "policyStoreId", store,
+ "definition", Map.of("cedarJson", malformedCedarSchema))))
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+
+ givenAws("DoesNotExist", "{}")
+ .then().statusCode(400).body("__type", containsString("UnknownOperationException"));
+ }
+
+ private static String createStore(String validationMode, String deletionProtection) {
+ return givenAws("CreatePolicyStore", "{\"validationSettings\":{\"mode\":\"" + validationMode
+ + "\"},\"deletionProtection\":\"" + deletionProtection + "\"}")
+ .then().statusCode(200).extract().path("policyStoreId");
+ }
+
+ private static io.restassured.response.Response givenAws(String action, String body) {
+ return given().contentType(CONTENT_TYPE).header("Authorization", AUTH)
+ .header("X-Amz-Target", "VerifiedPermissions." + action).body(body)
+ .when().post("/");
+ }
+ @Test
+ void staticAndTemplateLinkedPolicies_supportLifecycleNamesAndFilters() {
+ String store = createStore("OFF", "DISABLED");
+ String staticStatement = "permit(principal, action == Demo::Action::\"read\", resource);";
+ String createStatic = objectJson(Map.of(
+ "policyStoreId", store,
+ "name", "name/read-all",
+ "definition", Map.of("static", Map.of("statement", staticStatement, "description", "reader"))));
+ String policyId = givenAws("CreatePolicy", createStatic).then().statusCode(200)
+ .body("policyType", equalTo("STATIC")).body("effect", equalTo("Permit"))
+ .body("actions[0].actionType", equalTo("Demo::Action"))
+ .body("actions[0].actionId", equalTo("read"))
+ .extract().path("policyId");
+ givenAws("GetPolicy", objectJson(Map.of("policyStoreId", store, "policyId", "name/read-all")))
+ .then().statusCode(200).body("policyId", equalTo(policyId))
+ .body("actions[0].actionId", equalTo("read"))
+ .body("definition.static.statement", equalTo(staticStatement));
+
+ String templateStatement = "permit(principal == ?principal, action == Demo::Action::\"write\", resource == ?resource);";
+ String templateId = givenAws("CreatePolicyTemplate", objectJson(Map.of(
+ "policyStoreId", store, "name", "name/writer", "statement", templateStatement)))
+ .then().statusCode(200).extract().path("policyTemplateId");
+ String linkedBody = objectJson(Map.of(
+ "policyStoreId", store,
+ "definition", Map.of("templateLinked", Map.of(
+ "policyTemplateId", templateId,
+ "principal", Map.of("entityType", "Demo::User", "entityId", "alice"),
+ "resource", Map.of("entityType", "Demo::Document", "entityId", "doc-1")))));
+ String linkedId = givenAws("CreatePolicy", linkedBody).then().statusCode(200)
+ .body("policyType", equalTo("TEMPLATE_LINKED")).extract().path("policyId");
+
+ givenAws("ListPolicies", objectJson(Map.of("policyStoreId", store,
+ "filter", Map.of("policyType", "TEMPLATE_LINKED"))))
+ .then().statusCode(200).body("policies.size()", equalTo(1))
+ .body("policies[0].policyId", equalTo(linkedId));
+
+ givenAws("DeletePolicyTemplate", objectJson(Map.of("policyStoreId", store, "policyTemplateId", templateId)))
+ .then().statusCode(200);
+ givenAws("GetPolicy", objectJson(Map.of("policyStoreId", store, "policyId", linkedId)))
+ .then().statusCode(400).body("__type", containsString("ResourceNotFoundException"));
+ }
+
+ @Test
+ void strictStoreRejectsPoliciesUntilSchemaExists_andUpdateCannotChangeEffect() {
+ String store = createStore("STRICT", "DISABLED");
+ String permit = "permit(principal, action, resource);";
+ givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store,
+ "definition", Map.of("static", Map.of("statement", permit)))))
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+
+ String strictSchema = "{\"Demo\":{\"entityTypes\":{\"User\":{\"shape\":{\"type\":\"Record\",\"attributes\":{}}},\"Document\":{\"shape\":{\"type\":\"Record\",\"attributes\":{}}}},\"actions\":{\"read\":{\"appliesTo\":{\"principalTypes\":[\"User\"],\"resourceTypes\":[\"Document\"]}}}}}";
+ givenAws("PutSchema", objectJson(Map.of("policyStoreId", store,
+ "definition", Map.of("cedarJson", strictSchema))))
+ .then().statusCode(200);
+ String scopedPermit = "permit(principal, action == Demo::Action::\"read\", resource);";
+ String id = givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store,
+ "definition", Map.of("static", Map.of("statement", scopedPermit)))))
+ .then().statusCode(200).extract().path("policyId");
+ givenAws("UpdatePolicy", objectJson(Map.of("policyStoreId", store, "policyId", id,
+ "definition", Map.of("static", Map.of("statement", "forbid(principal, action == Demo::Action::\"read\", resource);")))))
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void isAuthorized_evaluatesCedarJsonEntitiesAndDenyOverridesPermit() {
+ String store = createStore("OFF", "DISABLED");
+ String permit = "permit(principal, action == Demo::Action::\"read\", resource) when { principal.tenant == resource.tenant };";
+ String forbid = "forbid(principal, action, resource) when { resource.blocked };";
+ givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store, "definition", Map.of("static", Map.of("statement", permit)))))
+ .then().statusCode(200);
+ givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store, "definition", Map.of("static", Map.of("statement", forbid)))))
+ .then().statusCode(200);
+
+ String entities = "[{\"uid\":{\"type\":\"Demo::User\",\"id\":\"alice\"},\"attrs\":{\"tenant\":\"t1\"},\"parents\":[]},{\"uid\":{\"type\":\"Demo::Document\",\"id\":\"doc1\"},\"attrs\":{\"tenant\":\"t1\",\"blocked\":false},\"parents\":[]}]";
+ Map<String,Object> auth = Map.of(
+ "policyStoreId", store,
+ "principal", Map.of("entityType", "Demo::User", "entityId", "alice"),
+ "action", Map.of("actionType", "Demo::Action", "actionId", "read"),
+ "resource", Map.of("entityType", "Demo::Document", "entityId", "doc1"),
+ "entities", Map.of("cedarJson", entities));
+ givenAws("IsAuthorized", objectJson(auth)).then().statusCode(200)
+ .body("decision", equalTo("ALLOW"))
+ .body("determiningPolicies.size()", equalTo(1));
+
+ String blocked = entities.replace("\"blocked\":false", "\"blocked\":true");
+ java.util.LinkedHashMap<String,Object> blockedAuth = new java.util.LinkedHashMap<>(auth);
+ blockedAuth.put("entities", Map.of("cedarJson", blocked));
+ givenAws("IsAuthorized", objectJson(blockedAuth)).then().statusCode(200)
+ .body("decision", equalTo("DENY"))
+ .body("determiningPolicies.size()", equalTo(1));
+ }
+
+ @Test
+ void isAuthorized_supportsEntityListHierarchyAndBatchValidation() {
+ String store = createStore("OFF", "DISABLED");
+ String permit = "permit(principal in Demo::Group::\"admins\", action == Demo::Action::\"write\", resource);";
+ givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store, "definition", Map.of("static", Map.of("statement", permit)))))
+ .then().statusCode(200);
+ Map<String,Object> principal = Map.of("entityType", "Demo::User", "entityId", "alice");
+ Map<String,Object> resource = Map.of("entityType", "Demo::Document", "entityId", "doc1");
+ Map<String,Object> action = Map.of("actionType", "Demo::Action", "actionId", "write");
+ Map<String,Object> entity = Map.of(
+ "identifier", principal,
+ "parents", java.util.List.of(Map.of("entityType", "Demo::Group", "entityId", "admins")),
+ "attributes", Map.of("department", Map.of("string", "platform")));
+ Map<String,Object> auth = Map.of("policyStoreId", store, "principal", principal, "action", action, "resource", resource,
+ "entities", Map.of("entityList", java.util.List.of(entity)));
+ givenAws("IsAuthorized", objectJson(auth)).then().statusCode(200).body("decision", equalTo("ALLOW"));
+
+ Map<String,Object> item1 = Map.of("principal", principal, "action", action, "resource", resource);
+ Map<String,Object> item2 = Map.of("principal", principal,
+ "action", Map.of("actionType", "Demo::Action", "actionId", "read"),
+ "resource", Map.of("entityType", "Demo::Document", "entityId", "doc2"));
+ givenAws("BatchIsAuthorized", objectJson(Map.of("policyStoreId", store, "requests", java.util.List.of(item1, item2),
+ "entities", Map.of("entityList", java.util.List.of(entity)))))
+ .then().statusCode(200).body("results.size()", equalTo(2))
+ .body("results[0].decision", equalTo("ALLOW"))
+ .body("results[1].decision", equalTo("DENY"));
+ }
+
+ @Test
+ void createOperationsHonorEightHourClientTokenContract() {
+ String token = "token-123456";
+ String body = objectJson(Map.of("clientToken", token, "validationSettings", Map.of("mode", "OFF")));
+ String first = givenAws("CreatePolicyStore", body).then().statusCode(200).extract().path("policyStoreId");
+ String second = givenAws("CreatePolicyStore", body).then().statusCode(200).extract().path("policyStoreId");
+ org.junit.jupiter.api.Assertions.assertEquals(first, second);
+ givenAws("CreatePolicyStore", objectJson(Map.of("clientToken", token,
+ "validationSettings", Map.of("mode", "STRICT"))))
+ .then().statusCode(400).body("__type", containsString("ConflictException"));
+ }
+
+ @Test
+ void identitySourcesSupportCognitoAndOidcLifecycleAndFiltering() {
+ String store = createStore("OFF", "DISABLED");
+ String cognitoArn = "arn:aws:cognito-idp:us-east-1:111122223333:userpool/us-east-1_example";
+ String cognitoCreate = objectJson(Map.of(
+ "policyStoreId", store,
+ "principalEntityType", "Demo::User",
+ "configuration", Map.of("cognitoUserPoolConfiguration", Map.of(
+ "userPoolArn", cognitoArn,
+ "clientIds", java.util.List.of("client-1"),
+ "groupConfiguration", Map.of("groupEntityType", "Demo::Group")))));
+ String cognitoId = givenAws("CreateIdentitySource", cognitoCreate).then().statusCode(200)
+ .extract().path("identitySourceId");
+ givenAws("GetIdentitySource", objectJson(Map.of("policyStoreId", store, "identitySourceId", cognitoId)))
+ .then().statusCode(200)
+ .body("principalEntityType", equalTo("Demo::User"))
+ .body("details.openIdIssuer", equalTo("COGNITO"))
+ .body("configuration.cognitoUserPoolConfiguration.issuer", equalTo("https://cognito-idp.us-east-1.amazonaws.com/us-east-1_example"));
+
+ String oidcCreate = objectJson(Map.of(
+ "policyStoreId", store,
+ "principalEntityType", "Demo::ExternalUser",
+ "configuration", Map.of("openIdConnectConfiguration", Map.of(
+ "issuer", "https://id.example.com",
+ "entityIdPrefix", "ext",
+ "tokenSelection", Map.of("identityTokenOnly", Map.of(
+ "clientIds", java.util.List.of("web-client"), "principalIdClaim", "sub"))))));
+ String oidcId = givenAws("CreateIdentitySource", oidcCreate).then().statusCode(200)
+ .extract().path("identitySourceId");
+ givenAws("ListIdentitySources", objectJson(Map.of("policyStoreId", store,
+ "filters", java.util.List.of(Map.of("principalEntityType", "Demo::ExternalUser")))))
+ .then().statusCode(200).body("identitySources.size()", equalTo(1))
+ .body("identitySources[0].identitySourceId", equalTo(oidcId));
+
+ String update = objectJson(Map.of(
+ "policyStoreId", store,
+ "identitySourceId", oidcId,
+ "principalEntityType", "Demo::Partner",
+ "updateConfiguration", Map.of("openIdConnectConfiguration", Map.of(
+ "issuer", "https://id2.example.com",
+ "entityIdPrefix", "partner",
+ "tokenSelection", Map.of("accessTokenOnly", Map.of(
+ "audiences", java.util.List.of("api://demo"), "principalIdClaim", "sub"))))));
+ givenAws("UpdateIdentitySource", update).then().statusCode(200);
+ givenAws("GetIdentitySource", objectJson(Map.of("policyStoreId", store, "identitySourceId", oidcId)))
+ .then().statusCode(200).body("principalEntityType", equalTo("Demo::Partner"))
+ .body("configuration.openIdConnectConfiguration.issuer", equalTo("https://id2.example.com"));
+ givenAws("DeleteIdentitySource", objectJson(Map.of("policyStoreId", store, "identitySourceId", oidcId)))
+ .then().statusCode(200);
+ givenAws("GetIdentitySource", objectJson(Map.of("policyStoreId", store, "identitySourceId", oidcId)))
+ .then().statusCode(400).body("__type", containsString("ResourceNotFoundException"));
+ }
+
+ @Test
+ void deletePolicyAndPolicyStore_areIdempotentForRetries() {
+ String store = createStore("OFF", "DISABLED");
+ String policy = givenAws("CreatePolicy", objectJson(Map.of(
+ "policyStoreId", store,
+ "definition", Map.of("static", Map.of(
+ "statement", "permit(principal, action, resource);")))))
+ .then().statusCode(200).extract().path("policyId");
+
+ givenAws("DeletePolicy", objectJson(Map.of("policyStoreId", store, "policyId", policy)))
+ .then().statusCode(200);
+ givenAws("DeletePolicy", objectJson(Map.of("policyStoreId", store, "policyId", policy)))
+ .then().statusCode(200);
+ givenAws("DeletePolicyStore", objectJson(Map.of("policyStoreId", store)))
+ .then().statusCode(200);
+ givenAws("DeletePolicyStore", objectJson(Map.of("policyStoreId", store)))
+ .then().statusCode(200);
+ }
+
+ @Test
+ void updatePolicy_preservesProtectedScopeAndAllowsNameOnlyUpdate() {
+ String store = createStore("OFF", "DISABLED");
+ String original = "permit(principal == Demo::User::\"alice\", action == Demo::Action::\"read\", resource == Demo::Document::\"doc-1\");";
+ String policyId = givenAws("CreatePolicy", objectJson(Map.of(
+ "policyStoreId", store,
+ "definition", Map.of("static", Map.of("statement", original)))))
+ .then().statusCode(200)
+ .body("principal.entityType", equalTo("Demo::User"))
+ .body("principal.entityId", equalTo("alice"))
+ .body("resource.entityType", equalTo("Demo::Document"))
+ .body("resource.entityId", equalTo("doc-1"))
+ .extract().path("policyId");
+
+ givenAws("UpdatePolicy", objectJson(Map.of("policyStoreId", store, "policyId", policyId,
+ "name", "name/alice-reader")))
+ .then().statusCode(200).body("policyId", equalTo(policyId));
+
+ String changedPrincipal = "permit(principal == Demo::User::\"bob\", action == Demo::Action::\"read\", resource == Demo::Document::\"doc-1\");";
+ givenAws("UpdatePolicy", objectJson(Map.of("policyStoreId", store, "policyId", policyId,
+ "definition", Map.of("static", Map.of("statement", changedPrincipal)))))
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void identitySourceDocumentedCollectionLimits_areEnforced() {
+ String store = createStore("OFF", "DISABLED");
+ java.util.List<String> emptyAudiences = java.util.List.of();
+ givenAws("CreateIdentitySource", objectJson(Map.of(
+ "policyStoreId", store,
+ "principalEntityType", "Demo::User",
+ "configuration", Map.of("openIdConnectConfiguration", Map.of(
+ "issuer", "https://id.example.com",
+ "tokenSelection", Map.of("accessTokenOnly", Map.of(
+ "audiences", emptyAudiences)))))))
+ .then().statusCode(400).body("__type", containsString("ValidationException"));
+ }
+
+ private static String objectJson(Object value) {
+ try {
+ return new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(value);
+ } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifierTest.java b/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifierTest.java
new file mode 100644
index 0000000000..6eefa4d7d3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsOidcSignatureVerifierTest.java
@@ -0,0 +1,145 @@
+package io.github.hectorvent.floci.services.verifiedpermissions;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.hc.client5.http.SystemDefaultDnsResolver;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayInputStream;
+import java.net.InetAddress;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class VerifiedPermissionsOidcSignatureVerifierTest {
+
+ @Test
+ void publicIssuerValidationRequiresHttpsAndRejectsLocalNetworkAddresses() throws Exception {
+ assertThrows(VerifiedPermissionsOidcSignatureVerifier.VerificationException.class,
+ () -> VerifiedPermissionsOidcSignatureVerifier.validatePublicHttpsUri(
+ "http://issuer.example.com", "OIDC issuer"));
+ assertDoesNotThrow(() -> VerifiedPermissionsOidcSignatureVerifier.validatePublicHttpsUri(
+ "https://issuer.example.com", "OIDC issuer"));
+ assertThrows(VerifiedPermissionsOidcSignatureVerifier.VerificationException.class,
+ () -> VerifiedPermissionsOidcSignatureVerifier.validatePublicHttpsUri(
+ "https://127.0.0.1", "OIDC issuer"));
+ assertThrows(VerifiedPermissionsOidcSignatureVerifier.VerificationException.class,
+ () -> VerifiedPermissionsOidcSignatureVerifier.validatePublicHttpsUri(
+ "https://[::1]", "OIDC issuer"));
+
+ assertTrue(VerifiedPermissionsOidcSignatureVerifier.isBlockedPublicAddress(
+ InetAddress.getByName("127.0.0.1")));
+ assertTrue(VerifiedPermissionsOidcSignatureVerifier.isBlockedPublicAddress(
+ InetAddress.getByName("169.254.169.254")));
+ assertTrue(VerifiedPermissionsOidcSignatureVerifier.isBlockedPublicAddress(
+ InetAddress.getByName("10.0.0.1")));
+ assertTrue(VerifiedPermissionsOidcSignatureVerifier.isBlockedPublicAddress(
+ InetAddress.getByName("192.168.1.1")));
+ }
+
+ @Test
+ void oidcDocumentsRejectOversizedDeclaredAndStreamingBodies() throws Exception {
+ byte[] exactLimit = new byte[VerifiedPermissionsOidcSignatureVerifier.MAX_OIDC_DOCUMENT_BYTES];
+ assertEquals(exactLimit.length, VerifiedPermissionsOidcSignatureVerifier.readBoundedBody(
+ new ByteArrayInputStream(exactLimit), exactLimit.length, "OIDC discovery document").length);
+
+ byte[] oversized = new byte[VerifiedPermissionsOidcSignatureVerifier.MAX_OIDC_DOCUMENT_BYTES + 1];
+ assertThrows(VerifiedPermissionsOidcSignatureVerifier.VerificationException.class,
+ () -> VerifiedPermissionsOidcSignatureVerifier.readBoundedBody(
+ new ByteArrayInputStream(oversized), oversized.length, "OIDC discovery document"));
+ assertThrows(VerifiedPermissionsOidcSignatureVerifier.VerificationException.class,
+ () -> VerifiedPermissionsOidcSignatureVerifier.readBoundedBody(
+ new ByteArrayInputStream(oversized), -1, "JWKS document"));
+ }
+
+ @Test
+ void unknownKidsTriggerAtMostOneRateLimitedRefresh() throws Exception {
+ RSAPublicKey key = org.mockito.Mockito.mock(RSAPublicKey.class);
+ class CountingVerifier extends VerifiedPermissionsOidcSignatureVerifier {
+ int fetches;
+
+ CountingVerifier() {
+ super(new ObjectMapper(), SystemDefaultDnsResolver.INSTANCE);
+ }
+
+ @Override
+ Map<String, RSAPublicKey> fetchJwks(String issuer) {
+ fetches++;
+ return Map.of("known", key);
+ }
+ }
+
+ try (CountingVerifier verifier = new CountingVerifier()) {
+ assertSame(key, verifier.resolveKey("https://issuer.example.com", "known"));
+ assertNull(verifier.resolveKey("https://issuer.example.com", "missing-one"));
+ assertNull(verifier.resolveKey("https://issuer.example.com", "missing-two"));
+ assertEquals(2, verifier.fetches);
+ }
+ }
+
+ @Test
+ void unknownKidRefreshAllowsRoutineKeyRotation() throws Exception {
+ RSAPublicKey oldKey = org.mockito.Mockito.mock(RSAPublicKey.class);
+ RSAPublicKey newKey = org.mockito.Mockito.mock(RSAPublicKey.class);
+ class RotatingVerifier extends VerifiedPermissionsOidcSignatureVerifier {
+ int fetches;
+
+ RotatingVerifier() {
+ super(new ObjectMapper(), SystemDefaultDnsResolver.INSTANCE);
+ }
+
+ @Override
+ Map<String, RSAPublicKey> fetchJwks(String issuer) {
+ fetches++;
+ if (fetches == 1) {
+ return Map.of("old", oldKey);
+ }
+ return Map.of("old", oldKey, "new", newKey);
+ }
+ }
+
+ try (RotatingVerifier verifier = new RotatingVerifier()) {
+ assertSame(oldKey, verifier.resolveKey("https://issuer.example.com", "old"));
+ assertSame(newKey, verifier.resolveKey("https://issuer.example.com", "new"));
+ assertEquals(2, verifier.fetches);
+ }
+ }
+
+ @Test
+ void failedUnknownKidRefreshDoesNotStartCooldown() throws Exception {
+ RSAPublicKey oldKey = org.mockito.Mockito.mock(RSAPublicKey.class);
+ RSAPublicKey newKey = org.mockito.Mockito.mock(RSAPublicKey.class);
+ class RecoveringVerifier extends VerifiedPermissionsOidcSignatureVerifier {
+ int fetches;
+
+ RecoveringVerifier() {
+ super(new ObjectMapper(), SystemDefaultDnsResolver.INSTANCE);
+ }
+
+ @Override
+ Map<String, RSAPublicKey> fetchJwks(String issuer) {
+ fetches++;
+ if (fetches == 1) {
+ return Map.of("old", oldKey);
+ }
+ if (fetches == 2) {
+ throw new VerificationException("temporary JWKS failure");
+ }
+ return Map.of("old", oldKey, "new", newKey);
+ }
+ }
+
+ try (RecoveringVerifier verifier = new RecoveringVerifier()) {
+ assertSame(oldKey, verifier.resolveKey("https://issuer.example.com", "old"));
+ assertThrows(VerifiedPermissionsOidcSignatureVerifier.VerificationException.class,
+ () -> verifier.resolveKey("https://issuer.example.com", "new"));
+ assertSame(newKey, verifier.resolveKey("https://issuer.example.com", "new"));
+ assertEquals(3, verifier.fetches);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsServiceTest.java
new file mode 100644
index 0000000000..5a293fbbaf
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsServiceTest.java
@@ -0,0 +1,98 @@
+package io.github.hectorvent.floci.services.verifiedpermissions;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.sun.net.httpserver.HttpServer;
+import io.github.hectorvent.floci.cedar.CedarSidecarServer;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.RegionResolver;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.StorageBackend;
+import io.github.hectorvent.floci.services.kms.KmsService;
+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 org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class VerifiedPermissionsServiceTest {
+ private static final String ACCOUNT = "000000000000";
+ private static final String REGION = "us-east-1";
+
+ private static HttpServer cedarServer;
+ private final ObjectMapper objectMapper = new ObjectMapper();
+ private VerifiedPermissionsService service;
+
+ @BeforeAll
+ static void startCedarSidecar() throws Exception {
+ cedarServer = CedarSidecarServer.start(18181);
+ }
+
+ @AfterAll
+ static void stopCedarSidecar() {
+ cedarServer.stop(0);
+ }
+
+ @BeforeEach
+ void setUp() {
+ StorageBackend<String, PolicyStore> policyStores = AccountAwareStorageBackend.inMemory(ACCOUNT);
+ StorageBackend<String, PolicyStoreAlias> aliases = AccountAwareStorageBackend.inMemory(ACCOUNT);
+ StorageBackend<String, Policy> policies = AccountAwareStorageBackend.inMemory(ACCOUNT);
+ StorageBackend<String, PolicyTemplate> templates = AccountAwareStorageBackend.inMemory(ACCOUNT);
+ StorageBackend<String, IdempotencyRecord> idempotency = AccountAwareStorageBackend.inMemory(ACCOUNT);
+ StorageBackend<String, IdentitySource> identitySources = AccountAwareStorageBackend.inMemory(ACCOUNT);
+ CedarSidecarManager manager = mock(CedarSidecarManager.class);
+ when(manager.ensureReady()).thenReturn("http://127.0.0.1:18181");
+ CedarSidecarClient cedarClient = new CedarSidecarClient(manager, objectMapper);
+ service = new VerifiedPermissionsService(policyStores, aliases, policies, templates, idempotency,
+ identitySources, new RegionResolver(REGION, ACCOUNT), objectMapper, mock(KmsService.class), cedarClient);
+ }
+
+ @Test
+ void policyStoreLifecycleIsAvailableAtServiceLayer() throws Exception {
+ PolicyStore created = service.createPolicyStore(json("""
+ {"validationSettings":{"mode":"OFF"},"description":"service-test"}
+ """), REGION);
+
+ assertEquals("OFF", created.validationMode());
+ assertEquals("service-test", service.getPolicyStore(created.policyStoreId(), REGION).description());
+
+ service.clear();
+
+ AwsException error = assertThrows(AwsException.class,
+ () -> service.getPolicyStore(created.policyStoreId(), REGION));
+ assertEquals("ResourceNotFoundException", error.getErrorCode());
+ }
+
+ @Test
+ void invalidCedarSchemaIsRejectedBeforePersistence() throws Exception {
+ PolicyStore store = service.createPolicyStore(json("""
+ {"validationSettings":{"mode":"OFF"}}
+ """), REGION);
+
+ AwsException error = assertThrows(AwsException.class, () -> service.putSchema(json("""
+ {"policyStoreId":"%s","definition":{"cedarJson":"{\\"Demo\\":{\\"entityTypes\\":[]}}"}}
+ """.formatted(store.policyStoreId())), REGION));
+
+ assertEquals("ValidationException", error.getErrorCode());
+ assertNull(service.getPolicyStore(store.policyStoreId(), REGION).schema());
+ AwsException missing = assertThrows(AwsException.class,
+ () -> service.getSchema(store.policyStoreId(), REGION));
+ assertEquals("ResourceNotFoundException", missing.getErrorCode());
+ }
+
+ private JsonNode json(String value) throws Exception {
+ return objectMapper.readTree(value);
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index ed1219dd67..f7873f59c7 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -439,6 +439,9 @@ floci:
enabled: true
servicequotas:
enabled: true
+ verifiedpermissions:
+ enabled: true
+ cedar-url: http://127.0.0.1:18180
ram:
enabled: true
codegurureviewer:
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index 627912f147..97bf0fa975 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -317,6 +317,10 @@ services:
doc: docs/services/budgets.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/budgets/BudgetsJsonHandler.java, mode: switch }
+ - service: verifiedpermissions
+ doc: docs/services/verifiedpermissions.md
+ sources:
+ - { path: src/main/java/io/github/hectorvent/floci/services/verifiedpermissions/VerifiedPermissionsJsonHandler.java, mode: switch }
- service: sqs
doc: docs/services/sqs.md
sources: