mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(verifiedpermissions): add full service emulation (#3128)
* feat(verifiedpermissions): add full service emulation * fix(verifiedpermissions): harden OIDC and schema validation * test(verifiedpermissions): add service layer coverage * fix(verifiedpermissions): support native Cedar runtime * fix(verifiedpermissions): package Cedar native FFI * fix(verifiedpermissions): register Cedar deserializers for native * fix(verifiedpermissions): bound JWKS refreshes * fix(verifiedpermissions): avoid Cedar entity reflection * fix(verifiedpermissions): register Cedar native reflection * fix(verifiedpermissions): refresh rotated OIDC keys safely * fix(verifiedpermissions): retry failed JWKS refreshes * refactor(verifiedpermissions): isolate Cedar in sidecar * fix(verifiedpermissions): harden Cedar sidecar runtime * fix(verifiedpermissions): build cedar sidecar in compatibility CI * fix(verifiedpermissions): remove stale cedar jni config * fix(verifiedpermissions): recover cedar sidecar * fix(verifiedpermissions): bound OIDC document responses * fix(verifiedpermissions): start cedar sidecar in native sdk CI
This commit is contained in:
1 parent
7a7531a6b9
commit
2d51259120
41 files changed
+4800
-4
No files matched your search
@@ -14,3 +14,4 @@
|
||||
!native/**
|
||||
!.mvn/**
|
||||
!mvnw
|
||||
!sidecars/cedar/**
|
||||
@@ -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\` |"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 |
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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)
|
||||
|
||||
+124
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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" \
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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
|
||||
```
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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"]
|
||||
@@ -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>
|
||||
+493
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -734,6 +734,7 @@ public interface EmulatorConfig {
|
||||
SecurityHubServiceConfig securityhub();
|
||||
DetectiveServiceConfig detective();
|
||||
ServiceQuotasServiceConfig servicequotas();
|
||||
VerifiedPermissionsServiceConfig verifiedpermissions();
|
||||
RamServiceConfig ram();
|
||||
ControlCatalogServiceConfig controlcatalog();
|
||||
ControlTowerServiceConfig controltower();
|
||||
@@ -926,6 +927,17 @@ public interface EmulatorConfig {
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface VerifiedPermissionsServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
/** When set, Floci uses this URL and skips Cedar sidecar container management. */
|
||||
Optional<String> cedarUrl();
|
||||
|
||||
@WithDefault("floci/floci:latest-cedar")
|
||||
String cedarImage();
|
||||
}
|
||||
|
||||
interface RamServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -16,6 +16,7 @@ import io.github.hectorvent.floci.services.sns.SnsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.swf.SwfJsonHandler;
|
||||
import io.github.hectorvent.floci.services.verifiedpermissions.VerifiedPermissionsJsonHandler;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
@@ -51,6 +52,7 @@ public class AwsJsonController {
|
||||
private final SwfJsonHandler swfJsonHandler;
|
||||
private final NetworkFirewallJsonHandler networkFirewallJsonHandler;
|
||||
private final MarketplaceJsonHandler marketplaceJsonHandler;
|
||||
private final VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler;
|
||||
|
||||
@Inject
|
||||
public AwsJsonController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog,
|
||||
@@ -63,7 +65,8 @@ public class AwsJsonController {
|
||||
CloudControlJsonHandler cloudControlJsonHandler,
|
||||
SwfJsonHandler swfJsonHandler,
|
||||
NetworkFirewallJsonHandler networkFirewallJsonHandler,
|
||||
MarketplaceJsonHandler marketplaceJsonHandler) {
|
||||
MarketplaceJsonHandler marketplaceJsonHandler,
|
||||
VerifiedPermissionsJsonHandler verifiedPermissionsJsonHandler) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.strictBodyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
|
||||
this.catalog = catalog;
|
||||
@@ -78,6 +81,7 @@ public class AwsJsonController {
|
||||
this.swfJsonHandler = swfJsonHandler;
|
||||
this.networkFirewallJsonHandler = networkFirewallJsonHandler;
|
||||
this.marketplaceJsonHandler = marketplaceJsonHandler;
|
||||
this.verifiedPermissionsJsonHandler = verifiedPermissionsJsonHandler;
|
||||
}
|
||||
|
||||
@POST
|
||||
@@ -129,6 +133,7 @@ public class AwsJsonController {
|
||||
case "network-firewall" -> networkFirewallJsonHandler.handle(
|
||||
action, request, region, regionResolver.getAccountId());
|
||||
case "marketplace" -> marketplaceJsonHandler.handle(action, request, region);
|
||||
case "verifiedpermissions" -> verifiedPermissionsJsonHandler.handle(action, request, region);
|
||||
default -> null;
|
||||
};
|
||||
// catalog.matchTarget is protocol-agnostic: a JSON 1.1 target
|
||||
|
||||
@@ -649,6 +649,10 @@ public class ResolvedServiceCatalog {
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("codeguru-reviewer"), Set.of(),
|
||||
Set.of(io.github.hectorvent.floci.services.codegurureviewer.CodeGuruReviewerController.class)),
|
||||
descriptor("verifiedpermissions", "verifiedpermissions", config.services().verifiedpermissions().enabled(), true,
|
||||
"verifiedpermissions", config.storage().mode(), 5000L, null, ServiceProtocol.JSON,
|
||||
protocols(ServiceProtocol.JSON),
|
||||
Set.of("VerifiedPermissions."), Set.of("verifiedpermissions"), Set.of(), Set.of()),
|
||||
descriptor("marketplace", "marketplace", config.services().marketplace().enabled(), true,
|
||||
"marketplace", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON, ServiceProtocol.JSON, ServiceProtocol.CBOR),
|
||||
|
||||
+216
@@ -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) {}
|
||||
}
|
||||
+127
@@ -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) {}
|
||||
}
|
||||
+158
@@ -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;
|
||||
}
|
||||
}
|
||||
+589
@@ -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;
|
||||
}
|
||||
}
|
||||
+371
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1164
File diff suppressed because it is too large.
Load diff
+307
@@ -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) {}
|
||||
}
|
||||
+6
@@ -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) {}
|
||||
+14
@@ -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) {}
|
||||
+21
@@ -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);
|
||||
}
|
||||
}
|
||||
+25
@@ -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);
|
||||
}
|
||||
}
|
||||
+44
@@ -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);
|
||||
}
|
||||
}
|
||||
+19
@@ -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);
|
||||
}
|
||||
}
|
||||
+20
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
+74
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
+375
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+145
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+98
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user