From db16a8280319ba8a1e36ac23ab726fa5e1ad4b6f Mon Sep 17 00:00:00 2001 From: Lourens de Jager Date: Wed, 25 Nov 2026 23:29:43 +0000 Subject: [PATCH] fix: report not ready without flags, and reject unusable configuration - Until a fetch succeeds, every evaluation reports PROVIDER_NOT_READY with the TypeScript provider's message, instead of FLAG_NOT_FOUND and a warning blaming the slug. A wrong client identifier no longer looks like a typo in every flag key. - Strip whitespace around client_identifier and release_version_override, and reject values that still can't be sent in an HTTP header. A trailing newline from a file or mounted secret made every request fail. - Reject an http_client that isn't an httpx.Client. An httpx.AsyncClient made every request fail with an un-awaited coroutine. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- .../_feature_flag_evaluator_cache.py | 5 +- .../_octopus_feature_provider.py | 102 ++++++++++--- tests/test_octopus_feature_provider.py | 142 ++++++++++++++++-- 4 files changed, 217 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 9d0052d..8faeaf2 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ if client.get_boolean_value("to-the-moon-feature", False): Octopus feature flags are boolean, so evaluate them with `get_boolean_value` or `get_boolean_details`. Evaluating a flag as a string, integer, float or object returns your default value with an error code. +If the provider can't fetch your flags, for example because the client identifier is wrong or Octopus is unreachable, it still reports itself ready, and keeps trying every `cache_duration`. Until a fetch succeeds, every evaluation returns your default value with the `PROVIDER_NOT_READY` error code. + Call `api.shutdown()` when your application stops, so the provider releases its resources. For more on evaluating flags, see the [OpenFeature evaluation API documentation](https://openfeature.dev/docs/reference/concepts/evaluation-api/). @@ -65,9 +67,9 @@ For more on evaluating flags, see the [OpenFeature evaluation API documentation] | `cache_duration` | No | A `timedelta` for how often the provider checks for changed flags. Defaults to one minute. Must be positive. | | `request_timeout` | No | A `timedelta` for how long a request to Octopus may take in total before it's abandoned. Defaults to 10 seconds. Must be positive. | | `release_version_override` | No | Overrides the release version embedded in the client identifier. | -| `http_client` | No | An `httpx.Client` for requests to Octopus, for example to configure a proxy, TLS or instrumentation. The provider never closes a client you supply. If the client has its own timeouts, the shorter of those and `request_timeout` applies. By default, the provider creates and manages its own client. | +| `http_client` | No | An `httpx.Client` (not an `httpx.AsyncClient`) for requests to Octopus, for example to configure a proxy, TLS or instrumentation. The provider never closes a client you supply. If the client has its own timeouts, the shorter of those and `request_timeout` applies. By default, the provider creates and manages its own client. | -The provider takes a copy of the configuration when it's created, so later changes to the configuration don't affect it. It raises `ValueError` or `TypeError` if `client_identifier` is empty or isn't a string, or if `cache_duration` or `request_timeout` isn't a positive `timedelta`. `ProductMetadata` removes characters that aren't valid in an HTTP header token, and raises `ValueError` if the name, or a version you supply, has none left. +The provider takes a copy of the configuration when it's created, so later changes to the configuration don't affect it. It removes leading and trailing whitespace, such as a newline from a file or mounted secret, from `client_identifier` and `release_version_override`. It raises `ValueError` or `TypeError` if either of those is empty, isn't a string, or contains characters other than printable ASCII, if `cache_duration` or `request_timeout` isn't a positive `timedelta`, or if `http_client` isn't an `httpx.Client`. `ProductMetadata` removes characters that aren't valid in an HTTP header token, and raises `ValueError` if the name, or a version you supply, has none left. ### Logging diff --git a/src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py b/src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py index 5f6875e..328078b 100644 --- a/src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py +++ b/src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py @@ -23,8 +23,9 @@ class FeatureFlagEvaluatorCache: """Holds the evaluator the provider resolves flags against, and keeps it updated by polling the feature flags service. - Until a fetch succeeds it holds an empty evaluator, so every flag is - missing. A failed refresh keeps the last good evaluator. + Until a fetch succeeds it holds an empty evaluator with no content hash, + which the provider treats as not ready. A failed refresh keeps the last + good evaluator. """ def __init__( diff --git a/src/octopus_openfeature_provider/_octopus_feature_provider.py b/src/octopus_openfeature_provider/_octopus_feature_provider.py index fdf0416..3f83685 100644 --- a/src/octopus_openfeature_provider/_octopus_feature_provider.py +++ b/src/octopus_openfeature_provider/_octopus_feature_provider.py @@ -1,15 +1,24 @@ import copy +import re import threading from collections.abc import Mapping, Sequence from datetime import timedelta +import httpx from openfeature.evaluation_context import EvaluationContext -from openfeature.exception import FlagNotFoundError, TypeMismatchError +from openfeature.exception import ( + FlagNotFoundError, + ProviderNotReadyError, + TypeMismatchError, +) from openfeature.flag_evaluation import FlagResolutionDetails, FlagValueType from openfeature.provider import AbstractProvider, Metadata from octopus_openfeature_provider._feature_flag_api_client import FeatureFlagApiClient -from octopus_openfeature_provider._feature_flag_evaluator import FLAG_NOT_FOUND_MESSAGE +from octopus_openfeature_provider._feature_flag_evaluator import ( + FLAG_NOT_FOUND_MESSAGE, + FeatureFlagEvaluator, +) from octopus_openfeature_provider._feature_flag_evaluator_cache import ( FeatureFlagEvaluatorCache, ) @@ -19,6 +28,11 @@ MAX_CACHE_DURATION = timedelta(seconds=threading.TIMEOUT_MAX) +PROVIDER_NOT_READY_MESSAGE = "No Octopus feature flags are available. The provider failed to initialize, or was used before initializing." + +# httpx sends header values as ASCII, and rejects control characters in them. +_INVALID_HEADER_VALUE_CHARACTERS = re.compile(r"[^\x20-\x7e]") + class OctopusFeatureProvider(AbstractProvider): """An OpenFeature provider for Octopus feature flags. @@ -26,12 +40,22 @@ class OctopusFeatureProvider(AbstractProvider): Register it with the OpenFeature SDK, for example with `openfeature.api.set_provider`. Octopus feature flags are booleans only. + Until the provider has fetched the flags, every evaluation returns the + default value with the `PROVIDER_NOT_READY` error code. + + Leading and trailing whitespace, such as the newline at the end of a value + read from a file, is removed from the client identifier and the release + version override. + Raises: - ValueError: If the configuration's client identifier is empty, or its - `cache_duration` or `request_timeout` isn't positive, or its - `cache_duration` is longer than `threading.TIMEOUT_MAX` seconds. - TypeError: If the configuration's client identifier isn't a `str`, - or its `cache_duration` or `request_timeout` isn't a `timedelta`. + ValueError: If the configuration's client identifier or release + version override is empty or contains characters that aren't valid + in an HTTP header, or its `cache_duration` or `request_timeout` + isn't positive, or its `cache_duration` is longer than + `threading.TIMEOUT_MAX` seconds. + TypeError: If the configuration's client identifier or release version + override isn't a `str`, its `cache_duration` or `request_timeout` + isn't a `timedelta`, or its `http_client` isn't an `httpx.Client`. """ def __init__(self, configuration: OctopusFeatureConfiguration) -> None: @@ -39,7 +63,7 @@ def __init__(self, configuration: OctopusFeatureConfiguration) -> None: # A shallow copy, so the provider is unaffected by later changes to the # configuration but still uses the caller's HTTP client. self._configuration = copy.copy(configuration) - _validate(self._configuration) + _validate_and_clean(self._configuration) self._evaluator_cache = FeatureFlagEvaluatorCache( FeatureFlagApiClient(self._configuration), self._configuration.cache_duration, @@ -47,7 +71,8 @@ def __init__(self, configuration: OctopusFeatureConfiguration) -> None: def initialize(self, evaluation_context: EvaluationContext) -> None: # Never raises, so the SDK reports the provider as ready even when the - # fetch fails. Every flag is then missing until a refresh succeeds. + # fetch fails. Every evaluation then reports PROVIDER_NOT_READY until + # a refresh succeeds. self._evaluator_cache.initialize() def shutdown(self) -> None: @@ -62,9 +87,7 @@ def resolve_boolean_details( default_value: bool, evaluation_context: EvaluationContext | None = None, ) -> FlagResolutionDetails[bool]: - return self._evaluator_cache.get_evaluator().evaluate( - flag_key, evaluation_context - ) + return self._require_evaluator().evaluate(flag_key, evaluation_context) def resolve_string_details( self, @@ -99,22 +122,31 @@ def resolve_object_details( raise self._reject_non_boolean_evaluation(flag_key) def _reject_non_boolean_evaluation(self, flag_key: str) -> Exception: - evaluator = self._evaluator_cache.get_evaluator() + evaluator = self._require_evaluator() if evaluator.find_evaluation_by_slug(flag_key) is None: return FlagNotFoundError(FLAG_NOT_FOUND_MESSAGE) return TypeMismatchError("Octopus only supports boolean flags.") - -def _validate(configuration: OctopusFeatureConfiguration) -> None: - client_identifier = configuration.client_identifier - # Callers without a type checker may pass None, for example from an unset - # environment variable. - if not isinstance(client_identifier, str): - raise TypeError( - f"client_identifier must be a str, but was {type(client_identifier).__name__}." + def _require_evaluator(self) -> FeatureFlagEvaluator: + """Without any evaluations, an unknown slug can't be told apart from + one that was never received, so report PROVIDER_NOT_READY rather than + masking the failure as FLAG_NOT_FOUND.""" + evaluator = self._evaluator_cache.get_evaluator() + # Every successful fetch has a content hash, so an empty one means no + # fetch has succeeded yet. + if not evaluator.content_hash: + raise ProviderNotReadyError(PROVIDER_NOT_READY_MESSAGE) + return evaluator + + +def _validate_and_clean(configuration: OctopusFeatureConfiguration) -> None: + configuration.client_identifier = _clean_header_value( + "client_identifier", configuration.client_identifier + ) + if configuration.release_version_override is not None: + configuration.release_version_override = _clean_header_value( + "release_version_override", configuration.release_version_override ) - if not client_identifier.strip(): - raise ValueError("client_identifier must not be empty.") _validate_positive_duration("cache_duration", configuration.cache_duration) # The polling thread waits this long between checks, and a longer wait # raises OverflowError there, which would stop polling without a log. @@ -123,6 +155,30 @@ def _validate(configuration: OctopusFeatureConfiguration) -> None: f"cache_duration must be at most {MAX_CACHE_DURATION}, but was {configuration.cache_duration}." ) _validate_positive_duration("request_timeout", configuration.request_timeout) + http_client = configuration.http_client + # An httpx.AsyncClient would otherwise fail every request, because its + # methods return coroutines that are never awaited. + if http_client is not None and not isinstance(http_client, httpx.Client): + raise TypeError( + f"http_client must be an httpx.Client, but was {type(http_client).__name__}." + ) + + +def _clean_header_value(name: str, value: str) -> str: + # Callers without a type checker may pass None, for example from an unset + # environment variable. + if not isinstance(value, str): + raise TypeError(f"{name} must be a str, but was {type(value).__name__}.") + # Values read from a file or a mounted secret often end with a newline, + # which httpx would reject on every request. + cleaned = value.strip() + if not cleaned: + raise ValueError(f"{name} must not be empty.") + if _INVALID_HEADER_VALUE_CHARACTERS.search(cleaned): + raise ValueError( + f"{name} must contain only printable ASCII characters, so it can be sent in an HTTP header." + ) + return cleaned def _validate_positive_duration(name: str, value: timedelta) -> None: diff --git a/tests/test_octopus_feature_provider.py b/tests/test_octopus_feature_provider.py index 4760cfc..260a0ef 100644 --- a/tests/test_octopus_feature_provider.py +++ b/tests/test_octopus_feature_provider.py @@ -19,7 +19,7 @@ from openfeature.client import OpenFeatureClient from openfeature.evaluation_context import EvaluationContext from openfeature.event import EventDetails, ProviderEvent -from openfeature.exception import ErrorCode, FlagNotFoundError +from openfeature.exception import ErrorCode, ProviderNotReadyError from openfeature.flag_evaluation import Reason from openfeature.provider import AbstractProvider, ProviderStatus @@ -31,10 +31,15 @@ from octopus_openfeature_provider._feature_flag_evaluator_cache import ( POLLING_THREAD_NAME, ) -from octopus_openfeature_provider._octopus_feature_provider import MAX_CACHE_DURATION +from octopus_openfeature_provider._octopus_feature_provider import ( + MAX_CACHE_DURATION, + PROVIDER_NOT_READY_MESSAGE, +) pytestmark = pytest.mark.usefixtures("reset_the_sdk") +LOGGER = "octopus_openfeature_provider" + MANIFEST = """ [ { "slug": "enabled-feature", "value": true, "reason": "The flag is enabled for this environment." }, @@ -136,22 +141,30 @@ def test_set_provider_initializes_in_the_background( assert client.get_boolean_value("enabled-feature", False) is True -def test_when_the_fetch_fails_the_provider_is_ready_and_every_flag_is_missing( +# A 404 is what a wrong client identifier gets. +@pytest.mark.parametrize("status", [404, 500]) +def test_when_the_fetch_fails_every_evaluation_reports_provider_not_ready( feature_flags_server: FakeFeatureFlagsServer, + caplog: pytest.LogCaptureFixture, + status: int, ) -> None: feature_flags_server.evaluations.body = MANIFEST - feature_flags_server.evaluations.status = 500 + feature_flags_server.evaluations.status = status - client = client_for(feature_flags_server) + with caplog.at_level(logging.WARNING, logger=LOGGER): + client = client_for(feature_flags_server) + details = client.get_boolean_details("enabled-feature", False) assert client.get_provider_status() == ProviderStatus.READY - details = client.get_boolean_details("enabled-feature", False) assert details.value is False assert details.reason == Reason.ERROR - assert details.error_code == ErrorCode.FLAG_NOT_FOUND + assert details.error_code == ErrorCode.PROVIDER_NOT_READY + assert details.error_message == PROVIDER_NOT_READY_MESSAGE + # The slug isn't the problem, so the log doesn't blame it. + assert not any("slug" in record.getMessage() for record in caplog.records) -def test_when_the_server_is_unreachable_the_provider_is_ready_and_every_flag_is_missing( +def test_when_the_server_is_unreachable_every_evaluation_reports_provider_not_ready( feature_flags_server: FakeFeatureFlagsServer, ) -> None: # Nothing listens on port 1, so the request raises rather than returning @@ -163,6 +176,27 @@ def test_when_the_server_is_unreachable_the_provider_is_ready_and_every_flag_is_ assert client.get_provider_status() == ProviderStatus.READY details = client.get_boolean_details("enabled-feature", False) assert details.reason == Reason.ERROR + assert details.error_code == ErrorCode.PROVIDER_NOT_READY + + +def test_evaluation_before_initialization_raises_provider_not_ready( + provider: OctopusFeatureProvider, +) -> None: + with pytest.raises(ProviderNotReadyError) as raised: + provider.resolve_boolean_details("enabled-feature", False) + + assert raised.value.error_message == PROVIDER_NOT_READY_MESSAGE + + +def test_a_fetched_manifest_with_no_flags_reports_flag_not_found( + feature_flags_server: FakeFeatureFlagsServer, +) -> None: + feature_flags_server.evaluations.body = "[]" + + details = client_for(feature_flags_server).get_boolean_details( + "enabled-feature", False + ) + assert details.error_code == ErrorCode.FLAG_NOT_FOUND @@ -173,7 +207,6 @@ def test_when_the_server_is_unreachable_the_provider_is_ready_and_every_flag_is_ '[{ "slug": "enabled-feature", "value": false, "reason": "Changed." }]' ) CHANGED_CONTENT_HASH = base64.b64encode(b"\x02").decode() -LOGGER = "octopus_openfeature_provider" def wait_until(condition: Callable[[], bool], timeout: float = 5) -> None: @@ -427,7 +460,7 @@ def test_initializing_again_discards_evaluations_from_the_earlier_start( polling_provider.initialize(EvaluationContext()) - with pytest.raises(FlagNotFoundError): + with pytest.raises(ProviderNotReadyError): polling_provider.resolve_boolean_details("enabled-feature", False) @@ -473,7 +506,7 @@ def test_shutdown_during_initialization_does_not_start_polling( initializing.join(timeout=2) assert not initializing.is_alive() assert polling_threads() == [] - with pytest.raises(FlagNotFoundError): + with pytest.raises(ProviderNotReadyError): polling_provider.resolve_boolean_details("enabled-feature", False) @@ -605,6 +638,22 @@ def test_non_boolean_evaluation_of_a_flag_returns_the_default_with_type_mismatch assert details.error_code == ErrorCode.TYPE_MISMATCH +@NON_BOOLEAN_EVALUATIONS +def test_non_boolean_evaluation_before_a_successful_fetch_reports_provider_not_ready( + feature_flags_server: FakeFeatureFlagsServer, + evaluate: Callable[[Any, str, Any], Any], + default_value: object, +) -> None: + feature_flags_server.evaluations.status = 500 + + details = evaluate( + client_for(feature_flags_server), "enabled-feature", default_value + ) + + assert details.value == default_value + assert details.error_code == ErrorCode.PROVIDER_NOT_READY + + @NON_BOOLEAN_EVALUATIONS def test_non_boolean_evaluation_of_a_missing_flag_returns_the_default_with_flag_not_found( feature_flags_server: FakeFeatureFlagsServer, @@ -711,3 +760,74 @@ def test_rejects_a_duration_that_is_not_a_timedelta(field: str) -> None: with pytest.raises(TypeError, match=field): OctopusFeatureProvider(configuration) + + +@pytest.mark.parametrize("value", ["client-identifier\n", " client-identifier\r\n"]) +def test_strips_whitespace_around_the_client_identifier(value: str) -> None: + configuration = new_configuration() + configuration.client_identifier = value + + provider = OctopusFeatureProvider(configuration) + + assert provider._configuration.client_identifier == "client-identifier" + + +def test_strips_whitespace_around_the_release_version_override() -> None: + configuration = new_configuration() + configuration.release_version_override = "2026.1.0\n" + + provider = OctopusFeatureProvider(configuration) + + assert provider._configuration.release_version_override == "2026.1.0" + + +def test_sends_the_stripped_values_in_its_requests( + feature_flags_server: FakeFeatureFlagsServer, +) -> None: + feature_flags_server.evaluations.body = MANIFEST + configuration = configuration_for( + feature_flags_server, release_version_override="2026.1.0\n" + ) + configuration.client_identifier += "\n" + + api.set_provider_and_wait(OctopusFeatureProvider(configuration)) + + assert api.get_client().get_boolean_value("enabled-feature", False) is True + (request,) = feature_flags_server.requests_to(EVALUATIONS_PATH) + assert request.header("Authorization") == "Bearer client-identifier" + assert request.header("X-Release-Version") == "2026.1.0" + + +@pytest.mark.parametrize("field", ["client_identifier", "release_version_override"]) +@pytest.mark.parametrize("value", ["line\nbreak", "tab\tinside", "caf\u00e9"]) +def test_rejects_a_header_value_with_invalid_characters(field: str, value: str) -> None: + configuration = new_configuration() + setattr(configuration, field, value) + + with pytest.raises(ValueError, match=field): + OctopusFeatureProvider(configuration) + + +@pytest.mark.parametrize("value", ["", " \n"]) +def test_rejects_an_empty_release_version_override(value: str) -> None: + configuration = new_configuration() + configuration.release_version_override = value + + with pytest.raises(ValueError, match="release_version_override"): + OctopusFeatureProvider(configuration) + + +def test_rejects_a_release_version_override_that_is_not_a_string() -> None: + configuration = new_configuration() + configuration.release_version_override = 2026 # type: ignore[assignment] + + with pytest.raises(TypeError, match="release_version_override"): + OctopusFeatureProvider(configuration) + + +def test_rejects_an_async_http_client() -> None: + configuration = new_configuration() + configuration.http_client = httpx.AsyncClient() # type: ignore[assignment] + + with pytest.raises(TypeError, match="http_client"): + OctopusFeatureProvider(configuration)