From c0f56a6b5baca9355285752241f023d71a998b83 Mon Sep 17 00:00:00 2001 From: Saurabh Jain Date: Sun, 13 Sep 2026 16:19:44 +0200 Subject: [PATCH] feat(policies): deprecate the v11 policy simulation methods A v11.0.0 platform deprecates /api/v1/policies/simulate, /impact-report and /conflicts and removes them in v11.1: every response carries X-AxonFlow-Removed-In: v11.1 and a successor Link naming /api/v1/typed-policies, plus an RFC 9745 Deprecation header once v11.0.0 is tagged. simulatePolicies, getPolicyImpactReport and detectPolicyConflicts, and their Async forms, are now @Deprecated with Javadoc saying so. They keep answering until v11.1, but on a v11.0.0 platform their results come from the legacy engine, which no longer decides, so they do not predict what the platform enforces. createPolicyOverride and deletePolicyOverride now document that a v11.0.0 platform retires per-policy overrides and refuses both with LegacyPolicyWriteFrozenException. A stamped route that carries an id is reported once, as its route template, not once per id: the eleven methods that put an id in a static- or dynamic-policy path tag the request with its template, and the once-per-route record keys on it. A source census fails any new such call site that carries no template. The runtime leg v11_deprecations drives the deprecations against a live Evaluation-or-above stack. Refs getaxonflow/axonflow-enterprise#3746 Signed-off-by: Saurabh Jain --- CHANGELOG.md | 20 +- README.md | 8 + runtime-e2e/v11_deprecations/README.md | 30 ++ .../v11_deprecations/V11DeprecationsTest.java | 278 +++++++++++++++ runtime-e2e/v11_deprecations/run.sh | 17 + .../java/com/getaxonflow/sdk/AxonFlow.java | 141 +++++++- .../com/getaxonflow/sdk/AxonFlowConfig.java | 12 +- .../sdk/PlatformRouteDeprecation.java | 10 +- .../getaxonflow/sdk/PolicySimulationTest.java | 1 + .../getaxonflow/sdk/V11DeprecationsTest.java | 332 ++++++++++++++++++ 10 files changed, 825 insertions(+), 24 deletions(-) create mode 100644 runtime-e2e/v11_deprecations/README.md create mode 100644 runtime-e2e/v11_deprecations/V11DeprecationsTest.java create mode 100755 runtime-e2e/v11_deprecations/run.sh create mode 100644 src/test/java/com/getaxonflow/sdk/V11DeprecationsTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 235be020..6a4d7dec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,8 +27,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`AxonFlowConfig.Builder.onRouteDeprecation(...)`.** When the platform marks a route a call used as deprecated (`X-AxonFlow-Removed-In` or an RFC 9745 `Deprecation` header, with the successor from `Link: <...>; rel="successor-version"`), the SDK reports it once per route: to this - listener when it is set, otherwise to the log at WARN. From v11.0.0 the legacy static- and - dynamic-policy reads carry it. + listener when it is set, otherwise to the log at WARN. A route whose path carries an id is + reported once, as its template (`GET /api/v1/static-policies/{id}`), not once per id. From + v11.0.0 the legacy policy routes carry it: the static- and dynamic-policy routes and the policy + simulation routes. - **The v11.0.0 PEP capability handshake (axonflow-enterprise#3746).** An enforcement point declares the obligation types and schema versions it can discharge with `PEPHandshake.of(...)` and `PEPCapability.of(...)`, presented as `X-Axonflow-PEP-Handshake` on every call to a plane @@ -49,6 +51,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 its own namespace. Rolling back and withdrawing are customer portal operations the agent does not proxy, so the SDK has no method for either. +### Deprecated + +- **The v11.0.0 policy simulation routes (axonflow-enterprise#3746).** `simulatePolicies`, + `getPolicyImpactReport` and `detectPolicyConflicts`, and their `Async` forms, are deprecated: a + v11.0.0 platform deprecates `/api/v1/policies/simulate`, `/impact-report` and `/conflicts` and + removes them in v11.1, and stamps every response with `X-AxonFlow-Removed-In: v11.1` and a + successor `Link` naming `/api/v1/typed-policies` (plus an RFC 9745 `Deprecation` header once + v11.0.0 is tagged), which `AxonFlowConfig.Builder.onRouteDeprecation` reports once per route. + They keep answering until then, but on a v11.0.0 platform their results + come from the legacy engine, which no longer decides, so they do not predict what the platform + enforces. `createPolicyOverride` and `deletePolicyOverride` now document that + a v11.0.0 platform retires per-policy overrides and refuses both with + `LegacyPolicyWriteFrozenException`. + ### Fixed - **A static-policy read no longer fails on a category the SDK does not know diff --git a/README.md b/README.md index 6f6c16cd..f7bd8df3 100644 --- a/README.md +++ b/README.md @@ -416,6 +416,14 @@ TypedPolicySystemCorpus system = typed.system(); // the platform's own controls - **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. - **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. +## v11.0.0 deprecations + +A v11.0.0 platform deprecates its legacy policy routes and removes them in v11.1. Every response from them carries `X-AxonFlow-Removed-In: v11.1` and a successor `Link` naming `/api/v1/typed-policies`, plus an RFC 9745 `Deprecation` header once v11.0.0 is tagged, and the client reports each such route once through `AxonFlowConfig.Builder.onRouteDeprecation` (or logs it once at WARN when that is unset). A client derived with `asUser` shares that record, so a route is reported once per client family, and a route whose path carries an id is reported as its template, such as `POST /api/v1/static-policies/{id}/override`. + +- **Policy simulation.** `simulatePolicies`, `getPolicyImpactReport` and `detectPolicyConflicts`, and their `Async` forms, are `@Deprecated` and keep answering until v11.1, but on a v11.0.0 platform their results come from the legacy engine, which no longer decides, so they do not predict what the platform enforces; policy is authored and tested through `client.typedPolicies()` (see [Typed policy authoring](#typed-policy-authoring-v1100)). +- **The other legacy policy routes.** The SDK's other methods on `/api/v1/static-policies` and `/api/v1/dynamic-policies` reach routes the platform stamps and removes the same way (it stamps its other legacy families too). The client reports each at runtime; those methods are not marked `@Deprecated` in this release. +- **Per-policy overrides.** A v11.0.0 platform retires them: `createPolicyOverride` and `deletePolicyOverride` throw a `LegacyPolicyWriteFrozenException` (409, `LEGACY_POLICY_WRITE_FROZEN`) whose message names the typed policy route, where a system control is changed in the organization's typed document. + ## Reading decisions: who is asking decides what comes back `explainDecision` and `listDecisions` — and the audit reads — are scoped to the diff --git a/runtime-e2e/v11_deprecations/README.md b/runtime-e2e/v11_deprecations/README.md new file mode 100644 index 00000000..8fb3d240 --- /dev/null +++ b/runtime-e2e/v11_deprecations/README.md @@ -0,0 +1,30 @@ +# v11_deprecations + +Real-stack proof of the v11.0.0 deprecations through the SDK. `V11DeprecationsTest.java` calls the three policy simulation methods the SDK marks `@Deprecated` (`simulatePolicies`, `detectPolicyConflicts` and `getPolicyImpactReport`) and the two retired override writes against a real v11 agent and orchestrator, and reads what `AxonFlowConfig.Builder.onRouteDeprecation` reports. Nothing is mocked. + +## What it proves + +| Step | Expected | +|---|---| +| `simulatePolicies`, `detectPolicyConflicts` | keep answering; each route reported exactly once, with `X-AxonFlow-Removed-In: v11.1` and the successor exactly `/api/v1/typed-policies` from the `Link` | +| `getPolicyImpactReport` | a non-2xx refusal (see below), reported once the same way | +| the RFC 9745 `Deprecation` header | absent, or `@`: the platform adds it once v11.0.0 is tagged and omits it until then | +| a second call of each, and a call from a client derived with `asUser` | nothing new reported: once per route per client family | +| `createPolicyOverride`, `deletePolicyOverride` | `LegacyPolicyWriteFrozenException`, 409 `LEGACY_POLICY_WRITE_FROZEN`, whose message names `/api/v1/typed-policies`; the leg prints the platform's message | +| two static policies read by id | reported once, as `GET /api/v1/static-policies/{id}`; no report names a concrete id | +| a wrong secret | refused with the SDK's `AuthenticationException` (401), not swallowed | + +## Why the impact report is proved on its signal, not on a result + +The platform evaluates the named policy from the organization's tenant policies. A fresh organization has none, and a v11 platform refuses to create one (the legacy write freeze), so on a fresh v11 stack the call names a policy that cannot exist. The leg asserts only that the platform refuses it with a non-2xx (today a `500`, tracked in getaxonflow/axonflow-enterprise#4223), so a fix to that status leaves this leg green. The deprecation is stamped whatever the handler answers, and that is what this leg proves for the route. On an organization that still holds legacy tenant policies, the call returns its report until v11.1. + +## Run + +The simulation routes are registered from the Evaluation licence up, so boot an enterprise stack from the platform's main (`scripts/setup-e2e-testing.sh production-posture`). Then, from the repository root, with the credentials that script writes: + +``` +set -a; source /tmp/axonflow-e2e-env.sh; set +a +AXONFLOW_AGENT_URL=http://localhost:8080 ./runtime-e2e/v11_deprecations/run.sh +``` + +It exits non-zero on any failed assertion. It writes nothing the platform keeps: both override writes are refused. diff --git a/runtime-e2e/v11_deprecations/V11DeprecationsTest.java b/runtime-e2e/v11_deprecations/V11DeprecationsTest.java new file mode 100644 index 00000000..4d8c91d0 --- /dev/null +++ b/runtime-e2e/v11_deprecations/V11DeprecationsTest.java @@ -0,0 +1,278 @@ +// Copyright 2026 AxonFlow +// SPDX-License-Identifier: MIT + +import com.getaxonflow.sdk.AxonFlow; +import com.getaxonflow.sdk.AxonFlowConfig; +import com.getaxonflow.sdk.PlatformRouteDeprecation; +import com.getaxonflow.sdk.exceptions.AuthenticationException; +import com.getaxonflow.sdk.exceptions.AxonFlowException; +import com.getaxonflow.sdk.exceptions.LegacyPolicyWriteFrozenException; +import com.getaxonflow.sdk.simulation.ImpactReportInput; +import com.getaxonflow.sdk.simulation.ImpactReportRequest; +import com.getaxonflow.sdk.simulation.PolicyConflictResponse; +import com.getaxonflow.sdk.simulation.SimulatePoliciesRequest; +import com.getaxonflow.sdk.simulation.SimulatePoliciesResponse; +import com.getaxonflow.sdk.types.policies.PolicyTypes.CreatePolicyOverrideRequest; +import com.getaxonflow.sdk.types.policies.PolicyTypes.OverrideAction; +import com.getaxonflow.sdk.types.policies.PolicyTypes.StaticPolicy; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Real-stack proof of the v11.0.0 deprecations through the SDK. + * + *

Drives the built SDK against a live v11 agent and orchestrator on the Evaluation licence or + * above and asserts: + * + *

    + *
  1. {@code simulatePolicies} and {@code detectPolicyConflicts} keep answering, and {@code + * getPolicyImpactReport} is refused with a non-2xx on a fresh v11 organization (never pinned + * to one status: getaxonflow/axonflow-enterprise#4223). + *
  2. Each of the three routes is reported exactly once through {@code onRouteDeprecation}, with + * {@code X-AxonFlow-Removed-In: v11.1}, the successor exactly {@code /api/v1/typed-policies}, + * and a {@code Deprecation} header absent or {@code @}. + *
  3. A second call of each, and a client derived with {@code asUser}, report nothing new. + *
  4. {@code createPolicyOverride} and {@code deletePolicyOverride} throw {@code + * LegacyPolicyWriteFrozenException} (409) naming the typed route; the platform's message is + * printed. + *
  5. Two static policies read by id are reported once, as {@code GET + * /api/v1/static-policies/{id}}, and no report names a concrete id. + *
  6. A wrong secret is refused with the SDK's {@code AuthenticationException} (401). + *
+ * + *

Nothing is mocked, and nothing the platform keeps is written: both override writes are + * refused. Run with {@code run.sh}. + */ +@SuppressWarnings("deprecation") +public class V11DeprecationsTest { + + static final String AGENT = + System.getenv().getOrDefault("AXONFLOW_AGENT_URL", "http://localhost:8080"); + static final String SUCCESSOR = "/api/v1/typed-policies"; + static final Pattern DEPRECATION = Pattern.compile("@[0-9]+"); + static final String[] ROUTES = {"simulate", "conflicts", "impact-report"}; + static final List FAILURES = new ArrayList<>(); + + static void check(boolean ok, String description) { + System.out.println((ok ? "PASS: " : "FAIL: ") + description); + if (!ok) { + FAILURES.add(description); + } + } + + static String env(String name) { + String value = System.getenv(name); + return value == null || value.isEmpty() ? null : value; + } + + static AxonFlow client( + String clientId, String clientSecret, Consumer listener) { + return AxonFlow.create( + AxonFlowConfig.builder() + .endpoint(AGENT) + .clientId(clientId) + .clientSecret(clientSecret) + .onRouteDeprecation(listener) + .build()); + } + + static SimulatePoliciesRequest simulate() { + return SimulatePoliciesRequest.builder() + .query("Transfer $50,000 to external account") + .requestType("execute") + .build(); + } + + /** The impact report a fresh v11 organization refuses; returns the answer's status. */ + static int impactStatus(AxonFlow client) { + try { + client.getPolicyImpactReport( + ImpactReportRequest.builder() + .policyId("sys_sqli_drop_table") + .inputs(List.of(ImpactReportInput.builder().query("DROP TABLE customers").build())) + .build()); + return 200; + } catch (AxonFlowException e) { + return e.getStatusCode(); + } + } + + static void expectFrozen(String label, Runnable write) { + try { + write.run(); + check(false, label + " was accepted; a v11.0.0 platform refuses it"); + } catch (LegacyPolicyWriteFrozenException e) { + System.out.println(" platform message: " + e.getMessage()); + check( + e.getStatusCode() == 409 + && LegacyPolicyWriteFrozenException.CODE.equals(e.getErrorCode()) + && e.getMessage().contains(SUCCESSOR), + label + + " throws LegacyPolicyWriteFrozenException (" + + e.getStatusCode() + + ", " + + e.getErrorCode() + + ") naming " + + SUCCESSOR); + } catch (AxonFlowException e) { + check( + false, + label + + " threw " + + e.getClass().getSimpleName() + + " (" + + e.getStatusCode() + + ", " + + e.getErrorCode() + + "): " + + e.getMessage()); + } + } + + public static void main(String[] args) { + String clientId = env("AXONFLOW_CLIENT_ID"); + String clientSecret = env("AXONFLOW_CLIENT_SECRET"); + String userToken = env("AXONFLOW_USER_TOKEN"); + System.out.println("agent: " + AGENT); + if (clientId == null || clientSecret == null || userToken == null) { + System.out.println( + "FAIL: set AXONFLOW_CLIENT_ID, AXONFLOW_CLIENT_SECRET and AXONFLOW_USER_TOKEN" + + " (source the stack's env file)"); + System.exit(2); + } + List reported = Collections.synchronizedList(new ArrayList<>()); + AxonFlow client = client(clientId, clientSecret, reported::add); + + try { + // 1. The two routes that still answer, and the one a fresh organization refuses. + SimulatePoliciesResponse simulated = client.simulatePolicies(simulate()); + // Reaching this check means the call answered 2xx: a refusal throws, and the outer catch + // records it as a FAIL. + check( + true, + "simulatePolicies() returned (allowed=" + + simulated.isAllowed() + + ", " + + simulated.getTotalPolicies() + + " policies evaluated)"); + PolicyConflictResponse conflicts = client.detectPolicyConflicts(); + check( + true, + "detectPolicyConflicts() returned (" + + conflicts.getConflictCount() + + " conflicts in " + + conflicts.getTotalPolicies() + + " policies)"); + int status = impactStatus(client); + check( + status >= 400, + "getPolicyImpactReport() is refused with a non-2xx on a fresh v11 organization (" + + status + + ")"); + + // 2. Each route reported exactly once, with the platform's own signal. + for (String route : ROUTES) { + String key = "POST /api/v1/policies/" + route; + List matches = + reported.stream().filter(d -> key.equals(d.getRoute())).collect(Collectors.toList()); + check(matches.size() == 1, key + " is reported exactly once (" + matches.size() + ")"); + if (matches.isEmpty()) { + continue; + } + PlatformRouteDeprecation d = matches.get(0); + System.out.println(" reported: " + d); + check( + SUCCESSOR.equals(d.getSuccessor()), + key + ": the successor is exactly " + SUCCESSOR + " (" + d.getSuccessor() + ")"); + check("v11.1".equals(d.getRemovedIn()), key + ": removed in v11.1 (" + d.getRemovedIn() + ")"); + check( + d.getDeprecation() == null || DEPRECATION.matcher(d.getDeprecation()).matches(), + key + ": Deprecation absent or @ (" + d.getDeprecation() + ")"); + } + check(reported.size() == ROUTES.length, "nothing else is reported (" + reported.size() + ")"); + + // 3. Once per route per client family: a second call, and a derived client, add nothing. + int before = reported.size(); + client.simulatePolicies(simulate()); + client.detectPolicyConflicts(); + impactStatus(client); + AxonFlow derived = client.asUser(userToken); + derived.simulatePolicies(simulate()); + derived.detectPolicyConflicts(); + impactStatus(derived); + check( + reported.size() == before, + "a second call of each, and a client derived with asUser, report nothing new (" + + (reported.size() - before) + + " new)"); + + // 4. The retired per-policy override writes. + expectFrozen( + "createPolicyOverride", + () -> + client.createPolicyOverride( + "sys_sqli_drop_table", + CreatePolicyOverrideRequest.builder() + .actionOverride(OverrideAction.WARN) + .overrideReason("runtime-e2e v11_deprecations") + .build())); + expectFrozen( + "deletePolicyOverride", () -> client.deletePolicyOverride("sys_sqli_drop_table")); + + // 6. A stamped route that carries an id is reported once, as its template: two real static + // policies read by id add one report, and no report names a concrete id. + List listed = client.listStaticPolicies(); + check(listed.size() >= 2, "listStaticPolicies() returned policies to read by id (" + listed.size() + ")"); + if (listed.size() >= 2) { + List ids = List.of(listed.get(0).getId(), listed.get(1).getId()); + for (String id : ids) { + try { + client.getStaticPolicy(id); + } catch (AxonFlowException e) { + System.out.println(" getStaticPolicy(" + id + ") answered " + e.getStatusCode()); + } + } + long byTemplate = + reported.stream().filter(d -> "GET /api/v1/static-policies/{id}".equals(d.getRoute())).count(); + check( + byTemplate == 1, + "two static policies read by id are reported once, as GET /api/v1/static-policies/{id} (" + + byTemplate + + ")"); + check( + reported.stream().noneMatch(d -> ids.stream().anyMatch(id -> d.getRoute().contains(id))), + "no report names a concrete id"); + } + + // 5. An auth failure stays observable: a wrong secret is the SDK's AuthenticationException. + try { + client(clientId, "not-the-licence", d -> {}).simulatePolicies(simulate()); + check(false, "a wrong secret was accepted"); + } catch (AuthenticationException e) { + check( + e.getStatusCode() == 401, + "a wrong secret is refused with AuthenticationException " + e.getStatusCode()); + } catch (AxonFlowException e) { + check( + false, + "a wrong secret threw " + + e.getClass().getSimpleName() + + " (" + + e.getStatusCode() + + "), not AuthenticationException"); + } + } catch (Exception e) { + check(false, "the run threw " + e.getClass().getSimpleName() + ": " + e.getMessage()); + } + + if (!FAILURES.isEmpty()) { + System.out.println("\nFAIL: v11_deprecations (" + FAILURES.size() + " assertion(s))"); + System.exit(1); + } + System.out.println("\nPASS: v11_deprecations"); + } +} diff --git a/runtime-e2e/v11_deprecations/run.sh b/runtime-e2e/v11_deprecations/run.sh new file mode 100755 index 00000000..9012d080 --- /dev/null +++ b/runtime-e2e/v11_deprecations/run.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Drives runtime-e2e/v11_deprecations/V11DeprecationsTest against a LIVE v11 stack on the +# Evaluation licence or above (the simulation routes are registered from Evaluation up), using the +# LOCAL SDK build. +# +# set -a; source /tmp/axonflow-e2e-env.sh; set +a +# AXONFLOW_AGENT_URL=http://localhost:8080 ./runtime-e2e/v11_deprecations/run.sh +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +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-deprecations-cp.txt +SDK_JAR=$(ls target/axonflow-sdk-*.jar | grep -v sources | grep -v javadoc | head -1) +CP="${SDK_JAR}:$(cat target/v11-deprecations-cp.txt)" +AXONFLOW_TELEMETRY=off java -cp "$CP" runtime-e2e/v11_deprecations/V11DeprecationsTest.java diff --git a/src/main/java/com/getaxonflow/sdk/AxonFlow.java b/src/main/java/com/getaxonflow/sdk/AxonFlow.java index 075c76d9..921c1b8b 100644 --- a/src/main/java/com/getaxonflow/sdk/AxonFlow.java +++ b/src/main/java/com/getaxonflow/sdk/AxonFlow.java @@ -507,6 +507,24 @@ private Response executeHttp(OkHttpClient client, Request request) throws java.i return response; } + /** + * The route a request was built for, with its path parameters as placeholders. The once-per-route + * deprecation record keys on it, so a stamped route that carries an id is reported once, as its + * template, rather than once per id. + */ + private static final class RouteTemplate { + private final String path; + + private RouteTemplate(String path) { + this.path = path; + } + } + + /** Tags a request with the route template it was built for. */ + private static Request withRoute(Request request, String template) { + return request.newBuilder().tag(RouteTemplate.class, new RouteTemplate(template)).build(); + } + private static final Pattern SUCCESSOR_LINK = Pattern.compile("<([^>]*)>\\s*;\\s*rel=\"?successor-version\"?", Pattern.CASE_INSENSITIVE); @@ -522,7 +540,9 @@ private void noteRouteDeprecation(Request request, Response response) { if (deprecation == null && removedIn == null) { return; } - String route = request.method() + " " + request.url().encodedPath(); + RouteTemplate template = request.tag(RouteTemplate.class); + String route = + request.method() + " " + (template != null ? template.path : request.url().encodedPath()); if (!reportedRouteDeprecations.add(route)) { return; } @@ -1608,7 +1628,16 @@ public CompletableFuture updateCircuitBreake * @return the simulation result * @throws NullPointerException if request is null * @throws AxonFlowException if the request fails - */ + * @deprecated A v11.0.0 platform deprecates {@code POST /api/v1/policies/simulate} and removes it + * in v11.1. Every response carries {@code X-AxonFlow-Removed-In: v11.1} and a successor + * {@code Link} naming {@code /api/v1/typed-policies}, plus an RFC 9745 {@code Deprecation} + * header once v11.0.0 is tagged, and the client reports the route once through {@link + * AxonFlowConfig.Builder#onRouteDeprecation}. Policy is authored and tested through the typed + * policy methods ({@link #typedPolicies()}). It keeps answering until v11.1; on a v11.0.0 + * platform its result comes from the legacy engine, which no longer decides, so it does not + * predict what the platform enforces. + */ + @Deprecated public SimulatePoliciesResponse simulatePolicies(SimulatePoliciesRequest request) { Objects.requireNonNull(request, "request cannot be null"); @@ -1632,7 +1661,10 @@ public SimulatePoliciesResponse simulatePolicies(SimulatePoliciesRequest request * * @param request the simulation request * @return a future containing the simulation result + * @deprecated Reaches the deprecated {@code POST /api/v1/policies/simulate}; see {@link + * #simulatePolicies(SimulatePoliciesRequest)}. */ + @Deprecated public CompletableFuture simulatePoliciesAsync( SimulatePoliciesRequest request) { return CompletableFuture.supplyAsync(() -> simulatePolicies(request), asyncExecutor); @@ -1663,7 +1695,16 @@ public CompletableFuture simulatePoliciesAsync( * @return the impact report * @throws NullPointerException if request is null * @throws AxonFlowException if the request fails - */ + * @deprecated A v11.0.0 platform deprecates {@code POST /api/v1/policies/impact-report} and + * removes it in v11.1. Every response carries {@code X-AxonFlow-Removed-In: v11.1} and a + * successor {@code Link} naming {@code /api/v1/typed-policies}, plus an RFC 9745 {@code + * Deprecation} header once v11.0.0 is tagged, and the client reports the route once through + * {@link AxonFlowConfig.Builder#onRouteDeprecation}. Policy is authored and tested through + * the typed policy methods ({@link #typedPolicies()}). It keeps answering until v11.1; on a + * v11.0.0 platform its result comes from the legacy engine, which no longer decides, so it + * does not predict what the platform enforces. + */ + @Deprecated public ImpactReportResponse getPolicyImpactReport(ImpactReportRequest request) { Objects.requireNonNull(request, "request cannot be null"); @@ -1687,7 +1728,10 @@ public ImpactReportResponse getPolicyImpactReport(ImpactReportRequest request) { * * @param request the impact report request * @return a future containing the impact report + * @deprecated Reaches the deprecated {@code POST /api/v1/policies/impact-report}; see {@link + * #getPolicyImpactReport(ImpactReportRequest)}. */ + @Deprecated public CompletableFuture getPolicyImpactReportAsync( ImpactReportRequest request) { return CompletableFuture.supplyAsync(() -> getPolicyImpactReport(request), asyncExecutor); @@ -1710,7 +1754,10 @@ public CompletableFuture getPolicyImpactReportAsync( * * @return the conflict detection result * @throws AxonFlowException if the request fails + * @deprecated Reaches the deprecated {@code POST /api/v1/policies/conflicts}; see {@link + * #detectPolicyConflicts(String)}. */ + @Deprecated public PolicyConflictResponse detectPolicyConflicts() { return detectPolicyConflicts(null); } @@ -1735,7 +1782,16 @@ public PolicyConflictResponse detectPolicyConflicts() { * @return the conflict detection result * @throws IllegalArgumentException if policyId is non-null and empty * @throws AxonFlowException if the request fails - */ + * @deprecated A v11.0.0 platform deprecates {@code POST /api/v1/policies/conflicts} and removes + * it in v11.1. Every response carries {@code X-AxonFlow-Removed-In: v11.1} and a successor + * {@code Link} naming {@code /api/v1/typed-policies}, plus an RFC 9745 {@code Deprecation} + * header once v11.0.0 is tagged, and the client reports the route once through {@link + * AxonFlowConfig.Builder#onRouteDeprecation}. Policy is authored and tested through the typed + * policy methods ({@link #typedPolicies()}). It keeps answering until v11.1; on a v11.0.0 + * platform its result comes from the legacy engine, which no longer decides, so it does not + * predict what the platform enforces. + */ + @Deprecated public PolicyConflictResponse detectPolicyConflicts(String policyId) { if (policyId != null && policyId.isEmpty()) { throw new IllegalArgumentException("policyId cannot be empty"); @@ -1766,7 +1822,10 @@ public PolicyConflictResponse detectPolicyConflicts(String policyId) { * Asynchronously scans all active policies for conflicts. * * @return a future containing the conflict detection result + * @deprecated Reaches the deprecated {@code POST /api/v1/policies/conflicts}; see {@link + * #detectPolicyConflicts(String)}. */ + @Deprecated public CompletableFuture detectPolicyConflictsAsync() { return CompletableFuture.supplyAsync(() -> detectPolicyConflicts(), asyncExecutor); } @@ -1776,7 +1835,10 @@ public CompletableFuture detectPolicyConflictsAsync() { * * @param policyId the policy ID to check for conflicts, or null to scan all policies * @return a future containing the conflict detection result + * @deprecated Reaches the deprecated {@code POST /api/v1/policies/conflicts}; see {@link + * #detectPolicyConflicts(String)}. */ + @Deprecated public CompletableFuture detectPolicyConflictsAsync(String policyId) { return CompletableFuture.supplyAsync(() -> detectPolicyConflicts(policyId), asyncExecutor); } @@ -3496,7 +3558,10 @@ public StaticPolicy getStaticPolicy(String policyId) { return retryExecutor.execute( () -> { - Request httpRequest = buildRequest("GET", "/api/v1/static-policies/" + policyId, null); + Request httpRequest = + withRoute( + buildRequest("GET", "/api/v1/static-policies/" + policyId, null), + "/api/v1/static-policies/{id}"); try (Response response = executeHttp(httpClient, httpRequest)) { return parseResponse(response, StaticPolicy.class); } @@ -3536,7 +3601,10 @@ public StaticPolicy updateStaticPolicy(String policyId, UpdateStaticPolicyReques return retryExecutor.execute( () -> { - Request httpRequest = buildRequest("PUT", "/api/v1/static-policies/" + policyId, request); + Request httpRequest = + withRoute( + buildRequest("PUT", "/api/v1/static-policies/" + policyId, request), + "/api/v1/static-policies/{id}"); try (Response response = executeHttp(httpClient, httpRequest)) { return parseResponse(response, StaticPolicy.class); } @@ -3554,7 +3622,10 @@ public void deleteStaticPolicy(String policyId) { retryExecutor.execute( () -> { - Request httpRequest = buildRequest("DELETE", "/api/v1/static-policies/" + policyId, null); + Request httpRequest = + withRoute( + buildRequest("DELETE", "/api/v1/static-policies/" + policyId, null), + "/api/v1/static-policies/{id}"); try (Response response = executeHttp(httpClient, httpRequest)) { if (!response.isSuccessful() && response.code() != 204) { handleErrorResponse(response); @@ -3578,7 +3649,10 @@ public StaticPolicy toggleStaticPolicy(String policyId, boolean enabled) { return retryExecutor.execute( () -> { Map body = Map.of("enabled", enabled); - Request httpRequest = buildPatchRequest("/api/v1/static-policies/" + policyId, body); + Request httpRequest = + withRoute( + buildPatchRequest("/api/v1/static-policies/" + policyId, body), + "/api/v1/static-policies/{id}"); try (Response response = executeHttp(httpClient, httpRequest)) { return parseResponse(response, StaticPolicy.class); } @@ -3679,7 +3753,9 @@ public List getStaticPolicyVersions(String policyId) { return retryExecutor.execute( () -> { Request httpRequest = - buildRequest("GET", "/api/v1/static-policies/" + policyId + "/versions", null); + withRoute( + buildRequest("GET", "/api/v1/static-policies/" + policyId + "/versions", null), + "/api/v1/static-policies/{id}/versions"); try (Response response = executeHttp(httpClient, httpRequest)) { Map wrapper = parseResponse(response, new TypeReference>() {}); @@ -3707,9 +3783,23 @@ public List getStaticPolicyVersions(String policyId) { /** * Creates a policy override. * + *

A v11.0.0 platform retires per-policy overrides of system controls and refuses this write + * with {@code 409 LEGACY_POLICY_WRITE_FROZEN}, thrown as a {@link + * LegacyPolicyWriteFrozenException} whose message names the typed policy route ({@code + * /api/v1/typed-policies}), where a system control is changed in the organization's typed + * document. An older platform still creates the override. + * + *

The platform documents this refusal as agent-api's {@code PerPolicyOverrideRetired} + * response. Its body, as a v11.0.0 platform sends it: + * + *

{@code
+   * {"error":{"code":"LEGACY_POLICY_WRITE_FROZEN","message":"Per-policy overrides of system controls are retired in v11: a system control is enabled, disabled or re-actioned in the organization's typed document, in its system_controls section, through the typed authoring route at /api/v1/typed-policies. Session break-glass overrides (ADR-044) are unaffected, and reads on this endpoint are unaffected."}}
+   * }
+ * * @param policyId the policy ID * @param request the override request * @return the created override + * @throws LegacyPolicyWriteFrozenException when a v11.0.0 platform refuses the retired write */ public PolicyOverride createPolicyOverride(String policyId, CreatePolicyOverrideRequest request) { Objects.requireNonNull(policyId, "policyId cannot be null"); @@ -3718,7 +3808,10 @@ public PolicyOverride createPolicyOverride(String policyId, CreatePolicyOverride return retryExecutor.execute( () -> { Request httpRequest = - buildRequest("POST", "/api/v1/static-policies/" + policyId + "/override", request); + withRoute( + buildRequest( + "POST", "/api/v1/static-policies/" + policyId + "/override", request), + "/api/v1/static-policies/{id}/override"); try (Response response = executeHttp(httpClient, httpRequest)) { return parseResponse(response, PolicyOverride.class); } @@ -3729,7 +3822,15 @@ public PolicyOverride createPolicyOverride(String policyId, CreatePolicyOverride /** * Deletes a policy override. * + *

A v11.0.0 platform retires per-policy overrides of system controls and refuses this write + * with {@code 409 LEGACY_POLICY_WRITE_FROZEN}, thrown as a {@link + * LegacyPolicyWriteFrozenException} whose message names the typed policy route ({@code + * /api/v1/typed-policies}), where a system control is changed in the organization's typed + * document. An older platform still deletes the override. The refusal's body is the one quoted on + * {@link #createPolicyOverride}. + * * @param policyId the policy ID + * @throws LegacyPolicyWriteFrozenException when a v11.0.0 platform refuses the retired write */ public void deletePolicyOverride(String policyId) { Objects.requireNonNull(policyId, "policyId cannot be null"); @@ -3737,7 +3838,9 @@ public void deletePolicyOverride(String policyId) { retryExecutor.execute( () -> { Request httpRequest = - buildRequest("DELETE", "/api/v1/static-policies/" + policyId + "/override", null); + withRoute( + buildRequest("DELETE", "/api/v1/static-policies/" + policyId + "/override", null), + "/api/v1/static-policies/{id}/override"); try (Response response = executeHttp(httpClient, httpRequest)) { if (!response.isSuccessful() && response.code() != 204) { handleErrorResponse(response); @@ -3825,7 +3928,9 @@ public DynamicPolicy getDynamicPolicy(String policyId) { return retryExecutor.execute( () -> { Request httpRequest = - buildOrchestratorRequest("GET", "/api/v1/dynamic-policies/" + policyId, null); + withRoute( + buildOrchestratorRequest("GET", "/api/v1/dynamic-policies/" + policyId, null), + "/api/v1/dynamic-policies/{id}"); try (Response response = executeHttp(httpClient, httpRequest)) { // Agent proxy (Issue #886) returns {"policy": {...}} wrapper DynamicPolicyResponse wrapper = parseResponse(response, DynamicPolicyResponse.class); @@ -3871,7 +3976,9 @@ public DynamicPolicy updateDynamicPolicy(String policyId, UpdateDynamicPolicyReq return retryExecutor.execute( () -> { Request httpRequest = - buildOrchestratorRequest("PUT", "/api/v1/dynamic-policies/" + policyId, request); + withRoute( + buildOrchestratorRequest("PUT", "/api/v1/dynamic-policies/" + policyId, request), + "/api/v1/dynamic-policies/{id}"); try (Response response = executeHttp(httpClient, httpRequest)) { // Agent proxy (Issue #886) returns {"policy": {...}} wrapper DynamicPolicyResponse wrapper = parseResponse(response, DynamicPolicyResponse.class); @@ -3892,7 +3999,9 @@ public void deleteDynamicPolicy(String policyId) { retryExecutor.execute( () -> { Request httpRequest = - buildOrchestratorRequest("DELETE", "/api/v1/dynamic-policies/" + policyId, null); + withRoute( + buildOrchestratorRequest("DELETE", "/api/v1/dynamic-policies/" + policyId, null), + "/api/v1/dynamic-policies/{id}"); try (Response response = executeHttp(httpClient, httpRequest)) { if (!response.isSuccessful() && response.code() != 204) { handleErrorResponse(response); @@ -3917,7 +4026,9 @@ public DynamicPolicy toggleDynamicPolicy(String policyId, boolean enabled) { () -> { Map body = Map.of("enabled", enabled); Request httpRequest = - buildOrchestratorRequest("PUT", "/api/v1/dynamic-policies/" + policyId, body); + withRoute( + buildOrchestratorRequest("PUT", "/api/v1/dynamic-policies/" + policyId, body), + "/api/v1/dynamic-policies/{id}"); try (Response response = executeHttp(httpClient, httpRequest)) { // Agent proxy (Issue #886) returns {"policy": {...}} wrapper DynamicPolicyResponse wrapper = parseResponse(response, DynamicPolicyResponse.class); diff --git a/src/main/java/com/getaxonflow/sdk/AxonFlowConfig.java b/src/main/java/com/getaxonflow/sdk/AxonFlowConfig.java index 2db59cb2..f3b30484 100644 --- a/src/main/java/com/getaxonflow/sdk/AxonFlowConfig.java +++ b/src/main/java/com/getaxonflow/sdk/AxonFlowConfig.java @@ -619,11 +619,13 @@ public Builder userAgent(String userAgent) { * Sets the listener that receives the deprecations the platform declares on a route this client * called. * - *

From v11.0.0 the legacy static- and dynamic-policy routes carry {@code - * X-AxonFlow-Removed-In} and a successor {@code Link}, and an RFC 9745 {@code Deprecation} - * header once the deprecating release is tagged. The listener is called once per route per - * client (a client {@code asUser} derives shares the record), on the thread that made the call. - * When unset, the SDK logs each deprecated route once at WARN. + *

From v11.0.0 the legacy policy routes (the static- and dynamic-policy routes and the + * policy simulation routes) carry {@code X-AxonFlow-Removed-In} and a successor {@code Link}, + * and an RFC 9745 {@code Deprecation} header once the deprecating release is tagged. The + * listener is called once per route per client (a client {@code asUser} derives shares the + * record), on the thread that made the call. A route whose path carries an id is reported once, + * as its template ({@code GET /api/v1/static-policies/{id}}), not once per id. When unset, the + * SDK logs each deprecated route once at WARN. * * @param listener the listener, or null to log instead * @return this builder diff --git a/src/main/java/com/getaxonflow/sdk/PlatformRouteDeprecation.java b/src/main/java/com/getaxonflow/sdk/PlatformRouteDeprecation.java index a81a52e6..70c2e8fe 100644 --- a/src/main/java/com/getaxonflow/sdk/PlatformRouteDeprecation.java +++ b/src/main/java/com/getaxonflow/sdk/PlatformRouteDeprecation.java @@ -23,7 +23,9 @@ public final class PlatformRouteDeprecation { /** * Creates a route deprecation. * - * @param route the method and path, e.g. {@code GET /api/v1/static-policies} + * @param route the method and the route: its path, or its template when the path carries an id, + * e.g. {@code GET /api/v1/static-policies} or {@code POST + * /api/v1/static-policies/{id}/override} * @param successor the route that replaces it, or null when the platform names none * @param removedIn the release that removes it, e.g. {@code v11.1}, or null * @param deprecation the RFC 9745 {@code Deprecation} value, or null when not sent @@ -36,7 +38,11 @@ public PlatformRouteDeprecation( this.deprecation = deprecation; } - /** Returns the method and path, e.g. {@code GET /api/v1/static-policies}. */ + /** + * Returns the method and the route: its path, or its template when the path carries an id (a path + * parameter reads {@code {id}}), e.g. {@code GET /api/v1/static-policies} or {@code POST + * /api/v1/static-policies/{id}/override}. + */ public String getRoute() { return route; } diff --git a/src/test/java/com/getaxonflow/sdk/PolicySimulationTest.java b/src/test/java/com/getaxonflow/sdk/PolicySimulationTest.java index 0207f3ed..0377397f 100644 --- a/src/test/java/com/getaxonflow/sdk/PolicySimulationTest.java +++ b/src/test/java/com/getaxonflow/sdk/PolicySimulationTest.java @@ -19,6 +19,7 @@ /** Tests for policy simulation methods. */ @WireMockTest @DisplayName("Policy Simulation") +@SuppressWarnings("deprecation") class PolicySimulationTest { private AxonFlow axonflow; diff --git a/src/test/java/com/getaxonflow/sdk/V11DeprecationsTest.java b/src/test/java/com/getaxonflow/sdk/V11DeprecationsTest.java new file mode 100644 index 00000000..2fe1ed48 --- /dev/null +++ b/src/test/java/com/getaxonflow/sdk/V11DeprecationsTest.java @@ -0,0 +1,332 @@ +// Copyright 2026 AxonFlow +// SPDX-License-Identifier: MIT +package com.getaxonflow.sdk; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.assertj.core.api.Assertions.*; + +import com.getaxonflow.sdk.exceptions.AxonFlowException; +import com.getaxonflow.sdk.exceptions.LegacyPolicyWriteFrozenException; +import com.getaxonflow.sdk.simulation.ImpactReportInput; +import com.getaxonflow.sdk.simulation.ImpactReportRequest; +import com.getaxonflow.sdk.simulation.SimulatePoliciesRequest; +import com.getaxonflow.sdk.types.policies.PolicyTypes.CreatePolicyOverrideRequest; +import com.getaxonflow.sdk.types.policies.PolicyTypes.OverrideAction; +import com.getaxonflow.sdk.types.policies.PolicyTypes.UpdateDynamicPolicyRequest; +import com.getaxonflow.sdk.types.policies.PolicyTypes.UpdateStaticPolicyRequest; +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; +import com.github.tomakehurst.wiremock.junit5.WireMockTest; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +/** + * The v11.0.0 deprecations: the three policy simulation routes keep answering until v11.1 and are + * reported once per route with the platform's own signal, and the retired per-policy override + * writes throw the typed frozen exception. + * + *

The stubs carry the headers a v11 platform stamps on these routes today, as sdk-go #233's live + * run read them from enterprise {@code 857455033}: {@code X-AxonFlow-Removed-In: v11.1} and {@code + * Link: ; rel="successor-version"}, and no {@code Deprecation} header, + * because the platform's {@code policypath.DeprecatedSince} stays empty until v11.0.0 is tagged. + */ +@WireMockTest +@SuppressWarnings("deprecation") +@DisplayName("v11.0.0 deprecations: the simulation routes and the retired override writes") +class V11DeprecationsTest { + + private static final String SUCCESSOR = "/api/v1/typed-policies"; + + /** + * The platform's refusal of a per-policy override write: agent-api's {@code + * PerPolicyOverrideRetired} response, whose message is {@code legacyfreeze.OverrideMessage}. + */ + private static final String OVERRIDE_RETIRED = + "{\"error\":{\"code\":\"LEGACY_POLICY_WRITE_FROZEN\",\"message\":\"Per-policy overrides of" + + " system controls are retired in v11: a system control is enabled, disabled or" + + " re-actioned in the organization's typed document, in its system_controls section," + + " through the typed authoring route at /api/v1/typed-policies. Session break-glass" + + " overrides (ADR-044) are unaffected, and reads on this endpoint are unaffected.\"}}"; + + private static final List ROUTES = List.of("simulate", "impact-report", "conflicts"); + + private final List reported = + Collections.synchronizedList(new ArrayList<>()); + + private AxonFlow axonflow; + + @BeforeEach + void setUp(WireMockRuntimeInfo wm) { + axonflow = + AxonFlow.create( + AxonFlowConfig.builder() + .endpoint(wm.getHttpBaseUrl()) + .clientId("test-client") + .clientSecret("test-secret") + .onRouteDeprecation(reported::add) + .build()); + for (String route : ROUTES) { + stubFor( + post(urlEqualTo("/api/v1/policies/" + route)) + .willReturn( + okJson("{}") + .withHeader("X-AxonFlow-Removed-In", "v11.1") + .withHeader("Link", "<" + SUCCESSOR + ">; rel=\"successor-version\""))); + } + } + + private static SimulatePoliciesRequest simulate() { + return SimulatePoliciesRequest.builder().query("q").requestType("execute").build(); + } + + private static ImpactReportRequest impact() { + return ImpactReportRequest.builder() + .policyId("p") + .inputs(List.of(ImpactReportInput.builder().query("q").build())) + .build(); + } + + @Test + @DisplayName("the simulation methods work, and each route is reported once with no Deprecation") + void theSimulationMethodsWorkAndEachRouteIsReportedOnce() throws Exception { + for (int i = 0; i < 2; i++) { + assertThat(axonflow.simulatePolicies(simulate())).isNotNull(); + assertThat(axonflow.simulatePoliciesAsync(simulate()).get()).isNotNull(); + assertThat(axonflow.getPolicyImpactReport(impact())).isNotNull(); + assertThat(axonflow.getPolicyImpactReportAsync(impact()).get()).isNotNull(); + assertThat(axonflow.detectPolicyConflicts()).isNotNull(); + assertThat(axonflow.detectPolicyConflicts("p")).isNotNull(); + assertThat(axonflow.detectPolicyConflictsAsync().get()).isNotNull(); + assertThat(axonflow.detectPolicyConflictsAsync("p").get()).isNotNull(); + } + AxonFlow derived = axonflow.asUser("someone"); + derived.simulatePolicies(simulate()); + derived.getPolicyImpactReport(impact()); + derived.detectPolicyConflicts(); + + // Every response carried the headers; the client's record, not a cache, kept it to one report. + verify(5, postRequestedFor(urlEqualTo("/api/v1/policies/simulate"))); + verify(5, postRequestedFor(urlEqualTo("/api/v1/policies/impact-report"))); + verify(9, postRequestedFor(urlEqualTo("/api/v1/policies/conflicts"))); + assertThat(reported) + .containsExactly( + new PlatformRouteDeprecation( + "POST /api/v1/policies/simulate", SUCCESSOR, "v11.1", null), + new PlatformRouteDeprecation( + "POST /api/v1/policies/impact-report", SUCCESSOR, "v11.1", null), + new PlatformRouteDeprecation( + "POST /api/v1/policies/conflicts", SUCCESSOR, "v11.1", null)); + } + + @Test + @DisplayName("every public method that reaches a simulation route is @Deprecated, plainly") + void everyMethodReachingTheSimulationRoutesIsDeprecated() throws Exception { + List reaching = + Arrays.stream(AxonFlow.class.getMethods()) + .filter( + m -> + m.getName().startsWith("simulatePolicies") + || m.getName().startsWith("getPolicyImpactReport") + || m.getName().startsWith("detectPolicyConflicts")) + .collect(Collectors.toList()); + + // The census, so a method added under one of these names cannot slip past the loop below. A + // method under a new name that reaches these routes is not caught here; the client still + // reports + // its route at runtime through onRouteDeprecation. + assertThat(reaching.stream().map(Method::toGenericString).sorted()) + .hasSize(8) + .contains( + AxonFlow.class + .getMethod("simulatePolicies", SimulatePoliciesRequest.class) + .toGenericString(), + AxonFlow.class.getMethod("detectPolicyConflictsAsync", String.class).toGenericString()); + for (Method method : reaching) { + Deprecated deprecated = method.getAnnotation(Deprecated.class); + assertThat(deprecated).as(method.toGenericString()).isNotNull(); + // The removal is the platform's (v11.1), and an SDK version is the release's to name. + assertThat(deprecated.forRemoval()).as(method.toGenericString()).isFalse(); + assertThat(deprecated.since()).as(method.toGenericString()).isEmpty(); + } + assertThat( + AxonFlow.class + .getMethod("createPolicyOverride", String.class, CreatePolicyOverrideRequest.class) + .getAnnotation(Deprecated.class)) + .isNull(); + assertThat( + AxonFlow.class + .getMethod("deletePolicyOverride", String.class) + .getAnnotation(Deprecated.class)) + .isNull(); + } + + @Test + @DisplayName("the retired override writes throw the frozen exception naming the typed route") + void theRetiredOverrideWritesThrowTheFrozenException() { + String path = "/api/v1/static-policies/sys_sqli_drop_table/override"; + stubFor( + post(urlEqualTo(path)) + .willReturn( + aResponse() + .withStatus(409) + .withHeader("Content-Type", "application/json") + .withBody(OVERRIDE_RETIRED))); + stubFor( + delete(urlEqualTo(path)) + .willReturn( + aResponse() + .withStatus(409) + .withHeader("Content-Type", "application/json") + .withBody(OVERRIDE_RETIRED))); + + List writes = + List.of( + () -> + axonflow.createPolicyOverride( + "sys_sqli_drop_table", + CreatePolicyOverrideRequest.builder() + .actionOverride(OverrideAction.WARN) + .overrideReason("a reason") + .build()), + () -> axonflow.deletePolicyOverride("sys_sqli_drop_table")); + for (ThrowingCallable write : writes) { + Throwable thrown = catchThrowable(write); + assertThat(thrown) + .isInstanceOf(LegacyPolicyWriteFrozenException.class) + .hasMessageContaining(SUCCESSOR) + .hasMessageContaining("system_controls"); + AxonFlowException refused = (AxonFlowException) thrown; + assertThat(refused.getStatusCode()).isEqualTo(409); + assertThat(refused.getErrorCode()).isEqualTo(LegacyPolicyWriteFrozenException.CODE); + } + // A refusal is an answer, not a transient: neither write is retried. + verify(1, postRequestedFor(urlEqualTo(path))); + verify(1, deleteRequestedFor(urlEqualTo(path))); + } + + @Test + @DisplayName("a stamped route that carries an id is reported once, as its template, not per id") + void aStampedRouteWithAnIdIsReportedOnceNotOncePerId() { + stubFor( + post(urlMatching("/api/v1/static-policies/[^/]+/override")) + .willReturn( + aResponse() + .withStatus(409) + .withHeader("Content-Type", "application/json") + .withHeader("X-AxonFlow-Removed-In", "v11.1") + .withHeader("Link", "<" + SUCCESSOR + ">; rel=\"successor-version\"") + .withBody(OVERRIDE_RETIRED))); + + for (String id : List.of("sys_a", "sys_b")) { + catchThrowable( + () -> + axonflow.createPolicyOverride( + id, + CreatePolicyOverrideRequest.builder() + .actionOverride(OverrideAction.WARN) + .overrideReason("a reason") + .build())); + } + + verify(2, postRequestedFor(urlMatching("/api/v1/static-policies/[^/]+/override"))); + assertThat(reported) + .containsExactly( + new PlatformRouteDeprecation( + "POST /api/v1/static-policies/{id}/override", SUCCESSOR, "v11.1", null)); + } + + @Test + @DisplayName("every method that puts an id in a stamped route reports the route's template once") + void everyIdBearingMethodReportsItsTemplateOnce() { + stubFor( + any(urlPathMatching("/api/v1/(static|dynamic)-policies/.+")) + .willReturn( + okJson("{}") + .withHeader("X-AxonFlow-Removed-In", "v11.1") + .withHeader("Link", "<" + SUCCESSOR + ">; rel=\"successor-version\""))); + + for (String id : List.of("pol_a", "pol_b")) { + catchThrowable(() -> axonflow.getStaticPolicy(id)); + catchThrowable( + () -> + axonflow.updateStaticPolicy( + id, UpdateStaticPolicyRequest.builder().name("n").build())); + catchThrowable(() -> axonflow.deleteStaticPolicy(id)); + catchThrowable(() -> axonflow.toggleStaticPolicy(id, true)); + catchThrowable(() -> axonflow.getStaticPolicyVersions(id)); + catchThrowable( + () -> + axonflow.createPolicyOverride( + id, + CreatePolicyOverrideRequest.builder() + .actionOverride(OverrideAction.WARN) + .build())); + catchThrowable(() -> axonflow.deletePolicyOverride(id)); + catchThrowable(() -> axonflow.getDynamicPolicy(id)); + catchThrowable( + () -> + axonflow.updateDynamicPolicy( + id, UpdateDynamicPolicyRequest.builder().name("n").build())); + catchThrowable(() -> axonflow.deleteDynamicPolicy(id)); + catchThrowable(() -> axonflow.toggleDynamicPolicy(id, true)); + } + + // Eleven methods, twice each; updateDynamicPolicy and toggleDynamicPolicy share PUT. + assertThat(reported) + .extracting(PlatformRouteDeprecation::getRoute) + .containsExactlyInAnyOrder( + "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}"); + } + + @Test + @DisplayName("every id concatenated into a stamped route's path carries the route's template") + void everyConcatenatedStampedPathCarriesItsTemplate() throws Exception { + java.nio.file.Path root = + java.nio.file.Paths.get(System.getProperty("basedir", System.getProperty("user.dir"))); + String source = + new String( + java.nio.file.Files.readAllBytes( + root.resolve("src/main/java/com/getaxonflow/sdk/AxonFlow.java")), + java.nio.charset.StandardCharsets.UTF_8); + // The v11 deprecated families (the platform's policypath.deprecatedFamilies, both spellings). + // It sees a family path concatenated with `+` only; one built with String.format, a + // StringBuilder or HttpUrl.Builder is not seen, and would be reported once per id. + java.util.regex.Matcher concatenated = + java.util.regex.Pattern.compile( + "\"/api/v1/(static-policies|system-policies|dynamic-policies|tenant-policies" + + "|policies|templates|policy-overrides)/\"\\s*\\+") + .matcher(source); + List untagged = new ArrayList<>(); + int found = 0; + while (concatenated.find()) { + found++; + int statement = + Math.max( + source.lastIndexOf(';', concatenated.start()), + source.lastIndexOf('{', concatenated.start())); + if (!source.substring(statement, concatenated.start()).contains("withRoute(")) { + int line = source.substring(0, concatenated.start()).split("\n", -1).length; + untagged.add("AxonFlow.java:" + line); + } + } + + assertThat(found).isEqualTo(11); + assertThat(untagged).as("a stamped route built with an id but no route template").isEmpty(); + } +}