mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(verifiedpermissions): run Cedar from the floci-sidecar-cedar image (#3799)
* feat(verifiedpermissions): run Cedar from the floci-sidecar-cedar image The Cedar sidecar now comes from floci-io/floci-sidecars as floci/floci-sidecar-cedar, pinned to an exact version because a cached :latest is never re-pulled. CedarSidecarManager reads the contract JSON that the image's /health returns: a sidecar speaking another contract major is refused immediately with a message naming the image and the FLOCI_SERVICES_VERIFIEDPERMISSIONS_CEDAR_IMAGE and _CEDAR_URL settings to change, instead of polling for thirty seconds or failing later on a request. A pre-configured URL is probed the same way. A sidecar whose health body is not JSON predates the contract and is accepted with a one-time warning. * test(verifiedpermissions): exercise the published Cedar image VerifiedPermissionsIntegrationTest no longer boots the in-tree sidecar in process: CedarSidecarManager starts the pinned image through Docker, the same path production takes, under a vp-test resource namespace so the manager's remove-before-start cannot kill a developer's live sidecar. It is skipped without Docker, and locally when the image is not present; in CI a missing image fails. VerifiedPermissionsServiceTest keeps its reject-before-persist coverage against a fake sidecar answering 400, and CedarSidecarClientTest pins the request shapes and the 200/400/other mapping Floci owns. * chore(build): drop the in-tree Cedar sidecar sidecars/cedar now lives in floci-io/floci-sidecars as cedar/ with its history. The build-helper test source root and the test-scoped cedar-java dependency existed only to boot that server inside the test JVM; the tests now run against the published image, so both go, along with the .dockerignore allowlist entry that let the sidecar Dockerfile see its sources from the repository root context. * ci: stop publishing the Cedar sidecar from this repository The release, nightly and reusable image workflows no longer build a Cedar image or record it in the provenance manifest; the sidecar is released from floci-io/floci-sidecars on its own cadence. The compatibility workflow no longer builds and starts the sidecar by hand: Floci pulls the pinned image itself over the mounted socket onto compat-net, exactly as it already does for floci-duck. The unit-test shards prefetch the pinned image, reading the tag from application.yml so the two cannot drift. The floci/floci:*-cedar tags stop at this change; whether the next release cut retags the sidecar image under the old name for a deprecation window is a release decision, not a workflow default. * docs(verifiedpermissions): document the external Cedar sidecar image The Verified Permissions page names floci/floci-sidecar-cedar, why it is pinned to an exact version, how to pre-pull it, where its API and the sidecar contract are documented, and what a contract mismatch looks like. The README's Docker integration table gains the Verified Permissions row it never had. AGENTS.md records the sidecar rule: own repository, no tag suffix on the Floci image, no :latest default, the sidecar releases first, and how a sidecar is tested from here.
This commit is contained in:
1 parent
f004aeaad5
commit
892927ceb5
21 files changed
+480
-766
No files matched your search
@@ -14,4 +14,3 @@
|
||||
!native/**
|
||||
!.mvn/**
|
||||
!mvnw
|
||||
!sidecars/cedar/**
|
||||
@@ -21,4 +21,7 @@ grep -q '/memorydb/' "$SHARD_FILE" && pull valkey/valkey:8
|
||||
grep -q '/ecr/' "$SHARD_FILE" && pull registry:2
|
||||
grep -q '/ec2/' "$SHARD_FILE" && { pull busybox:stable; pull alpine:latest; }
|
||||
grep -q '/common/docker/' "$SHARD_FILE" && pull public.ecr.aws/docker/library/python:3.12-alpine
|
||||
# The Cedar sidecar pin lives in application.yml; read it rather than duplicate it.
|
||||
CEDAR_IMAGE="$(grep -oE 'cedar-image: *"[^"]+"' src/main/resources/application.yml | grep -oE '"[^"]+"' | tr -d '"')"
|
||||
grep -q '/verifiedpermissions/' "$SHARD_FILE" && [ -n "$CEDAR_IMAGE" ] && pull "$CEDAR_IMAGE"
|
||||
exit 0
|
||||
@@ -42,12 +42,6 @@ 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 }}
|
||||
@@ -265,8 +259,6 @@ 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 }}
|
||||
|
||||
@@ -342,29 +334,6 @@ 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
|
||||
@@ -421,7 +390,6 @@ 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 }}
|
||||
@@ -440,8 +408,6 @@ 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"
|
||||
@@ -461,10 +427,7 @@ jobs:
|
||||
--arg jvmRef "$jvm_ref" \
|
||||
--arg jvmDigest "$JVM_DIGEST" \
|
||||
--arg jvmDigestRef "$jvm_digest_ref" \
|
||||
--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"]}' \
|
||||
'{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"]}' \
|
||||
> floci-image-provenance.json
|
||||
|
||||
if [[ "$PUBLISH_NATIVE" == "true" ]]; then
|
||||
@@ -484,8 +447,6 @@ 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"
|
||||
@@ -503,7 +464,6 @@ 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,7 +4,6 @@ on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'src/**'
|
||||
- 'sidecars/cedar/**'
|
||||
- 'pom.xml'
|
||||
- 'docker/Dockerfile.native-package'
|
||||
- 'docker/Dockerfile.compat'
|
||||
@@ -125,7 +124,6 @@ jobs:
|
||||
with:
|
||||
sparse-checkout: |
|
||||
compatibility-tests
|
||||
sidecars/cedar
|
||||
.github/ci
|
||||
|
||||
- name: Compare compat-terraform and compat-opentofu resource lists
|
||||
@@ -300,10 +298,6 @@ 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 \
|
||||
@@ -313,7 +307,6 @@ 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 \
|
||||
@@ -348,24 +341,8 @@ 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,7 +8,6 @@ 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
|
||||
@@ -233,30 +232,6 @@ 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,8 +7,6 @@ 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
|
||||
# Baseline: floci/floci:1.2.3-baseline floci/floci:latest-baseline
|
||||
# public.ecr.aws/floci/floci:1.2.3-baseline public.ecr.aws/floci/floci:latest-baseline
|
||||
# Compat: floci/floci:1.2.3-compat floci/floci:latest-compat
|
||||
@@ -226,8 +224,8 @@ jobs:
|
||||
# Ordering matters: this step wipes native/ and replaces it with the arm64-only
|
||||
# baseline binary. It is safe only because it runs AFTER the multi-arch image
|
||||
# above has been pushed, and nothing that follows reads native/ from the build
|
||||
# context: the Cedar sidecar builds from sidecars/cedar/ only, and the compat
|
||||
# image pulls its base (BASE_IMAGE) from the registry. Moving this step above
|
||||
# context: the compat image pulls its base (BASE_IMAGE) from the registry.
|
||||
# Moving this step above
|
||||
# the multi-arch push would silently publish `latest` from the baseline binary.
|
||||
- name: Stage ARMv8.0 baseline artifact under the native package path
|
||||
run: |
|
||||
@@ -264,32 +262,6 @@ jobs:
|
||||
cache-from: type=gha,scope=floci-arm64-baseline
|
||||
cache-to: type=gha,scope=floci-arm64-baseline,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:
|
||||
|
||||
@@ -321,6 +321,33 @@ References: `SqsCfnProvisioner` (smallest), `Ec2LaunchTemplateCfnProvisioner`
|
||||
|
||||
---
|
||||
|
||||
## Sidecars
|
||||
|
||||
A dependency too heavy for the native image (a native runtime, a large engine, another language
|
||||
ecosystem) ships as a sidecar: a stateless HTTP service in its own container that Floci starts
|
||||
lazily over the Docker socket. Sidecars live in
|
||||
[floci-io/floci-sidecars](https://github.com/floci-io/floci-sidecars), one directory per sidecar
|
||||
on the shared `sidecar-core`, and are published as `floci/floci-sidecar-<name>:<semver>` on
|
||||
Docker Hub. They implement that repository's `docs/contract.md` and carry no AWS vocabulary: the
|
||||
sidecar answers a generic question, Floci maps its service semantics onto the answer.
|
||||
|
||||
Floci-side rules:
|
||||
|
||||
- Never add a `sidecars/` directory to this repository, never publish a `floci/floci:<tag>-<name>`
|
||||
suffix, and never default an image to `:latest` (`ImageCacheService` never re-pulls a cached tag).
|
||||
- The consuming service owns two config knobs, `<name>-image` (an exact version) and `<name>-url`
|
||||
(skip container management), and a `<Name>SidecarManager` plus `<Name>SidecarClient` pair.
|
||||
`CedarSidecarManager` is the reference: it reads the contract JSON from `/health` and fails fast
|
||||
on a contract-major mismatch.
|
||||
- The sidecar releases before the Floci PR that needs it, as a final or an `X.Y.Z-rc.N` tag; the
|
||||
Floci PR pins that tag. A PR that needs an unreleased sidecar cannot pass CI.
|
||||
- Tests: the client's wire contract is covered by a JDK `HttpServer` fake; one Docker-gated
|
||||
`@QuarkusTest` runs the pinned image through the real manager under its own
|
||||
`floci.docker.resource-namespace`. A Floci test imports only Floci classes; the sidecar's own
|
||||
behaviour is tested in its repository.
|
||||
- A sidecar that is a stock upstream image plus a script from the classpath needs no repository
|
||||
but still goes through a manager with the same two knobs.
|
||||
|
||||
## Code Style
|
||||
|
||||
### General
|
||||
|
||||
@@ -418,6 +418,7 @@ Floci uses real Docker containers when in-process emulation would reduce fidelit
|
||||
| CodeBuild | User-specified environment image | Buildspec execution, log streaming, S3 artifact upload |
|
||||
| OpenSearch | `opensearchproject/opensearch:2` | Full OpenSearch engine with REST API |
|
||||
| ECR | `registry:2` | OCI-compatible registry for docker push and docker pull |
|
||||
| Verified Permissions | `floci/floci-sidecar-cedar:1.1.0` | Cedar 4 policy parsing, schema validation and authorization decisions, via a [Floci sidecar](https://github.com/floci-io/floci-sidecars) |
|
||||
|
||||
Docker-backed services require the Docker socket:
|
||||
|
||||
|
||||
@@ -69,12 +69,23 @@ to the AVP token type.
|
||||
|
||||
## 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.
|
||||
Cedar parsing, schema validation, and authorization run in a lazily started sidecar container,
|
||||
`floci/floci-sidecar-cedar`, published from
|
||||
[floci-io/floci-sidecars](https://github.com/floci-io/floci-sidecars). The main Floci JVM and
|
||||
native images do not include Cedar Java or its multi-platform native runtime. Floci starts the
|
||||
sidecar on the first Cedar-dependent AVP operation, probes its health endpoint, and reuses it until
|
||||
shutdown. The image is pinned to an exact version rather than `latest`: a cached `latest` is never
|
||||
re-pulled, so a pin is the only way a Floci upgrade reliably brings the matching sidecar. Pull it
|
||||
ahead of time on an air-gapped host with `docker pull floci/floci-sidecar-cedar:1.1.0`.
|
||||
|
||||
The sidecar implements the
|
||||
[sidecar contract](https://github.com/floci-io/floci-sidecars/blob/main/docs/contract.md); its
|
||||
endpoints are documented in the sidecar's
|
||||
[API reference](https://github.com/floci-io/floci-sidecars/blob/main/cedar/API.md). Floci checks
|
||||
the contract version the sidecar reports on `/health`: a sidecar speaking another contract major is
|
||||
refused immediately with an `InternalServerException` naming the image and the variable to change.
|
||||
A pre-configured sidecar URL can be supplied when Docker Compose or another supervisor owns the
|
||||
sidecar lifecycle; it is checked the same way.
|
||||
|
||||
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
|
||||
@@ -131,7 +142,7 @@ aliases, identity sources, and idempotency records with other resettable service
|
||||
| --- | --- | --- |
|
||||
| `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 |
|
||||
| `FLOCI_SERVICES_VERIFIEDPERMISSIONS_CEDAR_IMAGE` | `floci/floci-sidecar-cedar:1.1.0` | Image used for the lazily managed Cedar 4 sidecar; pin an exact version |
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -331,15 +331,6 @@
|
||||
</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>
|
||||
@@ -464,23 +455,6 @@
|
||||
</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>
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
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"]
|
||||
@@ -1,57 +0,0 @@
|
||||
<?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
@@ -1,493 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -998,7 +998,7 @@ public interface EmulatorConfig {
|
||||
/** When set, Floci uses this URL and skips Cedar sidecar container management. */
|
||||
Optional<String> cedarUrl();
|
||||
|
||||
@WithDefault("floci/floci:latest-cedar")
|
||||
@WithDefault("floci/floci-sidecar-cedar:1.1.0")
|
||||
String cedarImage();
|
||||
}
|
||||
|
||||
|
||||
+78
-5
@@ -1,5 +1,8 @@
|
||||
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 io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
@@ -13,13 +16,30 @@ import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/** Lazily starts and manages the Cedar 4 sidecar used by Amazon Verified Permissions. */
|
||||
/**
|
||||
* Lazily starts and manages the Cedar 4 sidecar used by Amazon Verified Permissions.
|
||||
*
|
||||
* <p>The sidecar is the {@code floci/floci-sidecar-cedar} image from floci-io/floci-sidecars. Its
|
||||
* {@code GET /health} answers the sidecar contract: {@code {"status","name","version","contract"}}.
|
||||
* A sidecar speaking a different contract major fails fast with a message naming the fix, rather
|
||||
* than surfacing later as an unexplained request error. A sidecar whose health body is not JSON
|
||||
* predates the contract and is accepted with a warning.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CedarSidecarManager {
|
||||
/** The sidecar contract major this manager speaks; see docs/contract.md in floci-io/floci-sidecars. */
|
||||
static final String REQUIRED_CONTRACT = "1";
|
||||
static final String IMAGE_ENV = "FLOCI_SERVICES_VERIFIEDPERMISSIONS_CEDAR_IMAGE";
|
||||
static final String URL_ENV = "FLOCI_SERVICES_VERIFIEDPERMISSIONS_CEDAR_URL";
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CedarSidecarManager.class);
|
||||
private static final String CONTAINER_NAME = "floci-cedar";
|
||||
private static final int CEDAR_PORT = 8180;
|
||||
@@ -29,6 +49,8 @@ public class CedarSidecarManager {
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final EmulatorConfig config;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AtomicBoolean contractReported = new AtomicBoolean();
|
||||
|
||||
private volatile String resolvedUrl;
|
||||
private volatile String containerId;
|
||||
@@ -36,10 +58,12 @@ public class CedarSidecarManager {
|
||||
@Inject
|
||||
public CedarSidecarManager(ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
EmulatorConfig config) {
|
||||
EmulatorConfig config,
|
||||
ObjectMapper objectMapper) {
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.config = config;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public synchronized boolean isAvailable() {
|
||||
@@ -71,7 +95,11 @@ public class CedarSidecarManager {
|
||||
}
|
||||
Optional<String> configured = config.services().verifiedpermissions().cedarUrl();
|
||||
if (configured.isPresent() && !configured.get().isBlank()) {
|
||||
resolvedUrl = trimTrailingSlash(configured.get());
|
||||
String url = trimTrailingSlash(configured.get());
|
||||
// Best effort: a sidecar that is not up yet is reported by the first real call,
|
||||
// but a sidecar speaking the wrong contract is refused here, once, with the fix.
|
||||
probeHealth(url);
|
||||
resolvedUrl = url;
|
||||
LOG.infov("Using pre-configured Cedar sidecar URL: {0}", resolvedUrl);
|
||||
return resolvedUrl;
|
||||
}
|
||||
@@ -116,18 +144,63 @@ public class CedarSidecarManager {
|
||||
LOG.infov("Cedar sidecar is ready at {0}", resolvedUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code false} means not ready yet (connection refused, non-200, timeout). A sidecar that
|
||||
* answers but speaks another contract major throws instead, so callers never retry it.
|
||||
*/
|
||||
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) {
|
||||
if (connection.getResponseCode() != 200) {
|
||||
return false;
|
||||
}
|
||||
String body;
|
||||
try (InputStream in = connection.getInputStream()) {
|
||||
body = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
checkContract(baseUrl, body);
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Cedar sidecar health probe failed for {0}", baseUrl);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void checkContract(String baseUrl, String body) {
|
||||
JsonNode health = parseHealth(body);
|
||||
if (health == null || !health.hasNonNull("contract")) {
|
||||
if (contractReported.compareAndSet(false, true)) {
|
||||
LOG.warnv("Cedar sidecar at {0} predates the sidecar contract (health body is not contract JSON); "
|
||||
+ "it still works, but move to floci/floci-sidecar-cedar to get version checks", baseUrl);
|
||||
}
|
||||
return;
|
||||
}
|
||||
String contract = health.path("contract").asText();
|
||||
String name = health.path("name").asText("unknown");
|
||||
String version = health.path("version").asText("unknown");
|
||||
if (!REQUIRED_CONTRACT.equals(contract)) {
|
||||
throw new IllegalStateException("Cedar sidecar at " + baseUrl + " (" + name + " " + version
|
||||
+ ") speaks sidecar contract " + contract + " but this Floci requires contract "
|
||||
+ REQUIRED_CONTRACT + ". Set " + IMAGE_ENV + " (currently "
|
||||
+ config.services().verifiedpermissions().cedarImage() + ") or " + URL_ENV
|
||||
+ " to a compatible sidecar.");
|
||||
}
|
||||
if (contractReported.compareAndSet(false, true)) {
|
||||
LOG.infov("Cedar sidecar {0} {1} (contract {2}) at {3}", name, version, contract, baseUrl);
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode parseHealth(String body) {
|
||||
try {
|
||||
return objectMapper.readTree(body);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.debugv(e, "Cedar sidecar health body is not JSON: {0}", body);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void waitForHealth(String baseUrl) {
|
||||
long deadline = System.currentTimeMillis() + HEALTH_POLL_MAX_MS;
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
|
||||
@@ -788,7 +788,8 @@ floci:
|
||||
verifiedpermissions:
|
||||
enabled: true
|
||||
# cedar-url: http://floci-cedar:8180 # set to skip sidecar container management
|
||||
cedar-image: "floci/floci:latest-cedar"
|
||||
# Exact version on purpose: a cached :latest is never re-pulled. Published from floci-io/floci-sidecars.
|
||||
cedar-image: "floci/floci-sidecar-cedar:1.1.0"
|
||||
ram:
|
||||
enabled: true
|
||||
codegurureviewer:
|
||||
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
package io.github.hectorvent.floci.services.verifiedpermissions;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
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 org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The wire contract Floci owns towards the Cedar sidecar: request shapes for each endpoint and
|
||||
* how the sidecar's 200 / 400 / other answers become AWS errors. Cedar semantics live in the
|
||||
* sidecar's own repository.
|
||||
*/
|
||||
class CedarSidecarClientTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final AtomicReference<String> lastPath = new AtomicReference<>();
|
||||
private final AtomicReference<JsonNode> lastBody = new AtomicReference<>();
|
||||
private HttpServer server;
|
||||
private CedarSidecarClient client;
|
||||
|
||||
@BeforeEach
|
||||
void startServer() throws IOException {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.start();
|
||||
CedarSidecarManager manager = mock(CedarSidecarManager.class);
|
||||
when(manager.ensureReady()).thenReturn("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
client = new CedarSidecarClient(manager, mapper);
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopServer() {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateSchemaPostsTheSchema() {
|
||||
answer("/v1/schema/validate", 200, "{\"valid\":true}");
|
||||
|
||||
client.validateSchema("{\"Demo\":{}}");
|
||||
|
||||
assertThat(lastPath.get(), equalTo("/v1/schema/validate"));
|
||||
assertThat(lastBody.get().get("schema").asText(), equalTo("{\"Demo\":{}}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validateEntityTypePostsTheType() {
|
||||
answer("/v1/entity-type/validate", 200, "{\"valid\":true}");
|
||||
|
||||
client.validateEntityType("Demo::User");
|
||||
|
||||
assertThat(lastBody.get().get("entityType").asText(), equalTo("Demo::User"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsePolicyReturnsEffectAndAst() {
|
||||
answer("/v1/policy/parse", 200, "{\"effect\":\"Forbid\",\"ast\":{\"effect\":\"forbid\"}}");
|
||||
|
||||
CedarSidecarClient.ParsedPolicy parsed = client.parsePolicy("forbid(principal, action, resource);", true);
|
||||
|
||||
assertThat(lastBody.get().get("statement").asText(), equalTo("forbid(principal, action, resource);"));
|
||||
assertThat(lastBody.get().get("template").asBoolean(), is(true));
|
||||
assertThat(parsed.effect(), equalTo("Forbid"));
|
||||
assertThat(parsed.ast().get("effect").asText(), equalTo("forbid"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validatePolicyPostsSchemaStatementAndTemplateFlag() {
|
||||
answer("/v1/policy/validate", 200, "{\"valid\":true}");
|
||||
|
||||
client.validatePolicy("{\"Demo\":{}}", "permit(principal, action, resource);", false);
|
||||
|
||||
assertThat(lastBody.get().get("schema").asText(), equalTo("{\"Demo\":{}}"));
|
||||
assertThat(lastBody.get().get("statement").asText(), equalTo("permit(principal, action, resource);"));
|
||||
assertThat(lastBody.get().get("template").asBoolean(), is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizePostsRequestPoliciesAndTemplatesAndReadsTheDecision() throws Exception {
|
||||
answer("/v1/authorize", 200,
|
||||
"{\"decision\":\"DENY\",\"determiningPolicyIds\":[\"deny\"],\"errors\":[\"e1\"]}");
|
||||
JsonNode request = mapper.readTree("{\"principal\":{\"entityType\":\"Demo::User\",\"entityId\":\"a\"}}");
|
||||
Policy policy = new Policy("store", "deny", null, "STATIC", "forbid(principal, action, resource);",
|
||||
null, null, null, null, "Forbid", null, null);
|
||||
PolicyTemplate template = new PolicyTemplate("store", "t1", null,
|
||||
"permit(principal == ?principal, action, resource == ?resource);", null, null, null);
|
||||
|
||||
CedarSidecarClient.EvaluationResult result = client.authorize(request, List.of(policy), Map.of("t1", template));
|
||||
|
||||
assertThat(lastBody.get().get("request").get("principal").get("entityId").asText(), equalTo("a"));
|
||||
assertThat(lastBody.get().get("policies").get(0).get("policyId").asText(), equalTo("deny"));
|
||||
assertThat(lastBody.get().get("templates").get("t1").get("policyTemplateId").asText(), equalTo("t1"));
|
||||
assertThat(result.decision(), equalTo("DENY"));
|
||||
assertThat(result.determiningPolicyIds(), contains("deny"));
|
||||
assertThat(result.errors(), contains("e1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sidecarBadRequestBecomesValidationExceptionWithTheSidecarMessage() {
|
||||
answer("/v1/policy/parse", 400, "{\"error\":\"unexpected token\"}");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> client.parsePolicy("permit(", false));
|
||||
|
||||
assertThat(error.getErrorCode(), equalTo("ValidationException"));
|
||||
assertThat(error.getMessage(), equalTo("unexpected token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherSidecarFailuresBecomeInternalServerException() {
|
||||
answer("/v1/authorize", 500, "{\"error\":\"boom\"}");
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> client.authorize(mapper.createObjectNode(), List.of(), Map.of()));
|
||||
|
||||
assertThat(error.getErrorCode(), equalTo("InternalServerException"));
|
||||
assertThat(error.getHttpStatus(), equalTo(500));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreachableSidecarBecomesInternalServerException() {
|
||||
CedarSidecarManager down = mock(CedarSidecarManager.class);
|
||||
when(down.ensureReady()).thenThrow(new IllegalStateException("speaks sidecar contract 2"));
|
||||
CedarSidecarClient offline = new CedarSidecarClient(down, mapper);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> offline.validateSchema("{}"));
|
||||
|
||||
assertThat(error.getErrorCode(), equalTo("InternalServerException"));
|
||||
assertThat(error.getMessage(), equalTo("Failed to call Cedar sidecar for schema validation: speaks sidecar contract 2"));
|
||||
}
|
||||
|
||||
private void answer(String path, int status, String body) {
|
||||
server.createContext(path, exchange -> {
|
||||
lastPath.set(exchange.getRequestURI().getPath());
|
||||
lastBody.set(mapper.readTree(exchange.getRequestBody()));
|
||||
respond(exchange, status, body);
|
||||
});
|
||||
}
|
||||
|
||||
private static void respond(HttpExchange exchange, int status, String body) throws IOException {
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
+106
-21
@@ -1,16 +1,27 @@
|
||||
package io.github.hectorvent.floci.services.verifiedpermissions;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
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.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
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.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
@@ -18,38 +29,35 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
class CedarSidecarManagerTest {
|
||||
|
||||
private final ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
|
||||
private final ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
private final EmulatorConfig.VerifiedPermissionsServiceConfig verifiedPermissions =
|
||||
mock(EmulatorConfig.VerifiedPermissionsServiceConfig.class);
|
||||
private final EmulatorConfig config = config(verifiedPermissions);
|
||||
private HttpServer fakeSidecar;
|
||||
|
||||
@AfterEach
|
||||
void stopFakeSidecar() {
|
||||
if (fakeSidecar != null) {
|
||||
fakeSidecar.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
@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);
|
||||
CedarSidecarManager manager = manager();
|
||||
|
||||
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);
|
||||
CedarSidecarManager manager = manager();
|
||||
setField(manager, "resolvedUrl", "http://127.0.0.1:1");
|
||||
setField(manager, "containerId", "stale-cedar");
|
||||
|
||||
@@ -59,6 +67,84 @@ class CedarSidecarManagerTest {
|
||||
assertNull(getField(manager, "containerId"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void contractOneSidecarIsAvailable() throws Exception {
|
||||
String url = startFakeSidecar(200, "{\"status\":\"ok\",\"name\":\"cedar\",\"version\":\"1.0.0\",\"contract\":\"1\"}");
|
||||
when(verifiedPermissions.cedarUrl()).thenReturn(Optional.of(url));
|
||||
|
||||
CedarSidecarManager manager = manager();
|
||||
|
||||
assertTrue(manager.isAvailable());
|
||||
assertEquals(url, manager.ensureReady());
|
||||
verifyNoInteractions(containerBuilder, lifecycleManager);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherContractMajorFailsFastNamingTheFix() throws Exception {
|
||||
String url = startFakeSidecar(200, "{\"status\":\"ok\",\"name\":\"cedar\",\"version\":\"2.3.0\",\"contract\":\"2\"}");
|
||||
when(verifiedPermissions.cedarUrl()).thenReturn(Optional.of(url));
|
||||
when(verifiedPermissions.cedarImage()).thenReturn("floci/floci-sidecar-cedar:1.1.0");
|
||||
|
||||
CedarSidecarManager manager = manager();
|
||||
|
||||
IllegalStateException available = assertThrows(IllegalStateException.class, manager::isAvailable);
|
||||
IllegalStateException ready = assertThrows(IllegalStateException.class, manager::ensureReady);
|
||||
assertThat(available.getMessage(), containsString("speaks sidecar contract 2"));
|
||||
assertThat(available.getMessage(), containsString("requires contract 1"));
|
||||
assertThat(available.getMessage(), containsString("cedar 2.3.0"));
|
||||
assertThat(ready.getMessage(), containsString(CedarSidecarManager.IMAGE_ENV));
|
||||
assertThat(ready.getMessage(), containsString("floci/floci-sidecar-cedar:1.1.0"));
|
||||
assertThat(ready.getMessage(), containsString(CedarSidecarManager.URL_ENV));
|
||||
assertNull(getField(manager, "resolvedUrl"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preContractSidecarWithTextHealthIsAccepted() throws Exception {
|
||||
String url = startFakeSidecar(200, "ok");
|
||||
when(verifiedPermissions.cedarUrl()).thenReturn(Optional.of(url));
|
||||
|
||||
CedarSidecarManager manager = manager();
|
||||
|
||||
assertTrue(manager.isAvailable());
|
||||
assertEquals(url, manager.ensureReady());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unhealthySidecarIsNotReadyRatherThanWrong() throws Exception {
|
||||
String url = startFakeSidecar(503, "{\"status\":\"starting\",\"contract\":\"2\"}");
|
||||
when(verifiedPermissions.cedarUrl()).thenReturn(Optional.of(url));
|
||||
|
||||
CedarSidecarManager manager = manager();
|
||||
|
||||
assertFalse(manager.isAvailable());
|
||||
assertEquals(url, manager.ensureReady());
|
||||
}
|
||||
|
||||
private CedarSidecarManager manager() {
|
||||
return new CedarSidecarManager(containerBuilder, lifecycleManager, config, new ObjectMapper());
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(EmulatorConfig.VerifiedPermissionsServiceConfig verifiedPermissions) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.verifiedpermissions()).thenReturn(verifiedPermissions);
|
||||
return config;
|
||||
}
|
||||
|
||||
private String startFakeSidecar(int status, String healthBody) throws IOException {
|
||||
fakeSidecar = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
fakeSidecar.createContext("/health", exchange -> {
|
||||
byte[] bytes = healthBody.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(status, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
});
|
||||
fakeSidecar.start();
|
||||
return "http://127.0.0.1:" + fakeSidecar.getAddress().getPort();
|
||||
}
|
||||
|
||||
private static void setField(Object target, String name, Object value) throws Exception {
|
||||
Field field = target.getClass().getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
@@ -70,5 +156,4 @@ class CedarSidecarManagerTest {
|
||||
field.setAccessible(true);
|
||||
return field.get(target);
|
||||
}
|
||||
|
||||
}
|
||||
+49
-11
@@ -2,9 +2,10 @@ 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 io.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.eclipse.microprofile.config.ConfigProvider;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -16,21 +17,58 @@ import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasEntry;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
|
||||
/**
|
||||
* Runs against the real Cedar sidecar image ({@code floci.services.verifiedpermissions.cedar-image}),
|
||||
* started by {@link CedarSidecarManager} exactly as in production. Needs Docker; skipped without
|
||||
* it. Locally it is also skipped when the pinned image is not present, so a developer without
|
||||
* registry access is not stuck; in CI a missing image is a failure, since a vanished tag must
|
||||
* not pass silently.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(VerifiedPermissionsIntegrationTest.CedarSidecarProfile.class)
|
||||
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();
|
||||
/**
|
||||
* Namespaces the sidecar container as {@code floci-vp-test-cedar}: the manager removes any
|
||||
* container of its name before starting, and the test config uses the same empty namespace
|
||||
* as a developer's running Floci, whose live sidecar would otherwise be killed.
|
||||
*/
|
||||
public static class CedarSidecarProfile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of("floci.docker.resource-namespace", "vp-test");
|
||||
}
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopCedarSidecar() {
|
||||
cedarServer.stop(0);
|
||||
@BeforeAll
|
||||
static void requireDockerAndTheSidecarImage() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
Assumptions.assumeTrue(isDockerAvailable(),
|
||||
"Docker daemon must be available for Verified Permissions integration tests");
|
||||
String image = ConfigProvider.getConfig().getValue("floci.services.verifiedpermissions.cedar-image", String.class);
|
||||
Assumptions.assumeTrue(imageUsable(image), "Cedar sidecar image " + image + " is not present locally");
|
||||
}
|
||||
|
||||
private static boolean isDockerAvailable() {
|
||||
return run("docker", "version", "--format", "{{.Server.Version}}");
|
||||
}
|
||||
|
||||
private static boolean imageUsable(String image) {
|
||||
if ("true".equals(System.getenv("CI"))) {
|
||||
return true;
|
||||
}
|
||||
return run("docker", "image", "inspect", image);
|
||||
}
|
||||
|
||||
private static boolean run(String... command) {
|
||||
try {
|
||||
Process process = new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
return process.waitFor() == 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+24
-7
@@ -3,7 +3,6 @@ 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;
|
||||
@@ -20,6 +19,10 @@ import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -30,18 +33,32 @@ class VerifiedPermissionsServiceTest {
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
private static HttpServer cedarServer;
|
||||
/**
|
||||
* A stand-in for the Cedar sidecar that rejects every schema. These tests cover the service's
|
||||
* ordering (reject before persist), not Cedar itself; Cedar semantics are covered by
|
||||
* {@code VerifiedPermissionsIntegrationTest} against the real image.
|
||||
*/
|
||||
private static HttpServer fakeCedar;
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private VerifiedPermissionsService service;
|
||||
|
||||
@BeforeAll
|
||||
static void startCedarSidecar() throws Exception {
|
||||
cedarServer = CedarSidecarServer.start(18181);
|
||||
static void startFakeCedar() throws Exception {
|
||||
fakeCedar = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
fakeCedar.createContext("/v1/schema/validate", exchange -> {
|
||||
byte[] bytes = "{\"error\":\"entityTypes must be an object\"}".getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json");
|
||||
exchange.sendResponseHeaders(400, bytes.length);
|
||||
try (OutputStream out = exchange.getResponseBody()) {
|
||||
out.write(bytes);
|
||||
}
|
||||
});
|
||||
fakeCedar.start();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopCedarSidecar() {
|
||||
cedarServer.stop(0);
|
||||
static void stopFakeCedar() {
|
||||
fakeCedar.stop(0);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
@@ -53,7 +70,7 @@ class VerifiedPermissionsServiceTest {
|
||||
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");
|
||||
when(manager.ensureReady()).thenReturn("http://127.0.0.1:" + fakeCedar.getAddress().getPort());
|
||||
CedarSidecarClient cedarClient = new CedarSidecarClient(manager, objectMapper);
|
||||
service = new VerifiedPermissionsService(policyStores, aliases, policies, templates, idempotency,
|
||||
identitySources, new RegionResolver(REGION, ACCOUNT), objectMapper, mock(KmsService.class), cedarClient);
|
||||
|
||||
@@ -483,7 +483,6 @@ floci:
|
||||
enabled: true
|
||||
verifiedpermissions:
|
||||
enabled: true
|
||||
cedar-url: http://127.0.0.1:18180
|
||||
ram:
|
||||
enabled: true
|
||||
codegurureviewer:
|
||||
|
||||
Reference in new issue
Block a user