From 520859e47e88e8beee824d386529ff548e358cf7 Mon Sep 17 00:00:00 2001 From: Saurabh Jain Date: Mon, 14 Sep 2026 09:23:53 +0200 Subject: [PATCH 1/3] feat(typed-policies): v11 parity: typed members, active(), v11 legs The typed answers carry the refusal's policy (getPolicy(), through a new seven-argument constructor; the six-argument one names no policy); the edition's catalog_digest, registry_version and catalog_fixture; template_omissions (TemplateOmissionReport) and template_omissions_unavailable on the publication and the activation; and the system control's name. TypedPolicySystemControl.getMandatory() returns a plain boolean, false when the platform omits it or sends null. active() is empty only for a 404 whose reason is nothing_active; any other 404 is a TypedPolicyRefusalException with status 404, and so is a 503 storage_unavailable (getaxonflow/axonflow-enterprise#4255). The examples: typed-policies finds its default document on its classpath, prints the template-omission report before it activates, and exits non-zero when a publication or activation it asked for is refused. The handshake example runs first everywhere, and every unknown_constraint sentence carries the getaxonflow/axonflow-enterprise#4247 follow-on. runtime-e2e/v11_examples makes six runs from outside the tree with no body file; runtime-e2e/typed_policies asserts the new members live. V11DeprecationsTest pins the exact 22 requests the id-bearing methods send. Closes #247 Signed-off-by: Saurabh Jain --- CHANGELOG.md | 28 ++- README.md | 12 +- .../getaxonflow/examples/PepHandshake.java | 16 +- examples/typed-policies/pom.xml | 9 + .../getaxonflow/examples/TypedPolicies.java | 128 +++++++++---- runtime-e2e/typed_policies/README.md | 10 +- .../TypedPolicyAuthoringTest.java | 101 ++++++++++- runtime-e2e/v11_examples/README.md | 36 +++- runtime-e2e/v11_examples/run.sh | 148 +++++++++++---- .../java/com/getaxonflow/sdk/AxonFlow.java | 26 ++- .../TypedPolicyRefusalException.java | 42 ++++- .../sdk/types/policies/TypedPolicyTypes.java | 142 ++++++++++++++- .../getaxonflow/sdk/TypedPoliciesTest.java | 168 +++++++++++++++++- .../getaxonflow/sdk/V11DeprecationsTest.java | 30 ++++ 14 files changed, 769 insertions(+), 127 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a787c83..0e4ea50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,17 +53,31 @@ and only a release that sends the handshake can declare it. to active. `client.typedPolicies()` reaches the six routes the agent proxies under `/api/v1/typed-policies`: `edition()`, `validate(document, fixtures)`, `publish(document, fixtures)`, `activate(digest, reason)`, `active()` and `system()`. Every refusal except a 401 is - a `TypedPolicyRefusalException` carrying the status, the platform's reason, any findings and - `Retry-After`; `active()` is empty when nothing is active. A client derived with `asUser` has - its own namespace. Rolling back and withdrawing are customer portal operations the agent does + a `TypedPolicyRefusalException` carrying the status, the platform's reason, any findings, the + policy a tier refusal names (`getPolicy()`) and `Retry-After`. `active()` is empty only for the + platform's `404 nothing_active`; any other 404 is a `TypedPolicyRefusalException` with status + 404, and a v11.0.0 platform answers a document store it cannot read with 503 + `storage_unavailable`, which throws it too (getaxonflow/axonflow-enterprise#4255). The answers + carry the edition's vocabulary (`getCatalogDigest()`, `getRegistryVersion()`, + `getCatalogFixture()`), the organization template controls a publication or an activation omits + (`getTemplateOmissions()`, a `TemplateOmissionReport`, or `getTemplateOmissionsUnavailable()` + when the platform could not report them), and each system control's `getName()`. + `TypedPolicySystemControl.getMandatory()` is a plain `boolean`, false when the platform omits + it. A client derived with `asUser` has its own namespace. Rolling back and withdrawing are customer portal operations the agent does not proxy, so the SDK has no method for either. - **Two runnable examples for the v11 platform (axonflow-enterprise#3746).** `examples/pep-handshake` declares an enforcement point's capabilities and decides with them, printing each verdict and its reasons; `examples/typed-policies` reads what the deployment may author, validates a document and, with - `AXONFLOW_TYPED_POLICY_PUBLISH=1`, publishes and activates it. Run the handshake example first: - after a document with an organization-scope constraint is activated, a decide that does not - supply the attribute the constraint conditions on is denied fail-closed with reasons - `["unknown_constraint"]`. + `AXONFLOW_TYPED_POLICY_PUBLISH=1`, publishes and activates it, printing the publication's + template-omission report before it activates: activating a document that omits the + organization template's controls removes them for the organization. It finds its default + document on its classpath, so it runs from any directory, and it exits non-zero when a + publication or activation it asked for is refused. Run the handshake example first: after a + document with an organization-scope constraint is activated, a decide that does not supply the + attribute the constraint conditions on is denied fail-closed with reasons + `["unknown_constraint"]`. From v11.0.0 the deny's first reason is that code, followed by one + naming each constraint it could not evaluate and the attribute it needed + (getaxonflow/axonflow-enterprise#4247). ### Deprecated diff --git a/README.md b/README.md index be4cebd..50fb352 100644 --- a/README.md +++ b/README.md @@ -426,8 +426,10 @@ TypedPolicySystemCorpus system = typed.system(); // the platform's own controls ``` - **Activation promotes.** A digest whose version does not advance past the active one is refused. Rolling back to an earlier document, and withdrawing the active one, are operations of the customer portal behind its session; the agent does not proxy them, so the SDK has no method for either. -- **The organization and the author are the ones your credentials resolve to.** The agent stamps both, and the platform overwrites any author named inside the document. A client derived with `asUser` has its own namespace, and its user token is the caller. -- **Refusals are typed.** Every refusal is a `TypedPolicyRefusalException` with the HTTP status, the platform's reason (such as `publication_refused`, `activation_refused` or `tier_limit`), any findings, and `getRetryAfter()` when the refusal is retryable; a 401 is the client's `AuthenticationException`. On an edition with separation of duties, publishing refuses with the finding code `APPROVER_IS_AUTHOR`: the route names no approver, and such a deployment approves in the customer portal. +- **Activation replaces the organization template.** Activating a document that omits the organization template's controls removes those controls for the organization. The template's controls carry the destructive-command blocks, DROP and TRUNCATE prevention and the blocking SQL-injection rows. `publish()` and `activate()` report which ones a document omits as `getTemplateOmissions()`, and the example prints that report. The publish fixture the example uses is a minimal example, not a starting point for production: it omits all of them. +- **The agent stamps the organization and the author.** The platform signs the caller as author whatever the document names. The organization is the one your credentials resolve to; on Community it is the deployment's (`ORG_ID`). A client derived with `asUser` has its own namespace, and its user token is the caller. +- **Refusals are typed.** Every refusal is a `TypedPolicyRefusalException` with the HTTP status, the platform's reason (such as `publication_refused`, `activation_refused` or `tier_limit`), any findings, `getPolicy()` for the policy a tier refusal names, and `getRetryAfter()` when the refusal is retryable; a 401 is the client's `AuthenticationException`. On an edition with separation of duties, publishing refuses with the finding code `APPROVER_IS_AUTHOR`: the route names no approver, and such a deployment approves in the customer portal. +- **`active()` is empty only for the platform's `nothing_active`.** Any other 404, from a platform before v11.0.0 or an endpoint that is not an agent, throws `TypedPolicyRefusalException` with status 404. A v11.0.0 platform answers a document store it cannot read with 503 `storage_unavailable`, which throws `TypedPolicyRefusalException` too (getaxonflow/axonflow-enterprise#4255). - **The document is the authoring model itself,** a `Map` rather than Java types, so a field the policy vocabulary gains is authorable without an SDK release. A null fixtures list sends none; an empty one sends `[]`. `validate` answers identically on every edition; the edition's boundary is applied when you publish. - **System controls are changed in the document, not per policy.** A v11.0.0 platform retires per-policy overrides: `createPolicyOverride` and `deletePolicyOverride` answer 409 `LEGACY_POLICY_WRITE_FROZEN` (agent-api's `PerPolicyOverrideRetired` response), and a system control is enabled, disabled or re-actioned in the organization's typed document, in its `system_controls` section. @@ -741,15 +743,15 @@ Runnable in this repository, against a live agent: ```bash mvn -q -DskipTests -DskipUnitTests=true install # put the SDK on the local classpath -AXONFLOW_AGENT_URL=http://localhost:8080 \ - mvn -q -f examples/authzen/pom.xml compile exec:java # AuthZEN: 9 steps, 4 of them refusals AXONFLOW_AGENT_URL=http://localhost:8080 \ mvn -q -f examples/pep-handshake/pom.xml compile exec:java # the PEP capability handshake AXONFLOW_AGENT_URL=http://localhost:8080 AXONFLOW_TYPED_POLICY_PUBLISH=1 \ mvn -q -f examples/typed-policies/pom.xml compile exec:java # validate, publish, activate +AXONFLOW_AGENT_URL=http://localhost:8080 \ + mvn -q -f examples/authzen/pom.xml compile exec:java # AuthZEN: 9 steps, 4 of them refusals ``` -Run `pep-handshake` before `typed-policies`. After a document with an organization-scope constraint is activated, a decide that does not supply the attribute the constraint conditions on is denied fail-closed with reasons ["unknown_constraint"]; supply the attribute or run the example on a fresh stack. On Enterprise the client id is the organization id and the secret its license key; a Community deployment accepts any credentials. +Run `pep-handshake` before `typed-policies`. After a document with an organization-scope constraint is activated, a decide that does not supply the attribute the constraint conditions on is denied fail-closed with reasons ["unknown_constraint"]; supply the attribute or run the example on a fresh stack. From v11.0.0 the deny's first reason is that code, followed by one naming each constraint it could not evaluate and the attribute it needed (getaxonflow/axonflow-enterprise#4247). On Enterprise the client id is the organization id and the secret its license key; a Community deployment accepts any credentials. ### Community Features diff --git a/examples/pep-handshake/src/main/java/com/getaxonflow/examples/PepHandshake.java b/examples/pep-handshake/src/main/java/com/getaxonflow/examples/PepHandshake.java index 5781395..1380c89 100644 --- a/examples/pep-handshake/src/main/java/com/getaxonflow/examples/PepHandshake.java +++ b/examples/pep-handshake/src/main/java/com/getaxonflow/examples/PepHandshake.java @@ -18,11 +18,11 @@ * platform reads from v10.4.0. * *

An enforcement point (a PEP) declares, on each governed call, the exact obligation types and - * schema versions it can discharge. On an Enterprise deployment an allow verdict carrying a - * mandatory obligation the declared set cannot discharge becomes a deny, so the enforcement point - * is never handed an instruction it would drop; a Community deployment records the declaration. - * From v11.0.0, on both editions, a decide under an organization's redact override refuses a caller - * that does not declare redaction. + * schema versions it can discharge. From v11.0.0, on every edition, the engine refuses a mandatory + * obligation the declaration cannot discharge: an organization's redact override on a decide + * refuses a caller that does not declare redaction. On an Enterprise deployment, in addition, an + * allow verdict carrying a mandatory obligation outside the declared set becomes a deny, so the + * enforcement point is never handed an instruction it would drop. * *

This example builds a declaration once for the client, derives a client presenting another one * (one process can be two enforcement points), and shows that a declaration the platform would @@ -30,8 +30,10 @@ * *

After a document with an organization-scope constraint is activated, a decide that does not * supply the attribute the constraint conditions on is denied fail-closed with reasons - * ["unknown_constraint"]; supply the attribute or run this example on a fresh stack. Run it before - * the typed-policies example, which publishes and activates such a document. + * ["unknown_constraint"]; supply the attribute or run this example on a fresh stack. From v11.0.0 + * the deny's first reason is that code, followed by one naming each constraint it could not + * evaluate and the attribute it needed (getaxonflow/axonflow-enterprise#4247). Run it before the + * typed-policies example, which publishes and activates such a document. * *

On Enterprise the client id is the organization id and the secret its license key; a Community * deployment accepts any credentials. diff --git a/examples/typed-policies/pom.xml b/examples/typed-policies/pom.xml index 4d9bd15..9a54ed6 100644 --- a/examples/typed-policies/pom.xml +++ b/examples/typed-policies/pom.xml @@ -29,6 +29,15 @@ + + + + ../../tests/fixtures + + typed_policy_publish_body.json + + + org.codehaus.mojo diff --git a/examples/typed-policies/src/main/java/com/getaxonflow/examples/TypedPolicies.java b/examples/typed-policies/src/main/java/com/getaxonflow/examples/TypedPolicies.java index 930b3e4..4f78c0c 100644 --- a/examples/typed-policies/src/main/java/com/getaxonflow/examples/TypedPolicies.java +++ b/examples/typed-policies/src/main/java/com/getaxonflow/examples/TypedPolicies.java @@ -9,9 +9,12 @@ import com.getaxonflow.sdk.exceptions.TypedPolicyRefusalException; import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.ActiveTypedPolicy; import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.AuthoringFinding; +import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.TemplateOmissionReport; import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.TypedAuthoringEdition; import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.TypedPolicyPublication; import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.TypedPolicyValidation; +import java.io.IOException; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; @@ -25,17 +28,26 @@ * pinned by its digest, and promoted to active. This example reads what the deployment may author, * validates a document and prints every finding, and shows the document in force. It publishes and * activates only when {@code AXONFLOW_TYPED_POLICY_PUBLISH=1}, because that changes the - * organization's active policy; a refusal prints the platform's reason and findings. + * organization's active policy. + * + *

Before it activates, it prints the publication's template-omission report: activating a + * document that omits the organization template's controls removes those controls for the + * organization. The default document is a minimal example, not a starting point for production: + * it omits all of them. A publication or activation that was asked for and refused prints the + * platform's reason and findings, and fails the run. * *

After a document with an organization-scope constraint is activated, a decide that does not * supply the attribute the constraint conditions on is denied fail-closed with reasons - * ["unknown_constraint"]; supply the attribute or run this example on a fresh stack. The default - * document is such a document, so run the pep-handshake example first. + * ["unknown_constraint"]; supply the attribute or run this example on a fresh stack. From v11.0.0 + * the deny's first reason is that code, followed by one naming each constraint it could not + * evaluate and the attribute it needed (getaxonflow/axonflow-enterprise#4247). The default document + * is such a document, so run the pep-handshake example first. * *

{@code AXONFLOW_TYPED_POLICY_BODY} names a JSON file holding {@code {"document": ..., - * "fixtures": [...]}}; the default is {@code tests/fixtures/typed_policy_publish_body.json}, read - * from the directory Maven runs in. On an edition with separation of duties, see the README's Typed - * policy authoring section for how a publication is approved. + * "fixtures": [...]}}. Without it the example reads the repository's {@code + * tests/fixtures/typed_policy_publish_body.json}, which its build puts on the classpath, so it runs + * from any directory. On an edition with separation of duties, see the README's Typed policy + * authoring section for how a publication is approved. * *

  * mvn -q -DskipTests -DskipUnitTests=true install   # from the repository root: the SDK on the local classpath
@@ -47,6 +59,9 @@
  */
 public final class TypedPolicies {
 
+  /** The default document, on the classpath. */
+  static final String DEFAULT_BODY = "/typed_policy_publish_body.json";
+
   private static int failures;
 
   private TypedPolicies() {}
@@ -84,17 +99,62 @@ private static void print(List findings) {
     }
   }
 
+  /** Prints a refusal: the platform's reason and any findings that refused it. */
+  private static void printRefusal(String what, TypedPolicyRefusalException refusal) {
+    System.out.println(
+        what
+            + ": HTTP "
+            + refusal.getStatus()
+            + " "
+            + refusal.getReason()
+            + ": "
+            + refusal.getMessage());
+    print(refusal.getFindings());
+  }
+
+  /**
+   * Prints which of the organization template's controls the document omits: activating it removes
+   * them for the organization.
+   */
+  private static void printTemplateOmissions(TypedPolicyPublication published) {
+    TemplateOmissionReport report = published.getTemplateOmissions();
+    if (report != null) {
+      System.out.println(
+          "template omissions: "
+              + report.getOmitted().size()
+              + " of "
+              + report.getOf()
+              + " template controls: "
+              + String.join(", ", report.getOmitted()));
+    } else if (published.getTemplateOmissionsUnavailable() != null) {
+      System.out.println(
+          "template omissions: unavailable: " + published.getTemplateOmissionsUnavailable());
+    } else {
+      System.out.println("template omissions: none");
+    }
+  }
+
+  /** The body {@code path} names, or the default document on the classpath when it is unset. */
+  static Map readBody(String path) throws IOException {
+    ObjectMapper mapper = new ObjectMapper();
+    TypeReference> type = new TypeReference>() {};
+    if (path != null && !path.isEmpty()) {
+      return mapper.readValue(Files.readAllBytes(Paths.get(path)), type);
+    }
+    try (InputStream in = TypedPolicies.class.getResourceAsStream(DEFAULT_BODY)) {
+      if (in == null) {
+        throw new IOException(
+            DEFAULT_BODY
+                + " is not on the classpath: build the example with its pom, or set"
+                + " AXONFLOW_TYPED_POLICY_BODY");
+      }
+      return mapper.readValue(in, type);
+    }
+  }
+
   public static void main(String[] args) throws Exception {
     String endpoint = System.getenv().getOrDefault("AXONFLOW_AGENT_URL", "http://localhost:8080");
-    String bodyPath =
-        System.getenv()
-            .getOrDefault(
-                "AXONFLOW_TYPED_POLICY_BODY", "tests/fixtures/typed_policy_publish_body.json");
-    Map body =
-        new ObjectMapper()
-            .readValue(
-                Files.readAllBytes(Paths.get(bodyPath)),
-                new TypeReference>() {});
+    Map body = readBody(System.getenv("AXONFLOW_TYPED_POLICY_BODY"));
     @SuppressWarnings("unchecked")
     Map document = (Map) body.get("document");
     @SuppressWarnings("unchecked")
@@ -137,29 +197,29 @@ public static void main(String[] args) throws Exception {
         step(
             "publish and activate",
             () -> {
+              TypedPolicyPublication published;
               try {
-                TypedPolicyPublication published = typed.publish(document, fixtures);
-                System.out.println(
-                    "published "
-                        + published.getDigest()
-                        + " (version "
-                        + published.getVersion()
-                        + ")");
-                typed.activate(published.getDigest(), "examples/typed-policies");
-                System.out.println("activated");
+                published = typed.publish(document, fixtures);
               } catch (TypedPolicyRefusalException refusal) {
                 // A refusal carries the platform's reason and, for a refused document, the findings
-                // that refused it.
-                System.out.println(
-                    "refused: HTTP "
-                        + refusal.getStatus()
-                        + " "
-                        + refusal.getReason()
-                        + ": "
-                        + refusal.getMessage());
-                print(refusal.getFindings());
-                throw refusal; // publishing was asked for, so a refusal fails the step
+                // that refused it. Publishing was asked for, so a refusal fails the step.
+                printRefusal("refused", refusal);
+                throw refusal;
+              }
+              System.out.println(
+                  "published " + published.getDigest() + " (version " + published.getVersion() + ")");
+              // Before activating: activating removes, for the organization, every template
+              // control the document omits.
+              printTemplateOmissions(published);
+              try {
+                typed.activate(published.getDigest(), "examples/typed-policies");
+              } catch (TypedPolicyRefusalException refusal) {
+                // Activation promotes: a document whose version does not advance past the active
+                // one is refused. Activating was asked for, so a refusal fails the step.
+                printRefusal("activation refused", refusal);
+                throw refusal;
               }
+              System.out.println("activated");
             });
       }
 
diff --git a/runtime-e2e/typed_policies/README.md b/runtime-e2e/typed_policies/README.md
index 4116a4f..4010e1c 100644
--- a/runtime-e2e/typed_policies/README.md
+++ b/runtime-e2e/typed_policies/README.md
@@ -6,10 +6,10 @@
 
 On a fresh stack, in order:
 
-1. Nothing is active yet: `active()` is empty from the platform's 404.
-2. `edition()` reports the deployment's boundary, and `system()` the shipped controls with their digest.
-3. The document the platform's own route test proves publishable validates clean, publishes to a digest, and activates.
-4. `active()` returns that document as the exact signed source. The platform overwrites the author: the document deliberately names `someone-else`, and the platform signs the caller the agent resolved.
+1. Nothing is active yet: `active()` is empty from the platform's `404 nothing_active`.
+2. `edition()` reports the deployment's boundary and names its vocabulary: `getCatalogDigest()`, a `getRegistryVersion()` above 0, and `getCatalogFixture()` false. `system()` returns the shipped controls with their digest, and reads each control's `getName()` and which are `getMandatory()`.
+3. The document the platform's own route test proves publishable validates clean, publishes to a digest, and activates. The publication reports the organization template controls the document omits, as `getTemplateOmissions()`: all of them, since the fixture is minimal. The activation reports the same omissions, beside the activation record.
+4. `active()` returns that document as the exact signed source, carrying the policies that were published. The platform overwrites the author: the document deliberately names `someone-else`, and the platform signs the caller the agent resolved (on Community, `Client` in the `axonflow-api-credential` realm, named by the client id).
 5. Activating the same digest again is a typed 409 `activation_refused`: activation promotes, and the version does not advance.
 6. Publishing with no fixtures is a typed 422 `publication_refused` whose message names the missing fixtures.
 7. A document naming an action the registry does not hold validates with the platform's rejecting finding (`ACTION_NOT_REGISTERED` on `grant.refund`), and publishing it is a typed 422 `document_refused` carrying that finding.
@@ -18,6 +18,8 @@ The document is `tests/fixtures/typed_policy_publish_body.json`, byte-identical
 
 ## What it does not prove
 
+A refusal's `getPolicy()` (a tier refusal) and the `getTemplateOmissionsUnavailable()` reasons are proven by the unit tests only: a Community stack crosses no tier ceiling, and reads its template.
+
 Rolling back and withdrawing are customer portal operations the agent does not proxy, so the SDK has no method for either. An edition with separation of duties refuses every publication through this route with `APPROVER_IS_AUTHOR`; the unit tests cover that refusal's shape, and this driver runs on Community, which has no separation of duties.
 
 ## Running it
diff --git a/runtime-e2e/typed_policies/TypedPolicyAuthoringTest.java b/runtime-e2e/typed_policies/TypedPolicyAuthoringTest.java
index b6a4667..6f68bb8 100644
--- a/runtime-e2e/typed_policies/TypedPolicyAuthoringTest.java
+++ b/runtime-e2e/typed_policies/TypedPolicyAuthoringTest.java
@@ -9,6 +9,7 @@
 import com.getaxonflow.sdk.exceptions.TypedPolicyRefusalException;
 import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.ActiveTypedPolicy;
 import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.AuthoringFinding;
+import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.TemplateOmissionReport;
 import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.TypedAuthoringEdition;
 import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.TypedPolicyActivation;
 import com.getaxonflow.sdk.types.policies.TypedPolicyTypes.TypedPolicyPublication;
@@ -20,6 +21,7 @@
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 import java.util.Optional;
 
 /**
@@ -27,14 +29,17 @@
  * client.typedPolicies()} against a real agent and orchestrator and asserts, on a fresh stack:
  *
  * 
    - *
  1. Nothing is active yet: {@code active()} is empty from the platform's 404. - *
  2. {@code edition()} reports the deployment's boundary, and {@code system()} the shipped - * controls with their digest. + *
  3. Nothing is active yet: {@code active()} is empty from the platform's 404 nothing_active. + *
  4. {@code edition()} reports the deployment's boundary and names its vocabulary (its digest, a + * registry version above 0, and not a test fixture), and {@code system()} the shipped controls + * with their digest, names and mandatory flags. *
  5. The document the platform's own route test proves publishable validates clean, publishes to - * a digest, and activates. - *
  6. {@code active()} returns that document as the exact signed source, with the AUTHOR - * overwritten by the platform: the document deliberately names someone-else, and the platform - * signs the caller the agent resolved. + * a digest reporting the template controls it omits (all of them: the fixture is minimal), and + * activates, reporting the same omissions beside the activation record. + *
  7. {@code active()} returns that document as the exact signed source, carrying the published + * policies, with the AUTHOR overwritten by the platform: the document deliberately names + * someone-else, and the platform signs the caller the agent resolved (on Community, the + * client id in the api-credential realm). *
  8. Activating the same digest again is a typed 409 ({@code activation_refused}). *
  9. Publishing with no fixtures is a typed 422 ({@code publication_refused}) whose message names * the missing fixtures. @@ -81,6 +86,22 @@ static Map member(Map m, String key) { return (Map) m.get(key); } + /** The ids of a document's policies, in order. */ + @SuppressWarnings("unchecked") + static List ids(Map document) { + List ids = new ArrayList<>(); + Map policy = member(document, "policy"); + Object policies = policy == null ? null : policy.get("policies"); + if (policies instanceof List) { + for (Object p : (List) policies) { + if (p instanceof Map && ((Map) p).get("id") != null) { + ids.add(((Map) p).get("id")); + } + } + } + return ids; + } + public static void main(String[] args) throws Exception { System.out.println("agent: " + AGENT); JsonNode body = MAPPER.readTree(Files.readAllBytes(Paths.get("tests/fixtures/typed_policy_publish_body.json"))); @@ -122,6 +143,22 @@ public static void main(String[] args) throws Exception { + (edition.getConstructs() == null ? null : edition.getConstructs().getEdition())); check(edition.isSuccess() && "organization".equals(edition.getRoot()), "edition() reports the root"); check(edition.getConstructs() != null, "edition() reports the construct boundary"); + System.out.println( + " vocabulary: catalog_digest=" + + edition.getCatalogDigest() + + " registry_version=" + + edition.getRegistryVersion() + + " catalog_fixture=" + + edition.getCatalogFixture()); + check( + edition.getCatalogDigest() != null && !edition.getCatalogDigest().isEmpty(), + "edition() names its vocabulary by digest"); + check( + edition.getRegistryVersion() != null && edition.getRegistryVersion() > 0, + "edition() names the deployment vocabulary's registry version"); + check( + Boolean.FALSE.equals(edition.getCatalogFixture()), + "edition() says the vocabulary is the deployment's, not a test fixture"); TypedPolicySystemCorpus system = typed.system(); System.out.println( " system: root=" @@ -137,6 +174,20 @@ public static void main(String[] args) throws Exception { check( system.getDigest() != null && !system.getDigest().isEmpty() && !system.getControls().isEmpty(), "system() returns the shipped corpus"); + long named = + system.getControls().stream() + .filter(c -> c.getName() != null && !c.getName().isEmpty()) + .count(); + long mandatory = system.getControls().stream().filter(c -> c.getMandatory()).count(); + System.out.println( + " system controls: " + + named + + " named, " + + mandatory + + " mandatory, of " + + system.getControls().size()); + check(named > 0, "system() reads each control's name"); + check(mandatory > 0, "system() reads which controls are mandatory"); System.out.println("== validate, publish, activate"); TypedPolicyValidation validation = typed.validate(document, fixtures); @@ -145,9 +196,29 @@ public static void main(String[] args) throws Exception { TypedPolicyPublication published = typed.publish(document, fixtures); System.out.println(" publish: digest=" + published.getDigest() + " version=" + published.getVersion()); check(published.getDigest() != null && !published.getDigest().isEmpty(), "publish() returns the artifact digest"); + TemplateOmissionReport omissions = published.getTemplateOmissions(); + System.out.println( + " template omissions: " + + (omissions == null + ? "none reported (unavailable: " + published.getTemplateOmissionsUnavailable() + ")" + : omissions.getOmitted().size() + " of " + omissions.getOf() + ": " + String.join(", ", omissions.getOmitted()))); + // The minimal publish fixture omits every organization template control. + check( + omissions != null + && omissions.getOf() != null + && omissions.getOf() > 0 + && omissions.getOmitted().size() == omissions.getOf(), + "publish() reports the template controls the document omits: all of them"); TypedPolicyActivation activation = typed.activate(published.getDigest(), "sdk-java runtime proof"); System.out.println(" activate: success=" + activation.isSuccess() + " activation=" + activation.getActivation()); check(activation.isSuccess(), "activate() promotes the digest"); + TemplateOmissionReport activated = activation.getTemplateOmissions(); + check( + activated != null + && omissions != null + && activated.getOmitted().equals(omissions.getOmitted()) + && Objects.equals(activated.getOf(), omissions.getOf()), + "activate() reports the same omissions, beside the activation record"); System.out.println("== the document in force"); Optional active = typed.active(); @@ -161,7 +232,21 @@ public static void main(String[] args) throws Exception { MAPPER.readValue(active.get().getSource(), MAP).equals(active.get().getDocument()), "its source is the signed source the document parses from"); check( - author != null && !"someone-else".equals(author.get("local")), + ids(active.get().getDocument()).equals(ids(document)), + "the document in force carries the policies that were published"); + // The author is the caller the agent stamped, never the name the request carries. On + // Community it is a client in the api-credential realm, named by the client id this proof + // presents. + boolean stamped = author != null && author.get("type") != null && author.get("local") != null; + if (edition.getConstructs() != null && "community".equals(edition.getConstructs().getEdition())) { + stamped = + stamped + && "Client".equals(author.get("type")) + && "axonflow-api-credential".equals(author.get("qualifier")) + && env("AXONFLOW_CLIENT_ID", "runtime-e2e").equals(author.get("local")); + } + check( + stamped && !"someone-else".equals(author.get("local")), "the platform signed the caller as author, not the name in the request"); } diff --git a/runtime-e2e/v11_examples/README.md b/runtime-e2e/v11_examples/README.md index 7681e91..f76fda1 100644 --- a/runtime-e2e/v11_examples/README.md +++ b/runtime-e2e/v11_examples/README.md @@ -1,25 +1,43 @@ # v11_examples -Real-stack proof that the two v11 examples run as the README says. `run.sh` builds the SDK from this tree, compiles `examples/pep-handshake` and `examples/typed-policies` against it, and runs them against a live Community agent in the README's order. Nothing is mocked. +Real-stack proof that the two v11 examples run as the README says. `run.sh` builds the SDK from this tree, compiles `examples/pep-handshake` and `examples/typed-policies` against it into a temporary directory, and runs them against a live Community agent in the README's order: the handshake example first. Every run starts from that directory, outside the tree, with no body file: `typed-policies` finds its default document on its classpath, as its own build puts it there. Telemetry is off. Nothing is mocked. + +## Precondition + +Before any run, `curl` waits up to 60 seconds for the agent's `/health` to answer `200`, then asks `GET /api/v1/typed-policies/active` and requires `404` with reason `nothing_active`: no typed document is active. Otherwise the leg stops with exit 2, because it needs a live agent, and it changes the organization's active policy, so it needs a fresh stack. The check is made outside the SDK, so an SDK regression is never reported as a stale stack. Exit 2 means only that; every other failure is exit 1. ## What it proves -| Step | Expected | +| Run | Expected | |---|---| -| `pep-handshake` on a fresh stack | exits 0; the first decide's verdict is `allow`; the declaration the platform would refuse fails in the client at `/pep_id`, before anything is sent | -| `typed-policies` with `AXONFLOW_TYPED_POLICY_PUBLISH=1` | exits 0; the document is published and activated | -| `pep-handshake` again, after the activation | printed as an observation, not asserted (below) | +| 1. `pep-handshake` | exits 0; the first decide's verdict is `allow`; the declaration the platform would refuse fails in the client at `/pep_id`, before anything is sent | +| 2. `typed-policies` without publishing, the README's default | exits 0; `active()` reads the platform's `nothing_active` as nothing active | +| 3. `typed-policies` with `AXONFLOW_TYPED_POLICY_PUBLISH=1` | exits 0; prints the publication's template-omission report before it activates; the document is published and activated | +| 4. `typed-policies` asked to publish a document the save-time checks reject | exits 1, printing the platform's typed `422 document_refused`: an example that was asked to publish and could not must not report success | +| 5. `typed-policies` publishing the same document again | the publication is accepted, and the activation is refused as a typed `409 activation_refused`; exits 1, since an example asked to activate and refused must not report success either | +| 6. `pep-handshake` again, after the activation | printed as an observation, not asserted (below) | + +Run 4 publishes a copy of `tests/fixtures/typed_policy_publish_body.json` with one action the registry does not contain (the same edit `runtime-e2e/typed_policies` makes), written to the temporary directory. It is refused before anything is admitted, so it changes nothing on the stack. + +Run 5 is refused because activation promotes. An artifact's digest covers its publication time, so publishing the same document again produces a new artifact, but its document version is the active one's, and a version that does not advance is not promoted. + +## Why the sixth run is an observation + +After a document with an organization-scope constraint is activated, a decide that does not supply the attribute the constraint conditions on is denied fail-closed with reasons `["unknown_constraint"]`; supply the attribute or run this example on a fresh stack. From v11.0.0 the deny's first reason is that code, followed by one naming each constraint it could not evaluate and the attribute it needed (getaxonflow/axonflow-enterprise#4247). The example's default document is such a document, so the sixth run shows that deny. It is the platform's by-design answer, not the SDK's, so this leg prints it rather than pinning it. It is why the README runs the handshake example first. + +A stack built before getaxonflow/axonflow-enterprise#4247 shows only the bare `["unknown_constraint"]`. -## Why the third run is an observation +## What it does not prove -After a document with an organization-scope constraint is activated, a decide that does not supply the attribute the constraint conditions on is denied fail-closed with reasons `["unknown_constraint"]`. The example's default document is such a document, so the third run shows that deny; it is the platform's by-design answer, not the SDK's, and this leg prints it rather than pinning it. That deny names no evaluated policy, which is getaxonflow/axonflow-enterprise#4227. It is why the README runs the handshake example first. +- **That the handshake reaches the wire.** A fresh Community stack allows the first decide with or without a declaration, and the `/pep_id` refusal happens in the client. +- **That the organization carries no other state.** The precondition proves no typed document is active. A recorded detection override, or a legacy per-policy override on a platform that still accepts them, would still apply. And on a stack built before getaxonflow/axonflow-enterprise#4255, an unreadable document store also answers `nothing_active`. ## Run -Community on the application database role (typed publishing needs an edition that lets a sole author publish). On a fresh stack: +Community on the application database role (typed publishing needs an edition that lets a sole author publish), on a fresh stack: ``` AXONFLOW_AGENT_URL=http://localhost:8080 ./runtime-e2e/v11_examples/run.sh ``` -Every step uses `AXONFLOW_CLIENT_ID` and `AXONFLOW_CLIENT_SECRET`, defaulting to `runtime-e2e` / `runtime-e2e-secret`; a Community deployment accepts any credentials. It exits non-zero on any failed assertion, and it changes the organization's active policy. +It leaves `AXONFLOW_CLIENT_ID` and `AXONFLOW_CLIENT_SECRET` unset, so the examples present no credentials, and on Community the organization is the deployment's (`ORG_ID`). It ignores any `AXONFLOW_TYPED_POLICY_PUBLISH` or `AXONFLOW_TYPED_POLICY_BODY` it was started with: each run sets its own. It exits 0 when every assertion passes, 1 when one fails, and 2 when the precondition does not hold (the agent does not answer, or a typed document is already active). It changes the organization's active policy. diff --git a/runtime-e2e/v11_examples/run.sh b/runtime-e2e/v11_examples/run.sh index effb8c2..4d3f15a 100755 --- a/runtime-e2e/v11_examples/run.sh +++ b/runtime-e2e/v11_examples/run.sh @@ -1,75 +1,159 @@ #!/usr/bin/env bash # Runs examples/pep-handshake and examples/typed-policies, built against the LOCAL SDK, against a -# LIVE Community agent, in the order the README gives, and asserts what each proves: +# LIVE Community agent, in the order the README gives, and asserts what each proves. Every example +# runs from a temporary directory, outside the tree, with no body file: typed-policies finds its +# default document on its classpath. # -# 1. pep-handshake on a fresh stack: exits 0, the first decide is allowed, and -# the declaration the platform would refuse fails in the client at /pep_id. -# 2. typed-policies with AXONFLOW_TYPED_POLICY_PUBLISH=1: exits 0, and the document is activated. -# 3. pep-handshake again: printed as an OBSERVATION, not asserted. After step 2 activates a +# Precondition, checked with curl rather than the SDK: the agent answers /health within 60 +# seconds, and no typed document is active (GET /api/v1/typed-policies/active answers 404 +# nothing_active). Otherwise the leg stops with exit 2: it needs a live agent, and it changes the +# organization's active policy, so it needs a fresh stack. Exit 2 means only that; every other +# failure is exit 1. +# +# 1. pep-handshake: exits 0, the first decide is allowed, and the declaration the platform would +# refuse fails in the client at /pep_id, before anything is sent. +# 2. typed-policies without publishing (the README's default): exits 0, and active() reads the +# platform's nothing_active as nothing active. +# 3. typed-policies with AXONFLOW_TYPED_POLICY_PUBLISH=1: exits 0, prints the publication's +# template-omission report BEFORE it activates, and the document is published and activated. +# 4. typed-policies asked to publish a document the save-time checks reject: exits 1, printing the +# platform's typed 422 document_refused. +# 5. typed-policies publishing the same document again: the publication is a new artifact of the +# same document version, so the activation is refused (a typed 409 activation_refused, since +# activation promotes), and the example exits 1. +# 6. pep-handshake again: printed as an OBSERVATION, not asserted. After run 3 activates a # document with an organization-scope constraint, a decide that does not supply the attribute -# the constraint conditions on is denied fail-closed with reasons ["unknown_constraint"]. +# the constraint conditions on is denied fail-closed with reasons ["unknown_constraint"]. From +# v11.0.0 the deny's first reason is that code, followed by one naming each constraint it could +# not evaluate and the attribute it needed (getaxonflow/axonflow-enterprise#4247). # -# It changes the organization's active policy (step 2), so run it on a fresh stack. +# Credentials are left unset, so the examples present none, and on Community the organization is +# the deployment's. # # AXONFLOW_AGENT_URL=http://localhost:8080 ./runtime-e2e/v11_examples/run.sh set -euo pipefail ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -cd "$ROOT" AGENT="${AXONFLOW_AGENT_URL:-http://localhost:8080}" -CLIENT_ID="${AXONFLOW_CLIENT_ID:-runtime-e2e}" -CLIENT_SECRET="${AXONFLOW_CLIENT_SECRET:-runtime-e2e-secret}" +# The credentials and the examples' own switches come only from the runs below, never from the +# environment the leg was started in. +unset AXONFLOW_CLIENT_ID AXONFLOW_CLIENT_SECRET AXONFLOW_TYPED_POLICY_PUBLISH AXONFLOW_TYPED_POLICY_BODY +OUT="$(mktemp -d "${TMPDIR:-/tmp}/v11-examples.XXXXXX")" +trap 'rm -rf "$OUT"' EXIT + +echo "=== precondition: the agent answers, and no typed document is active" +# A deadline, not an attempt count: an agent that accepts the connection and never answers must not +# hold the loop past 60 seconds. +healthy=0 +deadline=$((SECONDS + 60)) +while [ "$SECONDS" -lt "$deadline" ]; do + if [ "$(curl -s --max-time 5 -o /dev/null -w '%{http_code}' "$AGENT/health" || true)" = 200 ]; then + healthy=1 + break + fi + sleep 1 +done +if [ "$healthy" != 1 ]; then + echo "FAIL: $AGENT/health did not answer 200 within 60 seconds: start the stack first" + exit 2 +fi +code=$(curl -s --max-time 10 -o "$OUT/active.json" -w '%{http_code}' "$AGENT/api/v1/typed-policies/active" || true) +reason=$(grep -o '"reason": *"[^"]*"' "$OUT/active.json" 2>/dev/null | head -1 | sed 's/.*"\([^"]*\)"$/\1/' || true) +if [ "$code" != 404 ] || [ "$reason" != nothing_active ]; then + echo "FAIL: a typed document is already active, or the route did not answer nothing_active (HTTP $code, reason '$reason'): run this leg on a fresh stack" + exit 2 +fi +echo "ok: HTTP 404 nothing_active" + +cd "$ROOT" # This pom sets surefire's skipTests from its own skipUnitTests property, which overrides a # command-line -DskipTests, so -DskipTests alone still runs the whole unit suite. mvn -q -DskipTests -DskipUnitTests=true -Dfmt.skip=true package -mvn -q -DskipTests dependency:build-classpath -Dmdep.outputFile=target/v11-examples-cp.txt -SDK_JAR=$(ls target/axonflow-sdk-*.jar | grep -v sources | grep -v javadoc | head -1) +mvn -q -DskipTests dependency:build-classpath -Dmdep.outputFile="$OUT/cp.txt" +# The jar this build produced, by its version: a glob would also match a jar an earlier build left. +VERSION=$(awk '/axonflow-sdk<\/artifactId>/ { found = 1 } found && // { gsub(/.*|<\/version>.*/, ""); print; exit }' pom.xml) +SDK_JAR="$ROOT/target/axonflow-sdk-${VERSION}.jar" +[ -f "$SDK_JAR" ] || { echo "FAIL: no $SDK_JAR after the build"; exit 1; } # A binding so the SDK's WARN output is visible: the SDK depends on slf4j-api alone, and without a # binding its logger is a no-op. SLF4J_SIMPLE="${HOME}/.m2/repository/org/slf4j/slf4j-simple/2.0.12/slf4j-simple-2.0.12.jar" if [ ! -f "$SLF4J_SIMPLE" ]; then mvn -q dependency:get -Dartifact=org.slf4j:slf4j-simple:2.0.12 fi -CP="${SDK_JAR}:${SLF4J_SIMPLE}:$(cat target/v11-examples-cp.txt)" -OUT=target/v11-examples -rm -rf "$OUT" +CP="${SDK_JAR}:${SLF4J_SIMPLE}:$(cat "$OUT/cp.txt")" for ex in pep-handshake typed-policies; do - mkdir -p "$OUT/$ex" - javac -d "$OUT/$ex" -cp "$CP" examples/$ex/src/main/java/com/getaxonflow/examples/*.java + mkdir -p "$OUT/classes/$ex" + javac -d "$OUT/classes/$ex" -cp "$CP" "$ROOT"/examples/$ex/src/main/java/com/getaxonflow/examples/*.java done +# typed-policies' build puts its default document on its classpath (its pom's resources). +TYPED_CP="$OUT/classes/typed-policies:$ROOT/tests/fixtures:$CP" +HANDSHAKE_CP="$OUT/classes/pep-handshake:$CP" FAILURES=0 check() { if [ "$1" = ok ]; then echo "PASS: $2"; else echo "FAIL: $2"; FAILURES=$((FAILURES + 1)); fi } -# Runs one example with the given environment, captures its output, and returns its exit code. +# Runs one example from $OUT, outside the tree, with the given environment, prints its output, and +# returns its exit code. run_example() { - local ex=$1 main=$2 log=$3; shift 3 - set +e - env AXONFLOW_AGENT_URL="$AGENT" AXONFLOW_TELEMETRY=off AXONFLOW_CLIENT_ID="$CLIENT_ID" AXONFLOW_CLIENT_SECRET="$CLIENT_SECRET" "$@" \ - java -cp "$OUT/$ex:$CP" "$main" >"$log" 2>&1 - local rc=$? - set -e + local cp=$1 main=$2 log=$3; shift 3 + local rc=0 + (cd "$OUT" && env AXONFLOW_AGENT_URL="$AGENT" AXONFLOW_TELEMETRY=off "$@" java -cp "$cp" "$main") >"$log" 2>&1 || rc=$? grep -vE '^[[:space:]]*$| DEBUG | INFO ' "$log" | sed 's/^/ | /' return $rc } +# The first line number matching a pattern in a log, or 0. +line_of() { grep -n -m1 -E "$2" "$1" | cut -d: -f1 || true; } echo "=== 1. pep-handshake on a fresh stack" -rc=0; run_example pep-handshake com.getaxonflow.examples.PepHandshake "$OUT/1.log" || rc=$? +rc=0; run_example "$HANDSHAKE_CP" com.getaxonflow.examples.PepHandshake "$OUT/1.log" || rc=$? check "$([ $rc = 0 ] && echo ok)" "pep-handshake exits 0 (exit $rc)" first=$(grep -m1 -oE '^verdict=[a-z_]+' "$OUT/1.log" || true) check "$([ "$first" = verdict=allow ] && echo ok)" "the first decide is allowed on a fresh stack ($first)" check "$(grep -q '^refused at /pep_id: ' "$OUT/1.log" && echo ok)" \ "the declaration the platform would refuse fails in the client, at /pep_id, before anything is sent" -echo "=== 2. typed-policies: validate, publish and activate" -rc=0; run_example typed-policies com.getaxonflow.examples.TypedPolicies "$OUT/2.log" \ - AXONFLOW_TYPED_POLICY_PUBLISH=1 AXONFLOW_TYPED_POLICY_BODY="$ROOT/tests/fixtures/typed_policy_publish_body.json" || rc=$? +echo "=== 2. typed-policies without publishing, as the README runs it" +rc=0; run_example "$TYPED_CP" com.getaxonflow.examples.TypedPolicies "$OUT/2.log" || rc=$? +check "$([ $rc = 0 ] && echo ok)" "typed-policies exits 0 without publishing (exit $rc)" +check "$(grep -qx 'nothing is active' "$OUT/2.log" && echo ok)" \ + "active() reads the platform's nothing_active as nothing active" + +echo "=== 3. typed-policies with AXONFLOW_TYPED_POLICY_PUBLISH=1, as the README runs it" +rc=0; run_example "$TYPED_CP" com.getaxonflow.examples.TypedPolicies "$OUT/3.log" AXONFLOW_TYPED_POLICY_PUBLISH=1 || rc=$? check "$([ $rc = 0 ] && echo ok)" "typed-policies exits 0 (exit $rc)" -check "$(grep -qx 'activated' "$OUT/2.log" && echo ok)" "the document is published and activated" +omissions=$(line_of "$OUT/3.log" '^template omissions: ') +activated=$(line_of "$OUT/3.log" '^activated$') +check "$([ -n "$omissions" ] && [ -n "$activated" ] && [ "$omissions" -lt "$activated" ] && echo ok)" \ + "it prints the publication's template-omission report before it activates" +check "$([ -n "$activated" ] && echo ok)" "the document is published and activated" + +echo "=== 4. typed-policies asked to publish a document the save-time checks reject" +# The vendored body with one action the registry does not contain: the same edit +# runtime-e2e/typed_policies makes to it. +python3 - "$ROOT/tests/fixtures/typed_policy_publish_body.json" "$OUT/refused-body.json" <<'PY' +import json, sys +body = json.load(open(sys.argv[1])) +body["document"]["metadata"]["document_id"] = "v11-examples-refused" +body["document"]["policy"]["policies"][0]["actions"]["actions"][0]["local"] = "tool.not_registered" +json.dump(body, open(sys.argv[2], "w")) +PY +rc=0; run_example "$TYPED_CP" com.getaxonflow.examples.TypedPolicies "$OUT/4.log" \ + AXONFLOW_TYPED_POLICY_PUBLISH=1 AXONFLOW_TYPED_POLICY_BODY="$OUT/refused-body.json" || rc=$? +check "$([ $rc = 1 ] && echo ok)" "typed-policies exits 1 when the publication it asked for is refused (exit $rc)" +check "$(grep -q '^refused: HTTP 422 document_refused: ' "$OUT/4.log" && echo ok)" \ + "it prints the platform's typed 422 document_refused" + +echo "=== 5. typed-policies publishing the same document again" +rc=0; run_example "$TYPED_CP" com.getaxonflow.examples.TypedPolicies "$OUT/5.log" AXONFLOW_TYPED_POLICY_PUBLISH=1 || rc=$? +check "$([ $rc = 1 ] && echo ok)" "typed-policies exits 1 when the activation it asked for is refused (exit $rc)" +check "$(grep -q '^published ' "$OUT/5.log" && echo ok)" \ + "the second publication is accepted: a new artifact of the same document version" +check "$(grep -q '^activation refused: HTTP 409 activation_refused: ' "$OUT/5.log" && echo ok)" \ + "it prints the platform's typed 409 activation_refused" -echo "=== 3. OBSERVATION, not asserted: pep-handshake after the activation" -run_example pep-handshake com.getaxonflow.examples.PepHandshake "$OUT/3.log" || true -echo " observed: $(grep -m1 -oE '^verdict=.*' "$OUT/3.log" || echo 'no verdict printed')" +echo "=== 6. OBSERVATION, not asserted: pep-handshake after the activation" +run_example "$HANDSHAKE_CP" com.getaxonflow.examples.PepHandshake "$OUT/6.log" || true +echo " observed: $(grep -m1 -oE '^verdict=.*' "$OUT/6.log" || echo 'no verdict printed')" if [ "$FAILURES" -gt 0 ]; then echo; echo "FAIL: v11_examples ($FAILURES assertion(s))"; exit 1 diff --git a/src/main/java/com/getaxonflow/sdk/AxonFlow.java b/src/main/java/com/getaxonflow/sdk/AxonFlow.java index 921c1b8..e4e177e 100644 --- a/src/main/java/com/getaxonflow/sdk/AxonFlow.java +++ b/src/main/java/com/getaxonflow/sdk/AxonFlow.java @@ -201,8 +201,8 @@ private AxonFlow(AxonFlowConfig config) { && !config.getClientSecret().isEmpty() && (config.getClientId() == null || config.getClientId().isEmpty())) { throw new ConfigurationException( - "clientId is required when clientSecret is set. " - + "Set clientId to your tenant identity to avoid data being stored under the wrong tenant.", + "clientId is required when clientSecret is set. Set clientId to your tenant identity to" + + " avoid data being stored under the wrong tenant.", "clientId"); } @@ -7731,14 +7731,20 @@ public TypedPolicyActivation activate(String digest, String reason) { } /** - * The document in force, as the exact bytes that were signed, or empty when nothing is active - * (the platform's 404). + * The document in force, as the exact bytes that were signed, or empty when nothing is active. + * + *

    Nothing is active only when the platform says so: a 404 whose reason is {@code + * nothing_active}. Any other 404, from a platform before v11.0.0 or an endpoint that is not an + * agent, is a {@link TypedPolicyRefusalException} with status 404. A v11.0.0 platform answers a + * document store it cannot read with 503 {@code storage_unavailable}, which throws it too + * (getaxonflow/axonflow-enterprise#4255). * * @return the active document, if any + * @throws TypedPolicyRefusalException for any other refusal, a 404 included */ public Optional active() { TypedPolicyAnswer answer = sendTypedPolicy("GET", "/active", null); - if (answer.status == 404) { + if (answer.status == 404 && "nothing_active".equals(typedReason(answer))) { return Optional.empty(); } JsonNode node = typedPolicyObject(answer, "/active"); @@ -7841,6 +7847,7 @@ private AxonFlowException typedPolicyRefusal( answer.status, textMember(body, "reason"), textMember(body, "code"), + textMember(body, "policy"), findings, retryAfter); } @@ -7850,6 +7857,15 @@ private static String textMember(JsonNode body, String member) { return value != null && value.isTextual() ? value.asText() : null; } + /** The platform's {@code reason} in a JSON answer, or null. */ + private String typedReason(TypedPolicyAnswer answer) { + try { + return answer.body == null ? null : textMember(objectMapper.readTree(answer.body), "reason"); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + return null; + } + } + private T typedPolicyJson(String method, String route, Object payload, Class type) { return decodeTypedPolicy( typedPolicyObject(sendTypedPolicy(method, route, payload), route), route, type); diff --git a/src/main/java/com/getaxonflow/sdk/exceptions/TypedPolicyRefusalException.java b/src/main/java/com/getaxonflow/sdk/exceptions/TypedPolicyRefusalException.java index d906d0e..1c646a5 100644 --- a/src/main/java/com/getaxonflow/sdk/exceptions/TypedPolicyRefusalException.java +++ b/src/main/java/com/getaxonflow/sdk/exceptions/TypedPolicyRefusalException.java @@ -11,11 +11,11 @@ * *

    {@link #getStatus()} is the HTTP status and {@link #getReason()} the platform's reason, for * example {@code publication_refused} (422), {@code activation_refused} (409), {@code tier_limit} - * (402, with {@link #getCode()} naming the limit) or {@code artifact_cap} (429). {@link - * #getFindings()} holds the declared findings a refused publication or document carries, and {@link - * #getRetryAfter()} the seconds from {@code Retry-After} when the refusal is retryable. The message - * is the platform's own explanation. A 401 is an {@link AuthenticationException}, as on every other - * route. + * (402, with {@link #getCode()} naming the limit and {@link #getPolicy()} the policy that crossed + * it) or {@code artifact_cap} (429). {@link #getFindings()} holds the declared findings a refused + * publication or document carries, and {@link #getRetryAfter()} the seconds from {@code + * Retry-After} when the refusal is retryable. The message is the platform's own explanation. A 401 + * is an {@link AuthenticationException}, as on every other route. */ public class TypedPolicyRefusalException extends AxonFlowException { @@ -23,9 +23,30 @@ public class TypedPolicyRefusalException extends AxonFlowException { private final String reason; private final String code; + private final String policy; private final transient List findings; private final Integer retryAfter; + /** + * Creates a refusal that names no policy. + * + * @param message the platform's explanation + * @param status the HTTP status + * @param reason the platform's reason, or null + * @param code the platform's code, or null + * @param findings the declared findings, or null for none + * @param retryAfter the seconds from {@code Retry-After}, or null when there is none + */ + public TypedPolicyRefusalException( + String message, + int status, + String reason, + String code, + List findings, + Integer retryAfter) { + this(message, status, reason, code, null, findings, retryAfter); + } + /** * Creates a refusal. * @@ -33,6 +54,7 @@ public class TypedPolicyRefusalException extends AxonFlowException { * @param status the HTTP status * @param reason the platform's reason, or null * @param code the platform's code, or null + * @param policy the policy a tier refusal names, or null * @param findings the declared findings, or null for none * @param retryAfter the seconds from {@code Retry-After}, or null when there is none */ @@ -41,11 +63,13 @@ public TypedPolicyRefusalException( int status, String reason, String code, + String policy, List findings, Integer retryAfter) { super(message, status, code); this.reason = reason; this.code = code; + this.policy = policy; this.findings = findings == null ? Collections.emptyList() : Collections.unmodifiableList(findings); this.retryAfter = retryAfter; @@ -66,6 +90,14 @@ public String getCode() { return code; } + /** + * Returns the policy a tier refusal names, the one that crossed the ceiling, or null; an outage + * refusal (with {@code Retry-After}) names none. + */ + public String getPolicy() { + return policy; + } + /** Returns the declared findings the refusal carries; empty when there are none. */ public List getFindings() { return findings; diff --git a/src/main/java/com/getaxonflow/sdk/types/policies/TypedPolicyTypes.java b/src/main/java/com/getaxonflow/sdk/types/policies/TypedPolicyTypes.java index 4eda73b..17577ee 100644 --- a/src/main/java/com/getaxonflow/sdk/types/policies/TypedPolicyTypes.java +++ b/src/main/java/com/getaxonflow/sdk/types/policies/TypedPolicyTypes.java @@ -206,6 +206,15 @@ public static final class TypedAuthoringEdition { @JsonProperty("catalog") private final String catalog; + @JsonProperty("catalog_digest") + private final String catalogDigest; + + @JsonProperty("registry_version") + private final Integer registryVersion; + + @JsonProperty("catalog_fixture") + private final Boolean catalogFixture; + @JsonProperty("root") private final String root; @@ -225,6 +234,9 @@ public static final class TypedAuthoringEdition { public TypedAuthoringEdition( @JsonProperty("success") boolean success, @JsonProperty("catalog") String catalog, + @JsonProperty("catalog_digest") String catalogDigest, + @JsonProperty("registry_version") Integer registryVersion, + @JsonProperty("catalog_fixture") Boolean catalogFixture, @JsonProperty("root") String root, @JsonProperty("max_documents") Integer maxDocuments, @JsonProperty("constructs") EditionConstructReport constructs, @@ -232,6 +244,9 @@ public TypedAuthoringEdition( @JsonProperty("signing_key_custody") String signingKeyCustody) { this.success = success; this.catalog = catalog; + this.catalogDigest = catalogDigest; + this.registryVersion = registryVersion; + this.catalogFixture = catalogFixture; this.root = root; this.maxDocuments = maxDocuments; this.constructs = constructs; @@ -248,6 +263,24 @@ public String getCatalog() { return catalog; } + /** Returns the digest that identifies the vocabulary, or null when the platform sends none. */ + public String getCatalogDigest() { + return catalogDigest; + } + + /** Returns the vocabulary's registry version, or null when the platform sends none. */ + public Integer getRegistryVersion() { + return registryVersion; + } + + /** + * Returns whether the vocabulary is a test fixture rather than the deployment's, or null when + * the platform sends none. + */ + public Boolean getCatalogFixture() { + return catalogFixture; + } + /** Returns the one authority root this surface publishes under. */ public String getRoot() { return root; @@ -313,16 +346,39 @@ public static final class TypedPolicyPublication { @JsonProperty("findings") private final List findings; + @JsonProperty("template_omissions") + private final TemplateOmissionReport templateOmissions; + + @JsonProperty("template_omissions_unavailable") + private final String templateOmissionsUnavailable; + @JsonCreator public TypedPolicyPublication( @JsonProperty("success") boolean success, @JsonProperty("digest") String digest, @JsonProperty("version") Integer version, - @JsonProperty("findings") List findings) { + @JsonProperty("findings") List findings, + @JsonProperty("template_omissions") TemplateOmissionReport templateOmissions, + @JsonProperty("template_omissions_unavailable") String templateOmissionsUnavailable) { this.success = success; this.digest = digest; this.version = version; this.findings = list(findings); + this.templateOmissions = templateOmissions; + this.templateOmissionsUnavailable = templateOmissionsUnavailable; + } + + /** + * Returns the organization template's controls this document omits, which activating it removes + * for the organization; null when the platform sends no report. + */ + public TemplateOmissionReport getTemplateOmissions() { + return templateOmissions; + } + + /** Returns why the platform could not report the omissions, or null. */ + public String getTemplateOmissionsUnavailable() { + return templateOmissionsUnavailable; } public boolean isSuccess() { @@ -351,12 +407,22 @@ public static final class TypedPolicyActivation { @JsonProperty("activation") private final Map activation; + @JsonProperty("template_omissions") + private final TemplateOmissionReport templateOmissions; + + @JsonProperty("template_omissions_unavailable") + private final String templateOmissionsUnavailable; + @JsonCreator public TypedPolicyActivation( @JsonProperty("success") boolean success, - @JsonProperty("activation") Map activation) { + @JsonProperty("activation") Map activation, + @JsonProperty("template_omissions") TemplateOmissionReport templateOmissions, + @JsonProperty("template_omissions_unavailable") String templateOmissionsUnavailable) { this.success = success; this.activation = map(activation); + this.templateOmissions = templateOmissions; + this.templateOmissionsUnavailable = templateOmissionsUnavailable; } public boolean isSuccess() { @@ -366,6 +432,60 @@ public boolean isSuccess() { public Map getActivation() { return activation; } + + /** + * Returns the organization template's controls the activated document omits, beside the + * activation record rather than inside it; null when the platform sends no report. + */ + public TemplateOmissionReport getTemplateOmissions() { + return templateOmissions; + } + + /** Returns why the platform could not report the omissions, or null. */ + public String getTemplateOmissionsUnavailable() { + return templateOmissionsUnavailable; + } + } + + /** + * The organization template's controls a document omits: {@code omitted} of the template's {@code + * of} controls. Activating the document removes them for the organization. + */ + @JsonIgnoreProperties(ignoreUnknown = true) + public static final class TemplateOmissionReport { + @JsonProperty("omitted") + private final List omitted; + + @JsonProperty("of") + private final Integer of; + + @JsonProperty("message") + private final String message; + + @JsonCreator + public TemplateOmissionReport( + @JsonProperty("omitted") List omitted, + @JsonProperty("of") Integer of, + @JsonProperty("message") String message) { + this.omitted = list(omitted); + this.of = of; + this.message = message; + } + + /** Returns the omitted control ids; empty when none, or when the platform sends null. */ + public List getOmitted() { + return omitted; + } + + /** Returns how many controls the template has, or null. */ + public Integer getOf() { + return of; + } + + /** Returns the platform's summary, or null. */ + public String getMessage() { + return message; + } } /** @@ -396,6 +516,9 @@ public static final class TypedPolicySystemControl { @JsonProperty("id") private final String id; + @JsonProperty("name") + private final String name; + @JsonProperty("authority") private final String authority; @@ -403,7 +526,7 @@ public static final class TypedPolicySystemControl { private final String assurance; @JsonProperty("mandatory") - private final Boolean mandatory; + private final boolean mandatory; @JsonProperty("description") private final String description; @@ -414,15 +537,18 @@ public static final class TypedPolicySystemControl { @JsonCreator public TypedPolicySystemControl( @JsonProperty("id") String id, + @JsonProperty("name") String name, @JsonProperty("authority") String authority, @JsonProperty("assurance") String assurance, @JsonProperty("mandatory") Boolean mandatory, @JsonProperty("description") String description, @JsonProperty("obligations") List> obligations) { this.id = id; + this.name = name; this.authority = authority; this.assurance = assurance; - this.mandatory = mandatory; + // The platform omits mandatory when it is false. + this.mandatory = Boolean.TRUE.equals(mandatory); this.description = description; this.obligations = list(obligations); } @@ -431,6 +557,11 @@ public String getId() { return id; } + /** Returns the control's name, or null when the platform sends none. */ + public String getName() { + return name; + } + public String getAuthority() { return authority; } @@ -440,7 +571,8 @@ public String getAssurance() { return assurance; } - public Boolean getMandatory() { + /** Returns whether the control is mandatory; false when the platform omits it or sends null. */ + public boolean getMandatory() { return mandatory; } diff --git a/src/test/java/com/getaxonflow/sdk/TypedPoliciesTest.java b/src/test/java/com/getaxonflow/sdk/TypedPoliciesTest.java index c9e7de6..3850a55 100644 --- a/src/test/java/com/getaxonflow/sdk/TypedPoliciesTest.java +++ b/src/test/java/com/getaxonflow/sdk/TypedPoliciesTest.java @@ -110,6 +110,27 @@ void edition() { assertThat(edition.getConstructs().getReserved()).containsExactly("group_scope"); } + @Test + @DisplayName("the edition names its vocabulary, and reads it as absent when unsent") + void editionVocabulary() { + answering( + "GET", + "/edition", + 200, + "{\"success\":true,\"catalog\":\"deployment\",\"catalog_digest\":\"sha256:vocabulary\"," + + "\"registry_version\":2,\"catalog_fixture\":true}"); + TypedAuthoringEdition edition = client.typedPolicies().edition(); + assertThat(edition.getCatalogDigest()).isEqualTo("sha256:vocabulary"); + assertThat(edition.getRegistryVersion()).isEqualTo(2); + assertThat(edition.getCatalogFixture()).isTrue(); + reset(); + answering("GET", "/edition", 200, "{\"success\":true,\"catalog\":\"deployment\"}"); + TypedAuthoringEdition bare = client.typedPolicies().edition(); + assertThat(bare.getCatalogDigest()).isNull(); + assertThat(bare.getRegistryVersion()).isNull(); + assertThat(bare.getCatalogFixture()).isNull(); + } + @Test @DisplayName("validate sends the document and fixtures and returns every finding") void validate() { @@ -117,8 +138,8 @@ void validate() { "POST", "/validate", 200, - "{\"success\":false,\"findings\":[{\"code\":\"ACTION_NOT_REGISTERED\",\"severity\":\"reject\"," - + "\"policy_id\":\"grant.refund\",\"summary\":\"not registered\",\"detail\":\"tool.x\"}]}"); + "{\"success\":false,\"findings\":[{\"code\":\"ACTION_NOT_REGISTERED\",\"severity\":\"reject\",\"policy_id\":\"grant.refund\",\"summary\":\"not" + + " registered\",\"detail\":\"tool.x\"}]}"); TypedPolicyValidation validation = client.typedPolicies().validate(DOCUMENT, FIXTURES); verify( postRequestedFor(urlEqualTo(ROUTE + "/validate")) @@ -191,6 +212,71 @@ void activate() { .withRequestBody(equalToJson("{\"digest\":\"sha256:abc\",\"reason\":\"rollout\"}"))); } + @Test + @DisplayName("publish carries the template omission report") + void publishCarriesTheOmissionReport() { + answering( + "POST", + "/publish", + 200, + "{\"success\":true,\"digest\":\"sha256:abc\",\"version\":1,\"findings\":[]," + + "\"template_omissions\":{\"omitted\":[\"sys_a\",\"sys_b\"],\"of\":22," + + "\"message\":\"omits 2 of 22\"}}"); + TypedPolicyPublication published = client.typedPolicies().publish(DOCUMENT, FIXTURES); + assertThat(published.getTemplateOmissions().getOmitted()).containsExactly("sys_a", "sys_b"); + assertThat(published.getTemplateOmissions().getOf()).isEqualTo(22); + assertThat(published.getTemplateOmissions().getMessage()).isEqualTo("omits 2 of 22"); + assertThat(published.getTemplateOmissionsUnavailable()).isNull(); + } + + @Test + @DisplayName("a publication whose omission report is unavailable says why") + void aPublicationWhoseOmissionReportIsUnavailableSaysWhy() { + answering( + "POST", + "/publish", + 200, + "{\"success\":true,\"digest\":\"sha256:abc\",\"version\":1,\"template_omissions_unavailable\":\"the" + + " organization template could not be read\"}"); + TypedPolicyPublication published = client.typedPolicies().publish(DOCUMENT, FIXTURES); + assertThat(published.getTemplateOmissions()).isNull(); + assertThat(published.getTemplateOmissionsUnavailable()) + .isEqualTo("the organization template could not be read"); + } + + @Test + @DisplayName("activate carries the omission report beside the record, not inside it") + void activationCarriesTheOmissionReport() { + answering( + "POST", + "/activate", + 200, + "{\"success\":true,\"activation\":{\"digest\":\"sha256:abc\"}," + + "\"template_omissions\":{\"omitted\":[\"sys_a\"],\"of\":22," + + "\"message\":\"omits 1 of 22\"}}"); + TypedPolicyActivation activation = client.typedPolicies().activate(DIGEST, null); + assertThat(activation.getTemplateOmissions().getOmitted()).containsExactly("sys_a"); + assertThat(activation.getTemplateOmissions().getOf()).isEqualTo(22); + assertThat(activation.getTemplateOmissions().getMessage()).isEqualTo("omits 1 of 22"); + assertThat(activation.getTemplateOmissionsUnavailable()).isNull(); + assertThat(activation.getActivation()).doesNotContainKey("template_omissions"); + } + + @Test + @DisplayName("an activation whose omission report is unavailable says why") + void anActivationWhoseOmissionReportIsUnavailableSaysWhy() { + answering( + "POST", + "/activate", + 200, + "{\"success\":true,\"activation\":{\"digest\":\"sha256:abc\"},\"template_omissions_unavailable\":\"the" + + " organization template could not be read\"}"); + TypedPolicyActivation activation = client.typedPolicies().activate(DIGEST, null); + assertThat(activation.getTemplateOmissions()).isNull(); + assertThat(activation.getTemplateOmissionsUnavailable()) + .isEqualTo("the organization template could not be read"); + } + @Test @DisplayName("active keeps the exact bytes that were signed") void activeKeepsTheSignedBytes() { @@ -203,16 +289,41 @@ void activeKeepsTheSignedBytes() { } @Test - @DisplayName("nothing active is empty") + @DisplayName("nothing active is empty: the platform's 404 nothing_active") void nothingActive() { answering( "GET", "/active", 404, - "{\"success\":false,\"reason\":\"no_active_policy\",\"error\":\"nothing is active\"}"); + "{\"success\":false,\"reason\":\"nothing_active\",\"error\":\"nothing is active\"}"); assertThat(client.typedPolicies().active()).isEmpty(); } + @Test + @DisplayName("any other 404 on active is a typed refusal, not nothing active") + void anotherActive404IsARefusal() { + // A platform before v11.0.0, or an endpoint that is not an agent, is not "nothing active". + String[][] cases = { + {"404 page not found", null}, + { + "{\"success\":false,\"reason\":\"no_such_endpoint\",\"error\":\"no route\"}", + "no_such_endpoint" + }, + }; + for (String[] c : cases) { + reset(); + answering("GET", "/active", 404, c[0]); + assertThatThrownBy(() -> client.typedPolicies().active()) + .as(c[0]) + .isInstanceOfSatisfying( + TypedPolicyRefusalException.class, + e -> { + assertThat(e.getStatus()).isEqualTo(404); + assertThat(e.getReason()).isEqualTo(c[1]); + }); + } + } + @Test @DisplayName("system") void system() { @@ -236,6 +347,26 @@ void system() { assertThat(system.getDocument()).containsEntry("api_version", "v1"); } + @Test + @DisplayName("a system control names itself, and is not mandatory when unsaid") + void aControlNamesItselfAndIsNotMandatoryWhenUnsaid() { + answering( + "GET", + "/system", + 200, + "{\"success\":true,\"system\":{\"controls\":[{\"id\":\"sys.a\",\"name\":\"Block DROP" + + " TABLE\"," + + "\"mandatory\":true},{\"id\":\"sys.b\"},{\"id\":\"sys.c\",\"mandatory\":null}]}}"); + TypedPolicySystemCorpus system = client.typedPolicies().system(); + // Compared by value against false, so a drift back to a nullable Boolean fails here. + assertThat(system.getControls()) + .extracting(c -> c.getId(), c -> c.getName(), c -> c.getMandatory()) + .containsExactly( + tuple("sys.a", "Block DROP TABLE", true), + tuple("sys.b", null, false), + tuple("sys.c", null, false)); + } + // ------------------------------------------------------------------------- // Refusals // ------------------------------------------------------------------------- @@ -264,6 +395,9 @@ private void call(String operation) { case "edition": client.typedPolicies().edition(); break; + case "active": + client.typedPolicies().active(); + break; default: throw new IllegalArgumentException(operation); } @@ -304,7 +438,7 @@ void everyRefusalIsTyped() { 402, "tier_limit", "ERR_TIER_LIMIT_ORG_ROOT_POLICY", - ",\"code\":\"ERR_TIER_LIMIT_ORG_ROOT_POLICY\"", + ",\"code\":\"ERR_TIER_LIMIT_ORG_ROOT_POLICY\",\"policy\":\"grant.refund\"", Map.of(), List.of(), null @@ -325,6 +459,9 @@ void everyRefusalIsTyped() { {"activate", "POST", 409, "activation_refused", null, "", Map.of(), List.of(), null}, {"validate", "POST", 503, "catalog_not_configured", null, "", Map.of(), List.of(), null}, {"edition", "GET", 404, "no_such_endpoint", null, "", Map.of(), List.of(), null}, + // A v11.0.0 platform answers a document store it cannot read with 503 storage_unavailable, + // not with nothing_active (getaxonflow/axonflow-enterprise#4255). + {"active", "GET", 503, "storage_unavailable", null, "", Map.of(), List.of(), null}, }; for (Object[] c : cases) { String operation = (String) c[0]; @@ -351,6 +488,10 @@ void everyRefusalIsTyped() { .collect(Collectors.toList())) .isEqualTo(findings); assertThat(e.getRetryAfter()).isEqualTo(c[8]); + // A tier refusal names the policy that crossed the ceiling; an outage refusal + // (with Retry-After) names none. + assertThat(e.getPolicy()) + .isEqualTo(((String) c[5]).contains("\"policy\"") ? "grant.refund" : null); }); } } @@ -409,6 +550,21 @@ void nullCollectionsReadAsEmpty() { 200, "{\"success\":true,\"digest\":\"sha256:abc\",\"version\":1,\"findings\":null}"); assertThat(client.typedPolicies().publish(DOCUMENT, FIXTURES).getFindings()).isEmpty(); + answering( + "POST", + "/publish", + 200, + "{\"success\":true,\"digest\":\"sha256:abc\",\"template_omissions\":null}"); + assertThat(client.typedPolicies().publish(DOCUMENT, FIXTURES).getTemplateOmissions()).isNull(); + answering( + "POST", + "/publish", + 200, + "{\"success\":true,\"digest\":\"sha256:abc\"," + + "\"template_omissions\":{\"omitted\":null,\"of\":22,\"message\":\"m\"}}"); + assertThat( + client.typedPolicies().publish(DOCUMENT, FIXTURES).getTemplateOmissions().getOmitted()) + .isEmpty(); answering( "GET", "/edition", @@ -450,7 +606,7 @@ void aDerivedClientsIdentity() { answering("POST", "/validate", 200, "{\"success\":true}"); answering("POST", "/publish", 200, "{\"success\":true,\"digest\":\"sha256:abc\"}"); answering("POST", "/activate", 200, "{\"success\":true}"); - answering("GET", "/active", 404, "{}"); + answering("GET", "/active", 404, "{\"success\":false,\"reason\":\"nothing_active\"}"); answering("GET", "/system", 200, "{\"success\":true}"); Consumer everyRoute = c -> { diff --git a/src/test/java/com/getaxonflow/sdk/V11DeprecationsTest.java b/src/test/java/com/getaxonflow/sdk/V11DeprecationsTest.java index 2fe1ed4..ba6fe52 100644 --- a/src/test/java/com/getaxonflow/sdk/V11DeprecationsTest.java +++ b/src/test/java/com/getaxonflow/sdk/V11DeprecationsTest.java @@ -278,6 +278,36 @@ void everyIdBearingMethodReportsItsTemplateOnce() { catchThrowable(() -> axonflow.toggleDynamicPolicy(id, true)); } + // Each call sent its own request, with its id in its path, so a method that shares its template + // with another (updateDynamicPolicy and toggleDynamicPolicy are both PUT + // /api/v1/dynamic-policies/{id}) is seen to send: exactly 22 requests, in call order. + List templates = + List.of( + "GET /api/v1/static-policies/{id}", + "PUT /api/v1/static-policies/{id}", + "DELETE /api/v1/static-policies/{id}", + "PATCH /api/v1/static-policies/{id}", + "GET /api/v1/static-policies/{id}/versions", + "POST /api/v1/static-policies/{id}/override", + "DELETE /api/v1/static-policies/{id}/override", + "GET /api/v1/dynamic-policies/{id}", + "PUT /api/v1/dynamic-policies/{id}", + "DELETE /api/v1/dynamic-policies/{id}", + "PUT /api/v1/dynamic-policies/{id}"); + List expected = new ArrayList<>(); + for (String id : List.of("pol_a", "pol_b")) { + for (String template : templates) { + expected.add(template.replace("{id}", id)); + } + } + // WireMock lists serve events newest first. + List served = + getAllServeEvents().stream() + .map(e -> e.getRequest().getMethod().getName() + " " + e.getRequest().getUrl()) + .collect(Collectors.toList()); + Collections.reverse(served); + assertThat(served).containsExactlyElementsOf(expected); + // Eleven methods, twice each; updateDynamicPolicy and toggleDynamicPolicy share PUT. assertThat(reported) .extracting(PlatformRouteDeprecation::getRoute) From 45c2ad4cc05690863c02e0e09494d667900b59a0 Mon Sep 17 00:00:00 2001 From: Saurabh Jain Date: Mon, 14 Sep 2026 09:33:06 +0200 Subject: [PATCH 2/3] fix(typed-policies): fold review: the leg uses the example's resources runtime-e2e/v11_examples compiled the examples with javac and put tests/fixtures on the classpath itself, so it never exercised the resource block in examples/typed-policies/pom.xml that the README's mvn command relies on. The leg now runs that pom's resources phase alone (compiling with it would resolve the released SDK, not this tree's) and puts its target/classes on the classpath, so a wrong path in the pom fails run 2. Run 3's check requires a report ("template omissions: N of M template controls"), not only the prefix. A javac or mvn failure exits 1: javac exits 2 on a usage error, and the leg keeps exit 2 for its precondition. Signed-off-by: Saurabh Jain --- runtime-e2e/v11_examples/run.sh | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/runtime-e2e/v11_examples/run.sh b/runtime-e2e/v11_examples/run.sh index 4d3f15a..725cc57 100755 --- a/runtime-e2e/v11_examples/run.sh +++ b/runtime-e2e/v11_examples/run.sh @@ -67,8 +67,13 @@ echo "ok: HTTP 404 nothing_active" cd "$ROOT" # This pom sets surefire's skipTests from its own skipUnitTests property, which overrides a # command-line -DskipTests, so -DskipTests alone still runs the whole unit suite. -mvn -q -DskipTests -DskipUnitTests=true -Dfmt.skip=true package -mvn -q -DskipTests dependency:build-classpath -Dmdep.outputFile="$OUT/cp.txt" +mvn -q -DskipTests -DskipUnitTests=true -Dfmt.skip=true package || { echo "FAIL: the SDK build"; exit 1; } +mvn -q -DskipTests dependency:build-classpath -Dmdep.outputFile="$OUT/cp.txt" || { echo "FAIL: the classpath"; exit 1; } +# typed-policies' default document, put on its classpath by the example's own build (its pom's +# resources), so a wrong path there fails run 2. Only the resources phase runs: compiling the example +# with its pom would resolve the released SDK, not this tree's. +mvn -q -f "$ROOT/examples/typed-policies/pom.xml" resources:resources || { echo "FAIL: the example's resources"; exit 1; } +[ -f "$ROOT/examples/typed-policies/target/classes/typed_policy_publish_body.json" ] || { echo "FAIL: the example's build did not put its default document on its classpath"; exit 1; } # The jar this build produced, by its version: a glob would also match a jar an earlier build left. VERSION=$(awk '/axonflow-sdk<\/artifactId>/ { found = 1 } found && // { gsub(/.*|<\/version>.*/, ""); print; exit }' pom.xml) SDK_JAR="$ROOT/target/axonflow-sdk-${VERSION}.jar" @@ -77,15 +82,15 @@ SDK_JAR="$ROOT/target/axonflow-sdk-${VERSION}.jar" # binding its logger is a no-op. SLF4J_SIMPLE="${HOME}/.m2/repository/org/slf4j/slf4j-simple/2.0.12/slf4j-simple-2.0.12.jar" if [ ! -f "$SLF4J_SIMPLE" ]; then - mvn -q dependency:get -Dartifact=org.slf4j:slf4j-simple:2.0.12 + mvn -q dependency:get -Dartifact=org.slf4j:slf4j-simple:2.0.12 || { echo "FAIL: slf4j-simple"; exit 1; } fi CP="${SDK_JAR}:${SLF4J_SIMPLE}:$(cat "$OUT/cp.txt")" for ex in pep-handshake typed-policies; do mkdir -p "$OUT/classes/$ex" - javac -d "$OUT/classes/$ex" -cp "$CP" "$ROOT"/examples/$ex/src/main/java/com/getaxonflow/examples/*.java + # A javac usage error exits 2, which here means only the precondition: map every build failure to 1. + javac -d "$OUT/classes/$ex" -cp "$CP" "$ROOT"/examples/$ex/src/main/java/com/getaxonflow/examples/*.java || { echo "FAIL: javac $ex"; exit 1; } done -# typed-policies' build puts its default document on its classpath (its pom's resources). -TYPED_CP="$OUT/classes/typed-policies:$ROOT/tests/fixtures:$CP" +TYPED_CP="$OUT/classes/typed-policies:$ROOT/examples/typed-policies/target/classes:$CP" HANDSHAKE_CP="$OUT/classes/pep-handshake:$CP" FAILURES=0 @@ -101,7 +106,7 @@ run_example() { grep -vE '^[[:space:]]*$| DEBUG | INFO ' "$log" | sed 's/^/ | /' return $rc } -# The first line number matching a pattern in a log, or 0. +# The first line number matching a pattern in a log, or empty when none does. line_of() { grep -n -m1 -E "$2" "$1" | cut -d: -f1 || true; } echo "=== 1. pep-handshake on a fresh stack" @@ -121,7 +126,7 @@ check "$(grep -qx 'nothing is active' "$OUT/2.log" && echo ok)" \ echo "=== 3. typed-policies with AXONFLOW_TYPED_POLICY_PUBLISH=1, as the README runs it" rc=0; run_example "$TYPED_CP" com.getaxonflow.examples.TypedPolicies "$OUT/3.log" AXONFLOW_TYPED_POLICY_PUBLISH=1 || rc=$? check "$([ $rc = 0 ] && echo ok)" "typed-policies exits 0 (exit $rc)" -omissions=$(line_of "$OUT/3.log" '^template omissions: ') +omissions=$(line_of "$OUT/3.log" '^template omissions: [0-9]+ of [0-9]+ template controls: ') activated=$(line_of "$OUT/3.log" '^activated$') check "$([ -n "$omissions" ] && [ -n "$activated" ] && [ "$omissions" -lt "$activated" ] && echo ok)" \ "it prints the publication's template-omission report before it activates" From 4fa4bd95a003c8684bd33b10185a63df93b4976b Mon Sep 17 00:00:00 2001 From: Saurabh Jain Date: Mon, 14 Sep 2026 09:40:13 +0200 Subject: [PATCH 3/3] fix(typed-policies): fold review 2: clear the example's resources first Maven skips a missing resource directory without an error, and target/ is ignored, so after one run of runtime-e2e/v11_examples the document the example's resources phase copied stays behind, and a wrong path in examples/typed-policies/pom.xml would pass the check on every later run. The leg now clears that output before the resources phase, so a wrong path fails the leg before any run (not run 2, as the previous commit's message says). Signed-off-by: Saurabh Jain --- runtime-e2e/v11_examples/run.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/runtime-e2e/v11_examples/run.sh b/runtime-e2e/v11_examples/run.sh index 725cc57..9f11b07 100755 --- a/runtime-e2e/v11_examples/run.sh +++ b/runtime-e2e/v11_examples/run.sh @@ -70,8 +70,11 @@ cd "$ROOT" mvn -q -DskipTests -DskipUnitTests=true -Dfmt.skip=true package || { echo "FAIL: the SDK build"; exit 1; } mvn -q -DskipTests dependency:build-classpath -Dmdep.outputFile="$OUT/cp.txt" || { echo "FAIL: the classpath"; exit 1; } # typed-policies' default document, put on its classpath by the example's own build (its pom's -# resources), so a wrong path there fails run 2. Only the resources phase runs: compiling the example -# with its pom would resolve the released SDK, not this tree's. +# resources), so a wrong path there fails the leg before any run. Only the resources phase runs: +# compiling the example with its pom would resolve the released SDK, not this tree's. The output is +# cleared first: a missing resource directory is skipped without an error, so a document an earlier +# run left there would otherwise satisfy the check below. +rm -rf "$ROOT/examples/typed-policies/target/classes" mvn -q -f "$ROOT/examples/typed-policies/pom.xml" resources:resources || { echo "FAIL: the example's resources"; exit 1; } [ -f "$ROOT/examples/typed-policies/target/classes/typed_policy_publish_body.json" ] || { echo "FAIL: the example's build did not put its default document on its classpath"; exit 1; } # The jar this build produced, by its version: a glob would also match a jar an earlier build left.