diff --git a/docs/understand/scenarios/parametric.md b/docs/understand/scenarios/parametric.md index 4f63f91a74d..93d25e01e79 100644 --- a/docs/understand/scenarios/parametric.md +++ b/docs/understand/scenarios/parametric.md @@ -230,7 +230,7 @@ Options use the Node helper's names (`distributionChannel`, `apiKey`, `clientTok The shared `mocked_backend` fixture serves these protobuf responses. Import shared FFE constants and fixture helpers from `utils.mocked_backend.ffe`. On the server distribution endpoint, explicitly accepting `application/protobuf` selects protobuf, including in comma-separated `Accept` lists with a positive quality value. Wildcard-only requests and existing agentless provider tests continue to receive JSON. -Use `mocked_backend.client.ffe_set_response` or `mocked_backend.client.ffe_set_responses` with `response_format="protobuf"` to configure these responses; the default format is JSON. Each format has an independent response timeline, and controls reject response IDs unsupported by the selected format. `mocked_backend.client.ffe_reset` resets both timelines and the shared request history, serves the root UFC again instead of an `ffe_use_suite` suite, and clears `ffe_set_flag_selection_ignored_reason`. Use `mocked_backend.ffe_get_requests` to inspect paths, queries, and headers without including fixture control traffic. +Use `mocked_backend.client.ffe_set_response` or `mocked_backend.client.ffe_set_responses` with `response_format="protobuf"` to configure these responses; the default format is JSON. The standalone precomputed-fetch tests use `response_format="precomputed"` for the separate POST response timeline. Each format has an independent response timeline, and controls reject response IDs unsupported by the selected format. `mocked_backend.client.ffe_reset` resets all timelines and the shared request history, serves the root UFC again instead of an `ffe_use_suite` suite, and clears `ffe_set_flag_selection_ignored_reason`. Use `mocked_backend.ffe_get_requests` to inspect paths, queries, headers, and precomputed POST bodies without including fixture control traffic. The protobuf response IDs `selection_ignored_empty`, `selection_ignored_tag_load_failed`, and `selection_ignored_unknown` return the full rules fixture with a `DD-Flag-Selection-Ignored` header set to an empty string, `tag_load_failed`, or `future_reason`, respectively. Use these shared responses to test selection diagnostics without replacing the rules endpoint handler. The `valid` response omits the header. diff --git a/docs/understand/weblogs/parametric_weblog.md b/docs/understand/weblogs/parametric_weblog.md index db8d0767c8a..dc930334fe2 100644 --- a/docs/understand/weblogs/parametric_weblog.md +++ b/docs/understand/weblogs/parametric_weblog.md @@ -1021,6 +1021,36 @@ An unexpected failure, process timeout, or invalid child output returns HTTP 500 The parent strips `NODE_OPTIONS` and imposes a 10-second deadline. This does not test tracer hook attachment or delivery to an intake. +#### `POST /ffe/fetch-precomputed-configuration` + +Called by `ParametricTestClientApi.ffe_fetch_precomputed_configuration()`. Node.js-only +fresh-process probe of `fetchPrecomputedConfiguration()` from the Node SDK bundles +vendored in the tracer package, not a standalone development dependency. The +request has `options` using the SDK's public fields, optional +`entryPoint` (`root` or `rules-based`), `abort`, `abortAfterMs`, `mutateContext`, +`evaluate` (defaults to true), `trackExposures` (defaults to false), and optional evaluation `contexts`. + +The custom Fetch transport routes to `SYSTEM_TESTS_FFE_RULES_BASE_URL` without +changing the generated path, query, headers, body, or request options. `requestUrl` +records the SDK's original URL before this rewrite, and is absent when validation +or cancellation prevents the Fetch call. The response contains a portable `wire`, +codec `restored` wire, diagnostics, and optional actual +OpenFeature status/results; a typed fetch failure instead returns `error` with +`name`, `code`, `message`, and optional HTTP `status`. HTTP and exposure-channel +counts are observed through process exit. Unexpected errors/timeouts are HTTP 500. +`exposuresBeforeTracking` records the count after fetching/serialization and before +provider registration. The explicit tracking control proves this adapter's capture +path using the same channel; it does not create an uploader. +No tracer or uploader is initialized. Future-only opt-out is checked with +`evaluate: false` because the Node provider does not implement that policy. + +The shared mock accepts `POST /precompute-assignments`. Configure its independent +timeline with `ffe_set_response(..., response_format="precomputed")`; `ffe_reset()` +resets all three formats. `ffe_get_requests()` includes a detached parsed `body` +for these POST requests, in addition to their path and headers. Encoding, selection, +and opt-out results are scripted response cases, not an origin evaluator or rollout +simulator. The encoded cases test response acceptance, not live negotiation. + #### `POST /ffe/fetch-rules-configuration` Called by `ParametricTestClientApi.ffe_fetch_rules_configuration()`. Fetch and serialize portable rules in a process without tracer/provider initialization. diff --git a/manifests/cpp.yml b/manifests/cpp.yml index e8c99283af1..f877743a449 100644 --- a/manifests/cpp.yml +++ b/manifests/cpp.yml @@ -195,6 +195,7 @@ manifest: tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Split_Features: incomplete_test_app (Split-feature hook capture is currently implemented only in the Java parametric client) tests/parametric/test_ffe/test_exposure_hooks.py: incomplete_test_app (Exposure hook observations are not implemented) tests/parametric/test_ffe/test_flag_selection.py: irrelevant (cpp is not in scope for v1 agentless server SDK configuration-source coverage) + tests/parametric/test_ffe/test_precomputed_configuration.py: incomplete_test_app (Standalone precomputed-fetch endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_rules_configuration.py: missing_feature (Standalone rules configuration helpers are currently tested only in Node.js) tests/parametric/test_ffe/test_serial_id_metadata.py: missing_feature tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata_Go: irrelevant (Legacy Go metadata key) diff --git a/manifests/dotnet.yml b/manifests/dotnet.yml index a85642f9512..8c628d5a7f0 100644 --- a/manifests/dotnet.yml +++ b/manifests/dotnet.yml @@ -1293,6 +1293,7 @@ manifest: tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Split_Features: incomplete_test_app (Split-feature hook capture is currently implemented only in the Java parametric client) tests/parametric/test_ffe/test_exposure_hooks.py: incomplete_test_app (Exposure hook observations are not implemented) tests/parametric/test_ffe/test_flag_selection.py: missing_feature (The flag selection provider option is not implemented) + tests/parametric/test_ffe/test_precomputed_configuration.py: incomplete_test_app (Standalone precomputed-fetch endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_rules_configuration.py: missing_feature (Standalone rules configuration helpers are currently tested only in Node.js) tests/parametric/test_ffe/test_serial_id_metadata.py: missing_feature tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata_Go: irrelevant (Legacy Go metadata key) diff --git a/manifests/golang.yml b/manifests/golang.yml index e028efba924..3a56ba29028 100644 --- a/manifests/golang.yml +++ b/manifests/golang.yml @@ -2357,6 +2357,7 @@ manifest: tests/parametric/test_ffe/test_exposure_hooks.py: v2.13.0-dev # Easy win for all weblogs and version 2.12.0 tests/parametric/test_ffe/test_exposure_hooks.py::Test_FFE_ExposureHooks::test_evaluation_feature_aggregation: missing_feature (Test agent needs EVP flagevaluation capture) tests/parametric/test_ffe/test_flag_selection.py: missing_feature (The flag selection provider option is not implemented) + tests/parametric/test_ffe/test_precomputed_configuration.py: incomplete_test_app (Standalone precomputed-fetch endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_rules_configuration.py: missing_feature (Standalone rules configuration helpers are currently tested only in Node.js) tests/parametric/test_ffe/test_serial_id_metadata.py: v2.10.1 tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata: diff --git a/manifests/java.yml b/manifests/java.yml index 07122bdc951..74674ae8d7a 100644 --- a/manifests/java.yml +++ b/manifests/java.yml @@ -4395,6 +4395,7 @@ manifest: tests/parametric/test_ffe/test_exposure_hooks.py::Test_FFE_ExposureHooks::test_evaluation_feature_aggregation: missing_feature (Test agent needs EVP flagevaluation capture) tests/parametric/test_ffe/test_exposure_hooks.py::Test_FFE_ExposureHooks::test_multiprovider_exposure_guard: irrelevant (Go exposure hook composition guard) tests/parametric/test_ffe/test_flag_selection.py: missing_feature (The flag selection provider option is not implemented) + tests/parametric/test_ffe/test_precomputed_configuration.py: incomplete_test_app (Standalone precomputed-fetch endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_rules_configuration.py: missing_feature (Standalone rules configuration helpers are currently tested only in Node.js) tests/parametric/test_ffe/test_serial_id_metadata.py: v1.66.0 tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata_Go: irrelevant (Legacy Go metadata key) diff --git a/manifests/nodejs.yml b/manifests/nodejs.yml index f14c8eeb9bf..794915499cb 100644 --- a/manifests/nodejs.yml +++ b/manifests/nodejs.yml @@ -2757,6 +2757,7 @@ manifest: tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Split_Features: incomplete_test_app (Split-feature hook capture is currently implemented only in the Java parametric client) tests/parametric/test_ffe/test_exposure_hooks.py: incomplete_test_app (Exposure hook observations are not implemented) tests/parametric/test_ffe/test_flag_selection.py: *ref_6_25_0 + tests/parametric/test_ffe/test_precomputed_configuration.py: 'missing_feature (Requires a dd-trace-js release whose vendored openfeature-node-server bundles contain fetchPrecomputedConfiguration and DatadogCoreProvider, openfeature-js-client#462 and #469)' tests/parametric/test_ffe/test_rules_configuration.py: 7.0.0-pre # Exact development version until the first containing release is confirmed. tests/parametric/test_ffe/test_rules_configuration.py::Test_FFE_Rules_Configuration_Selection: missing_feature (FFL-3364 requires the Node flag-selection dependency update in dd-trace-js) tests/parametric/test_ffe/test_serial_id_metadata.py: v6.18.0 diff --git a/manifests/php.yml b/manifests/php.yml index ed267236442..bd5a499d54c 100644 --- a/manifests/php.yml +++ b/manifests/php.yml @@ -1772,6 +1772,7 @@ manifest: tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Split_Features: incomplete_test_app (Split-feature hook capture is currently implemented only in the Java parametric client) tests/parametric/test_ffe/test_exposure_hooks.py: incomplete_test_app (Exposure hook observations are not implemented) tests/parametric/test_ffe/test_flag_selection.py: missing_feature (The flag selection provider option is not implemented) + tests/parametric/test_ffe/test_precomputed_configuration.py: incomplete_test_app (Standalone precomputed-fetch endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_rules_configuration.py: missing_feature (Standalone rules configuration helpers are currently tested only in Node.js) tests/parametric/test_ffe/test_serial_id_metadata.py: missing_feature tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata_Go: irrelevant (Legacy Go metadata key) diff --git a/manifests/python.yml b/manifests/python.yml index 2e1390073ec..b9bc88e3975 100644 --- a/manifests/python.yml +++ b/manifests/python.yml @@ -3209,6 +3209,7 @@ manifest: tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Split_Features: incomplete_test_app (Split-feature hook capture is currently implemented only in the Java parametric client) tests/parametric/test_ffe/test_exposure_hooks.py: incomplete_test_app (Exposure hook observations are not implemented) tests/parametric/test_ffe/test_flag_selection.py: missing_feature (The flag selection provider option is not implemented) + tests/parametric/test_ffe/test_precomputed_configuration.py: incomplete_test_app (Standalone precomputed-fetch endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_rules_configuration.py: missing_feature (Standalone rules configuration helpers are currently tested only in Node.js) tests/parametric/test_ffe/test_serial_id_metadata.py: missing_feature tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata_Go: irrelevant (Legacy Go metadata key) diff --git a/manifests/ruby.yml b/manifests/ruby.yml index c75b173da74..2357781a1ca 100644 --- a/manifests/ruby.yml +++ b/manifests/ruby.yml @@ -2744,6 +2744,7 @@ manifest: tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Split_Features: incomplete_test_app (Split-feature hook capture is currently implemented only in the Java parametric client) tests/parametric/test_ffe/test_exposure_hooks.py: incomplete_test_app (Exposure hook observations are not implemented) tests/parametric/test_ffe/test_flag_selection.py: missing_feature (The flag selection provider option is not implemented) + tests/parametric/test_ffe/test_precomputed_configuration.py: incomplete_test_app (Standalone precomputed-fetch endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_rules_configuration.py: missing_feature (Standalone rules configuration helpers are currently tested only in Node.js) tests/parametric/test_ffe/test_serial_id_metadata.py: missing_feature tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata_Go: irrelevant (Legacy Go metadata key) diff --git a/manifests/rust.yml b/manifests/rust.yml index cc02269c6ee..210d99765b2 100644 --- a/manifests/rust.yml +++ b/manifests/rust.yml @@ -310,6 +310,7 @@ manifest: tests/parametric/test_ffe/test_dynamic_evaluation.py::Test_Feature_Flag_Split_Features: incomplete_test_app (Split-feature hook capture is currently implemented only in the Java parametric client) tests/parametric/test_ffe/test_exposure_hooks.py: incomplete_test_app (Exposure hook observations are not implemented) tests/parametric/test_ffe/test_flag_selection.py: irrelevant (rust is not in scope for v1 agentless server SDK configuration-source coverage) + tests/parametric/test_ffe/test_precomputed_configuration.py: incomplete_test_app (Standalone precomputed-fetch endpoint is only implemented in Node.js) tests/parametric/test_ffe/test_rules_configuration.py: missing_feature (Standalone rules configuration helpers are currently tested only in Node.js) tests/parametric/test_ffe/test_serial_id_metadata.py: missing_feature tests/parametric/test_ffe/test_serial_id_metadata.py::Test_FFE_Serial_Id_Metadata_Go: irrelevant (Legacy Go metadata key) diff --git a/tests/ffe/README.md b/tests/ffe/README.md index 4402362b126..6da747bb288 100644 --- a/tests/ffe/README.md +++ b/tests/ffe/README.md @@ -91,6 +91,16 @@ Fixture provenance and deterministic expected behavior are documented in [`core-provider-rules-wire.md`](../parametric/test_ffe/core-provider-rules-wire.md). Standalone precomputation helper coverage is a separate change in [#8267](https://github.com/DataDog/system-tests/pull/8267). +`tests/parametric/test_ffe/test_precomputed_configuration.py` covers the standalone +Node precomputed-fetch helper from both entry points: JSON:API request fields, +context binding and codec round-trips, fingerprint query mapping and response +encoding checks, selection diagnostics, opt-out acknowledgments, transport failures, +deadlines/cancellation, and invalid options without a request. It uses the shared +mock's `precomputed` response timeline and loads the tracer's vendored Node SDK +bundles. It remains gated pending a tracer release containing both the fetch helper +and `DatadogCoreProvider`. Use the same command above with this file selected and forced. +These tests validate scripted responses, not live Datadog selection or encoding rollout. + `Test_FFE_Rules_Configuration_Selection` covers tag/key-pattern query parameters on both distribution channels, invalid/URL-overflow selections dropped with diagnostics, quiet empty-selection omission, and retention of the full response when the backend ignores selection. It also checks diagnostics for nonempty `DD-Flag-Selection-Ignored` response headers, including unknown reasons. The mock does not implement backend filtering. These cases require [openfeature-js-client #445](https://github.com/DataDog/openfeature-js-client/pull/445) in the `dd-trace` dependency and remain gated in the Node manifest until a containing build is available. Other SDKs retain the existing file-level gate. The class also runs the canonical selection vectors' `sdk` expectations through real HTTP requests, grouped by distribution channel to share container startup. These cover Unicode `White_Space` trimming, UTF-8 byte ordering and length, the 31/32-value and 200/201-byte boundaries, and drop-reason precedence. Raw-query percent-decoding and server-side `selectedKeys` expectations are intentionally excluded. The fixture updater validates the SDK vector shape before replacing the snapshot, and the existing update workflow tracks changes to both evaluator and selection fixtures. diff --git a/tests/parametric/test_ffe/test_precomputed_configuration.py b/tests/parametric/test_ffe/test_precomputed_configuration.py new file mode 100644 index 00000000000..6f647fe377a --- /dev/null +++ b/tests/parametric/test_ffe/test_precomputed_configuration.py @@ -0,0 +1,330 @@ +"""Standalone client-channel precomputed fetching through real HTTP and portable codecs.""" + +import hashlib +import json +from typing import Any +from urllib.parse import parse_qs, urlsplit + +from utils import features, pytest, scenarios, slow +from utils.docker_fixtures import ParametricTestClientApi as APMLibrary +from utils.mocked_backend import MockedBackendServer +from utils.mocked_backend.ffe import PRECOMPUTED_CONFIG_PATH, RESPONSE_SECRET + +TOKEN = "system-tests-private-client-token" +HASH_CAPABILITY = "assignment-encoding-flag-key-256-v1" +DEPENDENT_CAPABILITY = "dependent-flag-variant-key-v1" +CONTEXT = { + "targetingKey": "subject", + "country": "US", + "count": 3, + "enabled": False, + "nested": {"tags": ["a"]}, + "empty": None, +} +OPTIONS = {"distributionChannel": "client", "clientToken": TOKEN, "env": "test & preview", "context": CONTEXT} +CUTOFF = "2026-11-06T12:00:00Z" + + +def fingerprint(*capabilities: str) -> str: + return json.dumps( + {"version": 1, "sdk": {"name": "browser", "version": "system-test"}, "capabilities": capabilities} + ) + + +@pytest.fixture +def library_env(mocked_backend: MockedBackendServer) -> dict[str, str]: + return {"SYSTEM_TESTS_FFE_RULES_BASE_URL": mocked_backend.ffe_library_base_url} + + +def snapshot(result: dict[str, Any], *, exposure_events: int = 0) -> tuple[dict[str, Any], dict[str, Any]]: + assert "error" not in result, result + wire = json.loads(result["wire"]) + assert json.loads(result["restored"]) == wire + assert set(wire) == {"version", "precomputed"} + assert result["httpRequests"] == 1 + assert result["exposureEvents"] == exposure_events + assert result["exposuresBeforeTracking"] == 0 + portable = wire["precomputed"] + assert portable["etag"] == '"precomputed-v1"' + assert portable["fetchedAt"] > 0 + return wire, json.loads(portable["response"])["data"]["attributes"] + + +def assert_error(result: dict[str, Any], code: str, *, requests: int, status: int | None = None) -> None: + assert "wire" not in result, result + assert result["error"]["name"] == "ConfigurationFetchError", result + assert result["error"]["code"] == code, result + assert result["error"].get("status") == status, result + assert result["httpRequests"] == requests, result + assert result["exposureEvents"] == 0, result + for secret in (TOKEN, RESPONSE_SECRET, "private-cancellation-reason", "private-invalid"): + assert secret not in json.dumps(result) + + +@scenarios.parametric +@features.feature_flags_portable_configuration +@slow +class Test_FFE_Precomputed_Configuration: + def test_request_wire_and_context_binding( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + with test_library: + for entry in ("root", "rules-based"): + count = len(mocked_backend.ffe_get_requests()) + result = test_library.ffe_fetch_precomputed_configuration( + { + "entryPoint": entry, + "mutateContext": True, + "contexts": [CONTEXT, {**CONTEXT, "targetingKey": "another-subject"}], + "options": { + **OPTIONS, + "site": "datad0g.com", + "applicationId": "application", + "clientFingerprint": fingerprint(HASH_CAPABILITY, DEPENDENT_CAPABILITY, "unknown-v1"), + }, + } + ) + wire, attributes = snapshot(result) + request_url = urlsplit(result["requestUrl"]) + assert request_url.scheme == "https" + assert request_url.netloc == "preview.ff-cdn.datad0g.com" + assert result["providerStatus"] == "READY" + assert wire["version"] == 1 + assert wire["precomputed"]["context"] == CONTEXT + assert attributes["environment"] == {"name": "test"} + assert attributes["observeFullEvaluationData"] is False + flags = attributes["flags"] + assert set(flags) == {"test-flag", "false-flag", "nullable"} + assert flags["false-flag"]["variationValue"] is False + assert flags["nullable"]["variationValue"] is None + assert flags["test-flag"]["features"] == [ + {"key": "checkout", "value": False, "destinations": ["HOOK", "EXPOSURE"]} + ] + success, mismatch = result["results"] + assert success["value"] is True + assert success["reason"] == "TARGETING_MATCH" + assert success["variant"] == "on" + assert success.get("errorCode") is None + assert success["flagMetadata"]["__dd_split_serial_id"] == 7 + assert success["flagMetadata"]["__dd_do_log"] is True + assert result["nullable"]["value"] is None + assert result["nullable"].get("errorCode") is None + assert mismatch["value"] is False + assert mismatch["errorCode"] == "INVALID_CONTEXT" + requests = mocked_backend.ffe_get_requests()[count:] + assert len(requests) == 1 + request = requests[0] + url = urlsplit(request["path"]) + assert url.path == PRECOMPUTED_CONFIG_PATH + assert parse_qs(url.query) == {"dd_env": ["test & preview"], "cap_dependent-flags-variant-key": ["v1"]} + headers = request["headers"] + assert headers["dd-client-token"] == TOKEN + assert headers["dd-application-id"] == "application" + assert headers["accept"] == headers["content-type"] == "application/vnd.api+json" + assert "dd-api-key" not in headers + assert "x-dd-feature-flags-capabilities" not in headers + body = request["body"] + assert body["data"]["type"] == "precompute-assignments-request" + sent = body["data"]["attributes"] + assert set(sent) == {"env", "source", "subject"} + assert sent["env"] == {"dd_env": "test & preview"} + assert sent["source"]["sdk_name"] == "nodejs" + assert sent["source"]["sdk_version"] + assert "__BUILD_ENV__" not in sent["source"]["sdk_version"] + assert sent["subject"] == { + "targeting_key": "subject", + "targeting_attributes": { + "targetingKey": "subject", + "country": "US", + "count": "3", + "enabled": "false", + "nested": '{"tags":["a"]}', + "empty": "null", + }, + } + + # Same observer and fetched input, now with an explicitly enabled SDK sink. + control = test_library.ffe_fetch_precomputed_configuration({"options": OPTIONS, "trackExposures": True}) + snapshot(control, exposure_events=2) + assert control["providerStatus"] == "READY" + assert control["results"][0]["value"] is True + assert control["results"][0].get("errorCode") is None + assert control["nullable"]["value"] is None + assert control["nullable"].get("errorCode") is None + + def test_fingerprint_response_validation( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + with test_library: + for value in (None, fingerprint(), fingerprint("unknown-v1"), fingerprint(HASH_CAPABILITY)): + mocked_backend.client.ffe_set_response("valid", response_format="precomputed") + result = test_library.ffe_fetch_precomputed_configuration( + {"options": {**OPTIONS, **({"clientFingerprint": value} if value else {})}} + ) + wire, attributes = snapshot(result) + assert wire["version"] == 1 + assert attributes["obfuscated"] is False + assert parse_qs(urlsplit(mocked_backend.ffe_get_requests()[-1]["path"]).query) == { + "dd_env": ["test & preview"] + } + mocked_backend.client.ffe_set_response("encoded", response_format="precomputed") + encoded = test_library.ffe_fetch_precomputed_configuration( + {"options": {**OPTIONS, "clientFingerprint": fingerprint(HASH_CAPABILITY)}} + ) + wire, attributes = snapshot(encoded) + assert wire["version"] == 2 + assert attributes["obfuscated"] is True + salt = bytes.fromhex(attributes["obfuscation"]["salt"]) + assert attributes["obfuscation"]["scheme"] == "flag-key-sha256-v1" + assert set(attributes["flags"]) == { + hashlib.sha256(b"datadog.feature-flags.flag-key.v1\0" + salt + key.encode()).hexdigest() + for key in ("test-flag", "false-flag", "nullable") + } + assert encoded["results"][0]["value"] is True + assert encoded["results"][0].get("errorCode") is None + for mode, extra in ( + ("encoded", {}), + ("unknown_encoding", {"clientFingerprint": fingerprint(HASH_CAPABILITY)}), + ): + mocked_backend.client.ffe_set_response(mode, response_format="precomputed") + result = test_library.ffe_fetch_precomputed_configuration({"options": {**OPTIONS, **extra}}) + assert_error(result, "decode", requests=1) + + def test_selection_and_diagnostics(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: + cases: list[tuple[str, Any, dict[str, list[str]] | None, str | None]] = [ + ( + "valid", + {"tags": [" payments ", "checkout", "checkout"], "keyPatterns": ["test-*", "nullable"]}, + {"tags": ["checkout", "payments"], "key_patterns": ["nullable", "test-*"]}, + None, + ), + ("selected_empty", {"keyPatterns": ["no-match-*"]}, {"tags": [], "key_patterns": ["no-match-*"]}, None), + ( + "selection_ignored_tag_load_failed", + {"tags": ["checkout"]}, + {"tags": ["checkout"], "key_patterns": []}, + "tag_load_failed", + ), + ("valid", {"tags": "private-invalid"}, None, "malformed_selection"), + ("valid", {"tags": [f"tag-{i}" for i in range(32)]}, None, "too_many_values"), + ("valid", {"tags": [], "keyPatterns": []}, None, None), + ] + with test_library: + for mode, selection, sent, diagnostic in cases: + mocked_backend.client.ffe_set_response(mode, response_format="precomputed") + result = test_library.ffe_fetch_precomputed_configuration( + {"options": {**OPTIONS, "flagSelection": selection}} + ) + _, attributes = snapshot(result) + request = mocked_backend.ffe_get_requests()[-1] + assert request["body"]["data"]["attributes"].get("flag_selection") == sent + if mode == "selected_empty": + assert attributes["flags"] == {} + assert result["results"][0]["value"] is False + assert result["results"][0]["errorCode"] == "FLAG_NOT_FOUND" + else: + assert "test-flag" in attributes["flags"] + assert result["results"][0]["value"] is True + assert len(result["diagnostics"]) == (1 if diagnostic else 0) + if diagnostic: + assert diagnostic in result["diagnostics"][0] + assert "private-invalid" not in json.dumps(result) + + def test_experimentation_opt_out_acknowledgment( + self, test_library: APMLibrary, mocked_backend: MockedBackendServer + ) -> None: + context = {**CONTEXT, "dd_experimentation_opt_out_at": CUTOFF} + with test_library: + for mode, response, other_mode in ( + ("immediate", "opt_out_immediate", "opt_out_future"), + ("future_experiments_only", "opt_out_future", "opt_out_immediate"), + ): + options = {**OPTIONS, "context": context, "experimentationOptOutMode": mode} + mocked_backend.client.ffe_set_response(response, response_format="precomputed") + result = test_library.ffe_fetch_precomputed_configuration( + {"options": options, "evaluate": mode == "immediate"} + ) + wire, attributes = snapshot(result) + assert wire["precomputed"]["context"] == context + assert attributes["evaluation_options"]["experimentation_opt_out"] is True + assert attributes["evaluation_options"]["experimentation_opt_out_mode"] == mode + if mode == "immediate": + assert result["results"][0]["value"] is True + assert result["results"][0].get("errorCode") is None + assert mocked_backend.ffe_get_requests()[-1]["body"]["data"]["attributes"]["evaluation_options"] == { + "experimentation_opt_out_mode": mode + } + for invalid_response in ("valid", other_mode, "opt_out_mismatch"): + mocked_backend.client.ffe_set_response(invalid_response, response_format="precomputed") + invalid = test_library.ffe_fetch_precomputed_configuration({"options": options, "evaluate": False}) + assert_error(invalid, "decode", requests=1) + mocked_backend.client.ffe_set_response("opt_out_immediate", response_format="precomputed") + invalid = test_library.ffe_fetch_precomputed_configuration({"options": OPTIONS}) + assert_error(invalid, "decode", requests=1) + + def test_transport_failures(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: + cases = [ + ("forbidden", "http", 403), + ("server_error", "http", 500), + ("redirect", "http", 302), + ("malformed", "decode", None), + ("invalid_response", "decode", None), + ("empty", "decode", None), + ("wrong_content_type", "invalid_response", None), + ("disconnect", "transport", None), + ("truncated_body", "transport", None), + ] + with test_library: + for response, code, status in cases: + mocked_backend.client.ffe_set_response(response, response_format="precomputed") + count = len(mocked_backend.ffe_get_requests()) + result = test_library.ffe_fetch_precomputed_configuration({"options": OPTIONS}) + assert_error(result, code, requests=1, status=status) + assert len(mocked_backend.ffe_get_requests()) == count + 1 + + def test_deadlines_and_cancellation(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: + with test_library: + for response in ("delayed", "delayed_body"): + for cancel in (False, True): + mocked_backend.client.ffe_set_response(response, response_format="precomputed") + count = len(mocked_backend.ffe_get_requests()) + result = test_library.ffe_fetch_precomputed_configuration( + { + "options": {**OPTIONS, "timeoutMs": 5000 if cancel else 2000}, + **({"abortAfterMs": 2000} if cancel else {}), + } + ) + assert_error(result, "cancelled" if cancel else "timeout", requests=1) + assert len(mocked_backend.ffe_get_requests()) == count + 1 + count = len(mocked_backend.ffe_get_requests()) + result = test_library.ffe_fetch_precomputed_configuration({"options": OPTIONS, "abort": True}) + assert_error(result, "cancelled", requests=0) + assert len(mocked_backend.ffe_get_requests()) == count + + def test_invalid_options_do_not_send(self, test_library: APMLibrary, mocked_backend: MockedBackendServer) -> None: + cases: list[dict[str, Any]] = [ + {"distributionChannel": "server"}, + {"distributionChannel": None}, + {"apiKey": "private-invalid-api-key"}, + {"clientToken": ""}, + {"clientToken": "private-invalid\r\nheader"}, + {"env": " "}, + {"site": "example.invalid"}, + {"applicationId": "\nprivate-invalid"}, + {"context": None}, + {"context": {"targetingKey": 42}}, + {"context": ["private-invalid"]}, + {"timeoutMs": 0}, + {"clientFingerprint": "private-invalid"}, + {"clientFingerprint": json.dumps({"version": 999})}, + {"experimentationOptOutMode": "private-invalid"}, + { + "experimentationOptOutMode": "immediate", + "context": {**CONTEXT, "dd_experimentation_opt_out_at": "private-invalid"}, + }, + ] + with test_library: + for extra in cases: + result = test_library.ffe_fetch_precomputed_configuration({"options": {**OPTIONS, **extra}}) + assert_error(result, "invalid_options", requests=0) + assert mocked_backend.ffe_get_requests() == [] diff --git a/tests/test_the_test/test_mock_ffe_precomputed_backend.py b/tests/test_the_test/test_mock_ffe_precomputed_backend.py new file mode 100644 index 00000000000..673182f5751 --- /dev/null +++ b/tests/test_the_test/test_mock_ffe_precomputed_backend.py @@ -0,0 +1,134 @@ +"""Validate the shared precomputed HTTP fixture independently of SDK results.""" + +import hashlib +import json + +import requests + +from utils import features, pytest, scenarios +from utils.mocked_backend import MockedBackendServer +from utils.mocked_backend.ffe import PRECOMPUTED_CONFIG_PATH, RULES_CONFIG_PATH + + +@scenarios.test_the_test +@features.not_reported +class Test_Mock_FFE_Precomputed_Backend: + def test_response_and_detached_request_capture(self) -> None: + backend = MockedBackendServer(port=0) + payload = { + "data": {"type": "precompute-assignments-request", "attributes": {"subject": {"targeting_key": "subject"}}} + } + try: + response = requests.post( + f"{backend.base_url}{PRECOMPUTED_CONFIG_PATH}?dd_env=test", + data=json.dumps(payload).encode(), + headers={"Content-Type": "application/vnd.api+json"}, + timeout=5, + ) + assert response.status_code == 200 + assert response.headers["Content-Type"] == "application/vnd.api+json" + assert response.headers["ETag"] == '"precomputed-v1"' + data = response.json()["data"] + assert data["type"] == "precomputed-assignments" + flags = data["attributes"]["flags"] + assert flags["test-flag"]["variationValue"] is True + assert flags["false-flag"]["variationValue"] is False + assert flags["nullable"]["variationValue"] is None + captured = backend.ffe_get_requests() + assert len(captured) == 1 + assert captured[0]["body"] == payload + captured[0]["body"]["data"]["type"] = "changed" + assert backend.ffe_get_requests()[0]["body"] == payload + finally: + backend.close() + + @pytest.mark.parametrize("body", [b"{", b"\xff"]) + def test_invalid_json_api_body_does_not_consume_response(self, body: bytes) -> None: + backend = MockedBackendServer(port=0) + try: + backend.client.ffe_set_response("forbidden", response_format="precomputed") + url = f"{backend.base_url}{PRECOMPUTED_CONFIG_PATH}" + response = requests.post(url, data=body, headers={"Content-Type": "application/vnd.api+json"}, timeout=5) + assert response.status_code == 400 + assert response.json() == {"error": "expected JSON"} + assert backend.ffe_get_requests() == [] + assert requests.post(url, json={}, timeout=5).status_code == 403 + finally: + backend.close() + + def test_redirect_records_destination_requests(self) -> None: + backend = MockedBackendServer(port=0) + try: + backend.client.ffe_set_response("redirect", response_format="precomputed") + response = requests.post( + f"{backend.base_url}{PRECOMPUTED_CONFIG_PATH}", json={}, allow_redirects=False, timeout=5 + ) + redirect_path = f"{PRECOMPUTED_CONFIG_PATH}/redirected" + assert response.status_code == 302 + assert response.headers["Location"] == f"{backend.ffe_library_base_url}{redirect_path}" + backend.client.ffe_set_response("valid", response_format="precomputed") + destination = requests.get(f"{backend.base_url}{redirect_path}", timeout=5) + assert destination.status_code == 200 + assert destination.json()["data"]["attributes"]["flags"]["test-flag"]["variationValue"] is True + captured = backend.ffe_get_requests() + assert len(captured) == 2 + assert captured[1]["path"] == redirect_path + assert captured[1]["body"] == {} + finally: + backend.close() + + def test_wrong_content_type(self) -> None: + backend = MockedBackendServer(port=0) + try: + backend.client.ffe_set_response("wrong_content_type", response_format="precomputed") + response = requests.post(f"{backend.base_url}{PRECOMPUTED_CONFIG_PATH}", json={}, timeout=5) + assert response.status_code == 200 + assert response.headers["Content-Type"] == "text/html" + assert response.content == b"{}" + finally: + backend.close() + + def test_encoding_timeline_and_reset(self) -> None: + backend = MockedBackendServer(port=0) + try: + backend.client.ffe_set_response("forbidden", response_format="protobuf") + backend.client.ffe_set_responses(["encoded", "forbidden"], response_format="precomputed") + url = f"{backend.base_url}{PRECOMPUTED_CONFIG_PATH}" + response = requests.post(url, json={}, timeout=5) + attributes = response.json()["data"]["attributes"] + assert attributes["obfuscated"] is True + assert attributes["obfuscation"] == { + "scheme": "flag-key-sha256-v1", + "salt": "000102030405060708090a0b0c0d0e0f", + } + assert set(attributes["flags"]) == { + hashlib.sha256(b"datadog.feature-flags.flag-key.v1\0" + bytes(range(16)) + key.encode()).hexdigest() + for key in ("test-flag", "false-flag", "nullable") + } + assert requests.post(url, json={}, timeout=5).status_code == 403 + assert requests.get(f"{backend.base_url}{RULES_CONFIG_PATH}/client", timeout=5).status_code == 403 + backend.client.ffe_reset() + assert backend.ffe_get_requests() == [] + reset = requests.post(url, json={}, timeout=5).json()["data"]["attributes"] + assert reset["obfuscated"] is False + assert set(reset["flags"]) == {"test-flag", "false-flag", "nullable"} + finally: + backend.close() + + def test_control_validation_and_scripted_policies(self) -> None: + backend = MockedBackendServer(port=0) + try: + with pytest.raises(ValueError, match="unsupported precomputed response"): + backend.client.ffe_set_response("not_modified", response_format="precomputed") + assert backend.ffe_get_requests() == [] + for mode, expected in (("opt_out_immediate", "immediate"), ("opt_out_future", "future_experiments_only")): + backend.client.ffe_set_response(mode, response_format="precomputed") + response = requests.post(f"{backend.base_url}{PRECOMPUTED_CONFIG_PATH}", json={}, timeout=5) + assert response.status_code == 200 + assert response.json()["data"]["attributes"]["evaluation_options"] == { + "experimentation_opt_out": True, + "experimentation_opt_out_mode": expected, + "dd_experimentation_opt_out_at": "2026-11-06T12:00:00Z", + } + finally: + backend.close() diff --git a/tests/test_the_test/test_mock_ffe_rules_backend.py b/tests/test_the_test/test_mock_ffe_rules_backend.py index ea11ca21010..ff77bc4ad72 100644 --- a/tests/test_the_test/test_mock_ffe_rules_backend.py +++ b/tests/test_the_test/test_mock_ffe_rules_backend.py @@ -147,7 +147,7 @@ def test_rejects_invalid_response_format(self, response_format: object) -> None: timeout=5, ) assert response.status_code == 400 - assert response.json() == {"error": "response_format must be json or protobuf"} + assert response.json() == {"error": "response_format must be json, protobuf, or precomputed"} assert server.ffe_get_requests() == [] finally: server.close() diff --git a/utils/build/docker/nodejs/parametric/ffe-precomputed-configuration.js b/utils/build/docker/nodejs/parametric/ffe-precomputed-configuration.js new file mode 100644 index 00000000000..8de13ac668d --- /dev/null +++ b/utils/build/docker/nodejs/parametric/ffe-precomputed-configuration.js @@ -0,0 +1,78 @@ +'use strict' + +const { channel } = require('node:diagnostics_channel') +const { writeFileSync } = require('node:fs') +const { createRequire } = require('node:module') + +async function main () { + const { options, entryPoint = 'root', abort = false, abortAfterMs, mutateContext = false, evaluate = true, contexts, trackExposures = false } = JSON.parse(process.argv[2]) + let httpRequests = 0 + let exposureEvents = 0 + let requestUrl + let outcome + const subscriptions = [ + ['undici:request:create', () => { httpRequests++ }], + ['http.client.request.start', () => { httpRequests++ }], + ['ffe:exposure:submit', () => { exposureEvents++ }] + ] + for (const [name, listener] of subscriptions) channel(name).subscribe(listener) + const requireLibrary = createRequire(require.resolve('dd-trace/package.json')) + // Load the bundles shipped by the tracer, without importing or initializing the tracer. + const root = requireLibrary('./vendor/dist/@datadog/openfeature-node-server') + const rules = requireLibrary('./vendor/dist/@datadog/openfeature-node-server/rules-based') + const sdk = entryPoint === 'root' ? root : rules + const { OpenFeature } = require('@openfeature/server-sdk') + OpenFeature.setLogger({ error () {}, warn () {}, info () {}, debug () {} }) + const originalContext = structuredClone(options.context) + const diagnostics = [] + const controller = new AbortController() + if (abort) controller.abort(new Error('private-cancellation-reason')) + const timer = abortAfterMs === undefined ? undefined : setTimeout(() => controller.abort(new Error('private-cancellation-reason')), abortAfterMs) + try { + try { + const configuration = await sdk.fetchPrecomputedConfiguration({ + ...options, + signal: controller.signal, + logger: { error: message => diagnostics.push(message) }, + fetch: (url, init) => { + requestUrl = String(url) + if (mutateContext) { + options.context.country = 'changed-after-request' + options.context.nested.tags.push('changed-after-request') + } + const { pathname, search } = new URL(url) + return fetch(`${process.env.SYSTEM_TESTS_FFE_RULES_BASE_URL}${pathname}${search}`, init) + } + }) + const wire = sdk.configurationToString(configuration) + const restored = sdk.configurationFromString(wire) + outcome = { wire, restored: sdk.configurationToString(restored), diagnostics, exposuresBeforeTracking: exposureEvents } + if (evaluate) { + const provider = new rules.DatadogCoreProvider(restored, { + experimentationOptOutMode: options.experimentationOptOutMode, + ...(trackExposures && { exposureChannel: channel('ffe:exposure:submit') }) + }) + OpenFeature.setProvider('precomputed-fetch', provider) + const client = OpenFeature.getClient('precomputed-fetch') + outcome.providerStatus = client.providerStatus + outcome.results = await Promise.all((contexts ?? [originalContext]).map(context => client.getBooleanDetails('test-flag', false, context))) + outcome.nullable = await client.getObjectDetails('nullable', { fallback: true }, originalContext) + } + } catch (error) { + if (!(error instanceof sdk.ConfigurationFetchError)) throw error + outcome = { error: { name: error.name, code: error.code, message: error.message, status: error.status }, diagnostics } + } + } finally { + clearTimeout(timer) + await OpenFeature.clearProviders() + process.once('exit', () => { + if (outcome !== undefined) writeFileSync(1, JSON.stringify({ ...outcome, requestUrl, httpRequests, exposureEvents })) + for (const [name, listener] of subscriptions) channel(name).unsubscribe(listener) + }) + } +} + +main().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/utils/build/docker/nodejs/parametric/server.js b/utils/build/docker/nodejs/parametric/server.js index 02fc5ac1f59..8b68b93f98b 100644 --- a/utils/build/docker/nodejs/parametric/server.js +++ b/utils/build/docker/nodejs/parametric/server.js @@ -611,6 +611,27 @@ app.post("/trace/otel/otel_set_baggage", (req, res) => { }); // Feature Flag & Experimentation endpoints +app.post('/ffe/fetch-precomputed-configuration', (req, res) => { + const { execFile } = require('node:child_process') + const path = require('node:path') + const env = { ...process.env } + delete env.NODE_OPTIONS + execFile(process.execPath, [path.join(__dirname, 'ffe-precomputed-configuration.js'), JSON.stringify(req.body)], { + env, + timeout: 10000 + }, (error, stdout, stderr) => { + if (error) { + console.error('Standalone precomputed fetch failed:', stderr || error) + return res.status(500).json({ error: 'Standalone precomputed fetch failed' }) + } + try { + res.json(JSON.parse(stdout)) + } catch (error) { + res.status(500).json({ error: 'Invalid standalone precomputed output' }) + } + }) +}) + app.post('/ffe/core-provider', (req, res) => { const { execFile } = require('node:child_process') const path = require('node:path') diff --git a/utils/docker_fixtures/_test_clients/_test_client_parametric.py b/utils/docker_fixtures/_test_clients/_test_client_parametric.py index 99ed5432ed3..92ac54a1619 100644 --- a/utils/docker_fixtures/_test_clients/_test_client_parametric.py +++ b/utils/docker_fixtures/_test_clients/_test_client_parametric.py @@ -822,6 +822,12 @@ def ffe_core_provider(self, options: dict[str, Any]) -> dict[str, Any]: response.raise_for_status() return cast("dict[str, Any]", response.json()) + def ffe_fetch_precomputed_configuration(self, options: dict[str, Any]) -> dict[str, Any]: + """Fetch a context-bound snapshot and exercise its wire with the packaged Node provider.""" + response = self._session.post(self._url("/ffe/fetch-precomputed-configuration"), json=options, timeout=15) + response.raise_for_status() + return cast("dict[str, Any]", response.json()) + def ffe_fetch_rules_configuration(self, options: dict[str, Any]) -> dict[str, Any]: """Fetch and serialize portable rules in a process without tracer/provider initialization.""" response = self._session.post(self._url("/ffe/fetch-rules-configuration"), json=options, timeout=15) @@ -1329,6 +1335,10 @@ def ffe_core_provider(self, options: dict[str, Any]) -> dict[str, Any]: """Exercise the standalone provider without initializing the tracer.""" return self._client.ffe_core_provider(options) + def ffe_fetch_precomputed_configuration(self, options: dict[str, Any]) -> dict[str, Any]: + """Fetch precomputed assignments without initializing the tracer.""" + return self._client.ffe_fetch_precomputed_configuration(options) + def ffe_start( self, configuration: dict | None = None, *, flag_selection: dict[str, list[str]] | None = None ) -> bool: diff --git a/utils/mocked_backend/_backend_ffe.py b/utils/mocked_backend/_backend_ffe.py index acf4ec83acf..ab82835aa92 100644 --- a/utils/mocked_backend/_backend_ffe.py +++ b/utils/mocked_backend/_backend_ffe.py @@ -2,9 +2,9 @@ Tests configure the response timeline with ``mocked_backend.client.ffe_set_response(...)`` or ``mocked_backend.client.ffe_set_responses([...])`` before starting the test library. Controls -default to JSON; use ``response_format="protobuf"`` for an independent protobuf timeline. +default to JSON; use ``response_format="protobuf"`` or ``"precomputed"`` for independent timelines. ``mocked_backend.client.ffe_get_status()`` reports request counts, auth, ETag, response codes, -and paths observed across both formats. +and paths observed across all three formats. Precomputed POSTs also capture their parsed bodies. The JSON configuration serves the root UFC, or with ``mocked_backend.client.ffe_use_suite(name)`` the UFC of that ffe-system-test-data evaluation suite. It applies the ``selected_flag_tags`` and @@ -20,6 +20,7 @@ import base64 import contextlib +import copy from http import HTTPStatus import json import os @@ -28,7 +29,7 @@ import socket import threading import time -from typing import TYPE_CHECKING, Literal, TypedDict, cast +from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypedDict, cast from urllib.parse import parse_qs, urlencode, urlparse from ._ffe_flag_selection import ( @@ -43,6 +44,7 @@ validate_forced_reason, ) from ._utils import CONTROL_URL_PREFIX +from ._ffe_precomputed import PRECOMPUTED_CONFIG_PATH, precomputed_response if TYPE_CHECKING: @@ -53,7 +55,7 @@ else: _Base = object -ResponseFormat = Literal["json", "protobuf"] +ResponseFormat = Literal["json", "protobuf", "precomputed"] SELECTION_IGNORED_RESPONSES = { "selection_ignored_empty": "", "selection_ignored_tag_load_failed": "tag_load_failed", @@ -87,6 +89,29 @@ *SELECTION_IGNORED_RESPONSES, } ), + "precomputed": frozenset( + { + "valid", + "encoded", + "unknown_encoding", + "selected_empty", + "opt_out_immediate", + "opt_out_future", + "opt_out_mismatch", + "forbidden", + "server_error", + "redirect", + "malformed", + "invalid_response", + "empty", + "wrong_content_type", + "delayed", + "delayed_body", + "disconnect", + "truncated_body", + *SELECTION_IGNORED_RESPONSES, + } + ), } DEFAULT_RESPONSE = "valid" UFC_ETAG = '"ufc-v1"' @@ -123,6 +148,7 @@ def load_rules_wire_fixture() -> RulesWireFixture: class MockedBackendFFERequest(TypedDict): path: str headers: dict[str, str] + body: NotRequired[dict[str, Any]] class MockedBackendFFEStatus(TypedDict): @@ -175,7 +201,9 @@ def set_responses(self, responses: object, response_format: ResponseFormat) -> N self.last_status_code = None self.status_codes = [] - def record_request(self, headers: Mapping[str, str], path: str, response_format: ResponseFormat) -> str: + def record_request( + self, headers: Mapping[str, str], path: str, response_format: ResponseFormat, body: dict[str, Any] | None = None + ) -> str: parsed = urlparse(path) normalized_headers = {key.lower(): value for key, value in headers.items()} @@ -186,7 +214,10 @@ def record_request(self, headers: Mapping[str, str], path: str, response_format: self.last_path = parsed.path self.last_if_none_match = normalized_headers.get("if-none-match") self.observed_dd_api_key = _get_dd_api_key(headers) - self.requests.append({"path": path, "headers": normalized_headers}) + recorded: MockedBackendFFERequest = {"path": path, "headers": normalized_headers} + if body is not None: + recorded["body"] = copy.deepcopy(body) + self.requests.append(recorded) responses = self.responses[response_format] response = responses[0] if len(responses) > 1: @@ -235,7 +266,7 @@ def status(self) -> MockedBackendFFEStatus: def get_requests(self) -> list[MockedBackendFFERequest]: with self._lock: - return [{"path": request["path"], "headers": dict(request["headers"])} for request in self.requests] + return copy.deepcopy(self.requests) def _get_dd_api_key(headers: Mapping[str, str]) -> str | None: @@ -285,8 +316,8 @@ def _valid_ufc_bytes(selected_keys: list[str] | None = None, suite: str | None = def _validate_response_format(response_format: object) -> ResponseFormat: - if response_format not in ("json", "protobuf"): - raise ValueError("response_format must be json or protobuf") + if response_format not in ("json", "protobuf", "precomputed"): + raise ValueError("response_format must be json, protobuf, or precomputed") return cast("ResponseFormat", response_format) @@ -421,6 +452,7 @@ class MockedBackendServerFfeMixin(_Base): # Endpoint contract: # - GET /api/v2/feature-flagging/config/rules-based/server?dd_env=test # - GET /api/v2/feature-flagging/config/rules-based/{server,client} (protobuf helpers) + # - POST /precompute-assignments (scripted precomputed assignments) # - GET /system-tests/ffe/status # - POST /system-tests/ffe/responses # - POST /system-tests/ffe/reset @@ -434,6 +466,8 @@ def _ffe_configure(self) -> None: self.add_handler("GET", CONFIG_PATH, self._ffe_handle_config) self.add_handler("GET", f"{RULES_CONFIG_PATH}/client", self._ffe_handle_rules_config) self.add_handler("GET", f"{RULES_CONFIG_PATH}/redirected", self._ffe_handle_rules_config) + self.add_handler("POST", PRECOMPUTED_CONFIG_PATH, self._ffe_handle_precomputed) + self.add_handler("GET", f"{PRECOMPUTED_CONFIG_PATH}/redirected", self._ffe_handle_precomputed) # exposures and flag evaluations sent straight to the event platform intake for path in EVP_INTAKE_PATHS: @@ -519,51 +553,84 @@ def _ffe_handle_rules_config( ) -> tuple[bytes, bytes]: response = self._ffe_state.record_request(dict(request.headers), request.path, "protobuf") try: - status = HTTPStatus.OK wire_fixture = load_rules_wire_fixture() headers = {"Content-Type": "application/protobuf", "ETag": wire_fixture["rules"]["etag"]} body = base64.b64decode(wire_fixture["rules"]["response"]) - if response in SELECTION_IGNORED_RESPONSES: - headers[FLAG_SELECTION_IGNORED_HEADER] = SELECTION_IGNORED_RESPONSES[response] - elif response == "delayed": - time.sleep(4) - elif response == "delayed_body": - # Each phase fits within the deadline, but their combined duration does not. - time.sleep(BODY_PHASE_DELAY_SECONDS) - request.before_response_body = lambda: time.sleep(BODY_PHASE_DELAY_SECONDS) - elif response in {"forbidden", "server_error"}: - status = HTTPStatus.FORBIDDEN if response == "forbidden" else HTTPStatus.INTERNAL_SERVER_ERROR - body = RESPONSE_SECRET.encode() - elif response == "redirect": - status = HTTPStatus.FOUND - headers["Location"] = f"{self.ffe_library_base_url}{RULES_CONFIG_PATH}/redirected" - elif response == "malformed": - body = b"\xff" - elif response == "empty": - body = b"" - elif response == "wrong_content_type": - headers["Content-Type"] = "application/json" - body = b"{}" - elif response == "disconnect": - request.connection.shutdown(socket.SHUT_RDWR) - elif response == "truncated_body": - - def truncate_body() -> None: - request.wfile.write(RESPONSE_SECRET.encode()) - request.connection.shutdown(socket.SHUT_RDWR) - - request.before_response_body = truncate_body - elif response != "valid": - raise ValueError(f"Unsupported protobuf rules response: {response}") + return self._ffe_send_configuration(request, response, headers, body, f"{RULES_CONFIG_PATH}/redirected") + finally: + self._ffe_state.finish_request() - self._ffe_state.record_response(status) - request.send_response(status) - for name, value in headers.items(): - request.send_header(name, value) - return body, body + def _ffe_handle_precomputed( + self, request: MockedBackendRequestHandler, payload: bytes | dict | None + ) -> tuple[Mapping | bytes, bytes]: + if isinstance(payload, bytes): + try: + payload = json.loads(payload) + except (ValueError, UnicodeDecodeError): + return request.write_json(HTTPStatus.BAD_REQUEST, {"error": "expected JSON"}) + body = payload if isinstance(payload, dict) else {} + response = self._ffe_state.record_request(dict(request.headers), request.path, "precomputed", body) + try: + headers = {"Content-Type": "application/vnd.api+json", "ETag": '"precomputed-v1"'} + content = json.dumps(precomputed_response(response)).encode() + if response == "invalid_response": + content = b"{}" + scripted = response if response in VALID_RESPONSE_IDS["protobuf"] else "valid" + return self._ffe_send_configuration( + request, scripted, headers, content, f"{PRECOMPUTED_CONFIG_PATH}/redirected" + ) finally: self._ffe_state.finish_request() + def _ffe_send_configuration( + self, + request: MockedBackendRequestHandler, + response: str, + headers: dict[str, str], + body: bytes, + redirect_path: str, + ) -> tuple[bytes, bytes]: + status = HTTPStatus.OK + if response in SELECTION_IGNORED_RESPONSES: + headers[FLAG_SELECTION_IGNORED_HEADER] = SELECTION_IGNORED_RESPONSES[response] + elif response == "delayed": + time.sleep(4) + elif response == "delayed_body": + # Each phase fits within the deadline, but their combined duration does not. + time.sleep(BODY_PHASE_DELAY_SECONDS) + request.before_response_body = lambda: time.sleep(BODY_PHASE_DELAY_SECONDS) + elif response in {"forbidden", "server_error"}: + status = HTTPStatus.FORBIDDEN if response == "forbidden" else HTTPStatus.INTERNAL_SERVER_ERROR + body = RESPONSE_SECRET.encode() + elif response == "redirect": + status = HTTPStatus.FOUND + headers["Location"] = f"{self.ffe_library_base_url}{redirect_path}" + elif response == "malformed": + body = b"\xff" + elif response == "empty": + body = b"" + elif response == "wrong_content_type": + headers["Content-Type"] = ( + "application/json" if headers["Content-Type"] == "application/protobuf" else "text/html" + ) + body = b"{}" + elif response == "disconnect": + request.connection.shutdown(socket.SHUT_RDWR) + elif response == "truncated_body": + + def truncate_body() -> None: + request.wfile.write(RESPONSE_SECRET.encode()) + request.connection.shutdown(socket.SHUT_RDWR) + + request.before_response_body = truncate_body + elif response != "valid": + raise ValueError(f"Unsupported configuration response: {response}") + self._ffe_state.record_response(status) + request.send_response(status) + for name, value in headers.items(): + request.send_header(name, value) + return body, body + def _ffe_handle_control_responses( self, request: MockedBackendRequestHandler, payload: bytes | dict | None ) -> tuple[Mapping, bytes]: diff --git a/utils/mocked_backend/_ffe_precomputed.py b/utils/mocked_backend/_ffe_precomputed.py new file mode 100644 index 00000000000..777b3be7d74 --- /dev/null +++ b/utils/mocked_backend/_ffe_precomputed.py @@ -0,0 +1,59 @@ +"""Scripted precompute-assignments responses, not an implementation of origin evaluation/rollouts.""" + +import hashlib +from typing import Any + +PRECOMPUTED_CONFIG_PATH = "/precompute-assignments" + + +def precomputed_response(mode: str) -> dict[str, Any]: + # JSON:API envelope and assignment fields follow the public browser precomputed-v1 + # fixture shape; flag keys, values, serialId, and features are local test data. + # Encoding metadata follows flag-key-sha256-v1; selection/policy outcomes are scripted. + assignment = { + "allocationKey": "allocation", + "variationKey": "on", + "variationType": "boolean", + "variationValue": True, + "reason": "TARGETING_MATCH", + "doLog": True, + "serialId": 7, + "features": [{"key": "checkout", "value": False, "destinations": ["HOOK", "EXPOSURE"]}], + } + flags = { + "test-flag": assignment, + "false-flag": {**assignment, "variationKey": "off", "variationValue": False}, + "nullable": {**assignment, "variationType": "object", "variationValue": None}, + } + attributes: dict[str, Any] = { + "createdAt": "2026-11-06T12:00:00Z", + "environment": {"name": "test"}, + "format": "PRECOMPUTED", + "obfuscated": False, + "observeFullEvaluationData": False, + "flags": flags, + } + if mode in ("encoded", "unknown_encoding"): + salt = "000102030405060708090a0b0c0d0e0f" + attributes.update({"obfuscated": True, "obfuscation": {"scheme": "flag-key-sha256-v1", "salt": salt}}) + attributes["flags"] = { + hashlib.sha256( + b"datadog.feature-flags.flag-key.v1\0" + bytes.fromhex(salt) + key.encode() + ).hexdigest(): value + for key, value in flags.items() + } + if mode == "unknown_encoding": + attributes["obfuscation"]["scheme"] = "unsupported-encoding" + elif mode == "selected_empty": + attributes["flags"] = {} + elif mode in ("opt_out_immediate", "opt_out_future", "opt_out_mismatch"): + attributes["evaluation_options"] = { + "experimentation_opt_out": True, + "experimentation_opt_out_mode": "future_experiments_only" + if mode in ("opt_out_future", "opt_out_mismatch") + else "immediate", + "dd_experimentation_opt_out_at": "2026-11-06T12:00:00Z" + if mode != "opt_out_mismatch" + else "2026-11-07T12:00:00Z", + } + return {"data": {"id": "subject", "type": "precomputed-assignments", "attributes": attributes}} diff --git a/utils/mocked_backend/ffe.py b/utils/mocked_backend/ffe.py index dd28d7c508f..d680acb04c4 100644 --- a/utils/mocked_backend/ffe.py +++ b/utils/mocked_backend/ffe.py @@ -4,6 +4,7 @@ SELECTED_FLAG_TAGS, Selection, ) +from ._ffe_precomputed import PRECOMPUTED_CONFIG_PATH from ._backend_ffe import ( CONFIG_PATH, CONFIG_QUERY, @@ -27,6 +28,7 @@ "EVALUATION_SUITES_RELATIVE_PATH", "EXPECTED_DD_ENV", "FLAG_SELECTION_IGNORED_HEADER", + "PRECOMPUTED_CONFIG_PATH", "RESPONSE_SECRET", "RULES_CONFIG_PATH", "SELECTED_FLAG_KEY_PATTERNS",