From f78fa74abdbc005dbf33c9e4d906bdf21a9921c1 Mon Sep 17 00:00:00 2001 From: Marius Ciepluch <11855163+norandom@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:23:52 +0100 Subject: [PATCH] feat(valid-detection-benchmark): define store capability prerequisites --- .env.example | 15 + .../specs/valid-detection-benchmark/tasks.md | 3 +- benchmarks/valid/store_configuration.py | 462 ++++++++++++++++++ ...est_valid_benchmark_store_configuration.py | 370 ++++++++++++++ 4 files changed, 849 insertions(+), 1 deletion(-) create mode 100644 benchmarks/valid/store_configuration.py create mode 100644 tests/test_valid_benchmark_store_configuration.py diff --git a/.env.example b/.env.example index 7c4b7108..6b0fdff1 100644 --- a/.env.example +++ b/.env.example @@ -22,6 +22,21 @@ OPENROUTER_API_KEY= # The bucket must have versioning enabled, a lifecycle rule expiring runs/, S3 Select and readable object tags # (see docs/rustfs.md); the store verifies them at startup and refuses to run otherwise. +# Valid detection benchmark stores. The application verifies preconfigured buckets and policies but never creates +# buckets, changes versioning/lifecycle, provisions credentials, or diagnoses cluster health. +VALID_BENCHMARK_DURABLE_S3_ENDPOINT= +VALID_BENCHMARK_DURABLE_S3_BUCKET= +VALID_BENCHMARK_DURABLE_AWS_ACCESS_KEY_ID= +VALID_BENCHMARK_DURABLE_AWS_SECRET_ACCESS_KEY= +VALID_BENCHMARK_DURABLE_S3_REGION= +VALID_BENCHMARK_DURABLE_AWS_SESSION_TOKEN= +VALID_BENCHMARK_TRANSIENT_S3_ENDPOINT= +VALID_BENCHMARK_TRANSIENT_S3_BUCKET= +VALID_BENCHMARK_TRANSIENT_AWS_ACCESS_KEY_ID= +VALID_BENCHMARK_TRANSIENT_AWS_SECRET_ACCESS_KEY= +VALID_BENCHMARK_TRANSIENT_S3_REGION= +VALID_BENCHMARK_TRANSIENT_AWS_SESSION_TOKEN= + # Operator notifications (Discord). Status of OpenUltraSAST processes and their results for the # system/AI operator -- not developer debugging, and not k3s/ax infra health. See # .kiro/steering/operator-notifications.md. Webhook posts to the operator channel; the operator id diff --git a/.kiro/specs/valid-detection-benchmark/tasks.md b/.kiro/specs/valid-detection-benchmark/tasks.md index 63f08222..992cdd0a 100644 --- a/.kiro/specs/valid-detection-benchmark/tasks.md +++ b/.kiro/specs/valid-detection-benchmark/tasks.md @@ -33,7 +33,7 @@ - Done when equal inputs produce byte-identical identities and malformed, empty, unsupported, or same-key/different-byte inputs fail before projection or scoring. - _Requirements: 7.1, 7.2, 7.3, 8.1, 8.4, 8.5, 8.6, 10.3_ - _Boundary: Benchmark Artifact Contracts_ -- [ ] 1.3 Define store settings, retention profiles, and capability prerequisites +- [x] 1.3 Define store settings, retention profiles, and capability prerequisites - Load purpose-specific durable and transient store settings from environment names without serializing endpoints or credentials into artifacts. - Represent required versioning, conditional-write, current-version, and noncurrent-version retention properties as validated capability profiles. - Keep bucket creation, lifecycle mutation, cluster health, and credential provisioning outside application authority. @@ -413,3 +413,4 @@ - Task 1.1 pins the exact public V3 facade and delegates decoding and complete replay validation to detection-core; frozen V2 and pilot artifacts remain byte-identical, read-only compatibility inputs with no V3 conversion path. - Task 1.2 adds a replacement-only canonical artifact and reference contract with closed kinds/access classes and exact content identity; the existing V2 substrate remains readable but cannot authorize replacement admission. +- Task 1.3 separates durable and transient store namespaces through canonical endpoint identity, requires versioning/conditional writes and purpose-specific current/noncurrent retention, emits only redacted closed startup reports, and denies administrator-owned operations. diff --git a/benchmarks/valid/store_configuration.py b/benchmarks/valid/store_configuration.py new file mode 100644 index 00000000..198e23fe --- /dev/null +++ b/benchmarks/valid/store_configuration.py @@ -0,0 +1,462 @@ +"""Fail-closed store configuration for the replacement valid benchmark. + +Runtime endpoints and credentials stay in this module's non-serializable settings +objects. Shared artifacts receive only closed capability status and policy digests. +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from dataclasses import dataclass, field +from enum import StrEnum +from ipaddress import ip_address +from urllib.parse import urlsplit + +from openultrasast.core.canonical import JsonValue, bytes_digest, canonical_bytes + +STORE_STARTUP_REPORT_SCHEMA = "openultrasast.valid-detection-benchmark.store-startup.v1" +DEFAULT_DURABLE_NONCURRENT_EXPIRY_DAYS = 30 +_BUCKET_NAME = re.compile(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]") + + +class StorePurpose(StrEnum): + """Purpose-specific stores with independent retention policy.""" + + DURABLE = "durable" + TRANSIENT = "transient" + + +class StoreConfigurationReason(StrEnum): + MISSING = "missing" + INVALID = "invalid" + + +class StoreCapabilityStatus(StrEnum): + READY = "ready" + UNSUPPORTED = "unsupported" + + +class StoreCapabilityReason(StrEnum): + VERSIONING_REQUIRED = "versioning_required" + CONDITIONAL_CREATE_REQUIRED = "conditional_create_required" + CONDITIONAL_UPDATE_REQUIRED = "conditional_update_required" + CURRENT_RETENTION_MISMATCH = "current_retention_mismatch" + NONCURRENT_RETENTION_MISMATCH = "noncurrent_retention_mismatch" + + +class StoreStartupStatus(StrEnum): + READY = "ready" + MISSING_CONFIGURATION = "missing_configuration" + UNSUPPORTED_CAPABILITY = "unsupported_capability" + + +class StoreStartupReason(StrEnum): + DURABLE_CONFIGURATION_MISSING = "durable_configuration_missing" + DURABLE_CONFIGURATION_INVALID = "durable_configuration_invalid" + TRANSIENT_CONFIGURATION_MISSING = "transient_configuration_missing" + TRANSIENT_CONFIGURATION_INVALID = "transient_configuration_invalid" + PURPOSE_CONFIGURATION_COLLISION = "purpose_configuration_collision" + DURABLE_CAPABILITY_EVIDENCE_MISSING = "durable_capability_evidence_missing" + TRANSIENT_CAPABILITY_EVIDENCE_MISSING = "transient_capability_evidence_missing" + DURABLE_CAPABILITY_UNSUPPORTED = "durable_capability_unsupported" + TRANSIENT_CAPABILITY_UNSUPPORTED = "transient_capability_unsupported" + + +class ApplicationStoreOperation(StrEnum): + READ_OBJECT = "read_object" + CREATE_OBJECT_IF_ABSENT = "create_object_if_absent" + CONDITIONAL_UPDATE = "conditional_update" + LIST_OBJECTS = "list_objects" + READ_VERSIONING = "read_versioning" + READ_LIFECYCLE = "read_lifecycle" + CREATE_BUCKET = "create_bucket" + SET_BUCKET_VERSIONING = "set_bucket_versioning" + PUT_LIFECYCLE_POLICY = "put_lifecycle_policy" + PROVISION_CREDENTIALS = "provision_credentials" + PROBE_CLUSTER_HEALTH = "probe_cluster_health" + + +ADMINISTRATOR_OPERATIONS = frozenset( + { + ApplicationStoreOperation.CREATE_BUCKET, + ApplicationStoreOperation.SET_BUCKET_VERSIONING, + ApplicationStoreOperation.PUT_LIFECYCLE_POLICY, + ApplicationStoreOperation.PROVISION_CREDENTIALS, + ApplicationStoreOperation.PROBE_CLUSTER_HEALTH, + } +) + + +class StoreConfigurationError(ValueError): + """Configuration is absent or invalid without disclosing its values.""" + + def __init__(self, purpose: StorePurpose, reason: StoreConfigurationReason, keys: tuple[str, ...]) -> None: + self.purpose = purpose + self.reason = reason + self.keys = keys + super().__init__(f"{purpose.value}_store_configuration_{reason.value}: {','.join(keys)}") + + +class StoreAuthorityError(PermissionError): + """An application identity requested an administrator-owned operation.""" + + +class StoreStartupError(RuntimeError): + """Startup prerequisites failed before benchmark execution.""" + + def __init__(self, report: StoreStartupReport) -> None: + self.report = report + reasons = ",".join(reason.value for reason in report.reasons) + super().__init__(f"benchmark_store_startup_refused:{report.status.value}:{reasons}") + + +@dataclass(frozen=True) +class StoreEnvironmentKeys: + endpoint: str + bucket: str + access_key_id: str + secret_access_key: str + region: str + session_token: str + + @property + def required(self) -> tuple[str, ...]: + return (self.endpoint, self.bucket, self.access_key_id, self.secret_access_key) + + @property + def optional(self) -> tuple[str, ...]: + return (self.region, self.session_token) + + +@dataclass(frozen=True) +class StoreSettings: + purpose: StorePurpose + endpoint: str = field(repr=False) + bucket: str + access_key_id: str = field(repr=False) + secret_access_key: str = field(repr=False) + region: str | None = field(default=None, repr=False) + session_token: str | None = field(default=None, repr=False) + + +@dataclass(frozen=True) +class StoreConfiguration: + durable: StoreSettings + transient: StoreSettings + + +@dataclass(frozen=True) +class RetentionProfile: + purpose: StorePurpose + versioning_required: bool + conditional_create_required: bool + conditional_update_required: bool + current_version_expiry_days: int | None + noncurrent_version_expiry_days: int | None + + def __post_init__(self) -> None: + requirements = ( + self.versioning_required, + self.conditional_create_required, + self.conditional_update_required, + ) + if any(type(value) is not bool or not value for value in requirements): + raise StoreConfigurationError(self.purpose, StoreConfigurationReason.INVALID, ("capability_profile",)) + _validate_retention(self.purpose, self.current_version_expiry_days, self.noncurrent_version_expiry_days) + + +@dataclass(frozen=True) +class StoreCapabilityEvidence: + purpose: StorePurpose + versioning_enabled: bool + conditional_create: bool + conditional_update: bool + current_version_expiry_days: int | None + noncurrent_version_expiry_days: int | None + + def __post_init__(self) -> None: + capability_flags = (self.versioning_enabled, self.conditional_create, self.conditional_update) + if any(type(value) is not bool for value in capability_flags): + raise StoreConfigurationError(self.purpose, StoreConfigurationReason.INVALID, ("capability_evidence",)) + _validate_optional_days(self.current_version_expiry_days, self.purpose) + _validate_optional_days(self.noncurrent_version_expiry_days, self.purpose) + + +@dataclass(frozen=True) +class StoreCapabilityReport: + purpose: StorePurpose + status: StoreCapabilityStatus + reasons: tuple[StoreCapabilityReason, ...] + profile_digest: str + + +@dataclass(frozen=True) +class StoreStartupReport: + status: StoreStartupStatus + reasons: tuple[StoreStartupReason, ...] + capabilities: tuple[StoreCapabilityReport, ...] + + +_ENVIRONMENT_KEYS = { + purpose: StoreEnvironmentKeys( + *( + f"VALID_BENCHMARK_{purpose.value.upper()}_{suffix}" + for suffix in ( + "S3_ENDPOINT", + "S3_BUCKET", + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + "S3_REGION", + "AWS_SESSION_TOKEN", + ) + ) + ) + for purpose in StorePurpose +} + + +def environment_keys(purpose: StorePurpose) -> StoreEnvironmentKeys: + return _ENVIRONMENT_KEYS[StorePurpose(purpose)] + + +def _hostname_namespace(hostname: str) -> str: + try: + return ip_address(hostname).compressed.lower() + except ValueError: + pass + if any(character.isspace() for character in hostname): + raise ValueError("endpoint hostname is malformed") + try: + canonical = hostname.encode("idna").decode("ascii").lower() + except UnicodeError as error: + raise ValueError("endpoint hostname is malformed") from error + labels = canonical.split(".") + label_pattern = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?") + if not labels or any(label_pattern.fullmatch(label) is None for label in labels): + raise ValueError("endpoint hostname is malformed") + return canonical + + +def _endpoint_namespace(value: str) -> tuple[str, str, int, str]: + try: + parsed = urlsplit(value) + hostname = parsed.hostname + port = parsed.port + except ValueError as error: + raise ValueError("endpoint URL is malformed") from error + scheme = parsed.scheme.lower() + if scheme not in {"http", "https"} or hostname is None: + raise ValueError("endpoint URL is malformed") + if parsed.username is not None or parsed.password is not None or parsed.query or parsed.fragment: + raise ValueError("endpoint URL is ambiguous") + authority = parsed.netloc.rsplit("@", 1)[-1] + if authority.endswith(":"): + raise ValueError("endpoint port is malformed") + effective_port = port if port is not None else {"http": 80, "https": 443}[scheme] + path = "" if parsed.path in {"", "/"} else parsed.path.removesuffix("/") + return (scheme, _hostname_namespace(hostname), effective_port, path) + + +def load_store_settings(purpose: StorePurpose, environ: Mapping[str, str]) -> StoreSettings: + """Load one purpose without placing runtime values in an artifact.""" + purpose = StorePurpose(purpose) + keys = environment_keys(purpose) + missing = tuple(key for key in keys.required if not environ.get(key, "").strip()) + if missing: + raise StoreConfigurationError(purpose, StoreConfigurationReason.MISSING, missing) + endpoint = environ[keys.endpoint].strip() + bucket = environ[keys.bucket].strip() + try: + _endpoint_namespace(endpoint) + endpoint_is_valid = True + except ValueError: + endpoint_is_valid = False + checks = ((keys.endpoint, endpoint_is_valid), (keys.bucket, bool(_BUCKET_NAME.fullmatch(bucket)))) + invalid = tuple(key for key, is_valid in checks if not is_valid) + if invalid: + raise StoreConfigurationError(purpose, StoreConfigurationReason.INVALID, invalid) + return StoreSettings( + purpose=purpose, + endpoint=endpoint, + bucket=bucket, + access_key_id=environ[keys.access_key_id].strip(), + secret_access_key=environ[keys.secret_access_key].strip(), + region=environ.get(keys.region, "").strip() or None, + session_token=environ.get(keys.session_token, "").strip() or None, + ) + + +def load_store_configuration(environ: Mapping[str, str]) -> StoreConfiguration: + durable = load_store_settings(StorePurpose.DURABLE, environ) + transient = load_store_settings(StorePurpose.TRANSIENT, environ) + if _same_namespace(durable, transient): + raise StoreConfigurationError( + StorePurpose.TRANSIENT, + StoreConfigurationReason.INVALID, + ("purpose_namespace_collision",), + ) + return StoreConfiguration(durable=durable, transient=transient) + + +def _same_namespace(durable: StoreSettings, transient: StoreSettings) -> bool: + return _endpoint_namespace(durable.endpoint) == _endpoint_namespace(transient.endpoint) and durable.bucket == transient.bucket + + +def _positive_days(value: object) -> bool: + return not isinstance(value, bool) and isinstance(value, int) and value > 0 + + +def _validate_optional_days(value: int | None, purpose: StorePurpose) -> None: + if value is not None and not _positive_days(value): + raise StoreConfigurationError(purpose, StoreConfigurationReason.INVALID, ("retention_days",)) + + +def _validate_retention(purpose: StorePurpose, current: int | None, noncurrent: int | None) -> None: + if purpose is StorePurpose.DURABLE: + if current is not None or not _positive_days(noncurrent): + raise StoreConfigurationError(purpose, StoreConfigurationReason.INVALID, ("durable_retention",)) + return + if not _positive_days(current) or not _positive_days(noncurrent): + raise StoreConfigurationError(purpose, StoreConfigurationReason.INVALID, ("transient_retention",)) + + +def default_retention_profiles( + *, + current_expiry_days: int, + noncurrent_expiry_days: int, + durable_noncurrent_expiry_days: int = DEFAULT_DURABLE_NONCURRENT_EXPIRY_DAYS, +) -> dict[StorePurpose, RetentionProfile]: + common = {"versioning_required": True, "conditional_create_required": True, "conditional_update_required": True} + return { + StorePurpose.DURABLE: RetentionProfile( + StorePurpose.DURABLE, + **common, + current_version_expiry_days=None, + noncurrent_version_expiry_days=durable_noncurrent_expiry_days, + ), + StorePurpose.TRANSIENT: RetentionProfile( + StorePurpose.TRANSIENT, + **common, + current_version_expiry_days=current_expiry_days, + noncurrent_version_expiry_days=noncurrent_expiry_days, + ), + } + + +def _profile_digest(profile: RetentionProfile) -> str: + value: JsonValue = { + "purpose": profile.purpose.value, + "versioning_required": profile.versioning_required, + "conditional_create_required": profile.conditional_create_required, + "conditional_update_required": profile.conditional_update_required, + "current_version_expiry_days": profile.current_version_expiry_days, + "noncurrent_version_expiry_days": profile.noncurrent_version_expiry_days, + } + return bytes_digest(canonical_bytes(value)) + + +def verify_store_capabilities(profile: RetentionProfile, evidence: StoreCapabilityEvidence) -> StoreCapabilityReport: + if profile.purpose is not evidence.purpose: + raise StoreConfigurationError(profile.purpose, StoreConfigurationReason.INVALID, ("capability_purpose",)) + comparisons = ( + (not evidence.versioning_enabled, StoreCapabilityReason.VERSIONING_REQUIRED), + (not evidence.conditional_create, StoreCapabilityReason.CONDITIONAL_CREATE_REQUIRED), + (not evidence.conditional_update, StoreCapabilityReason.CONDITIONAL_UPDATE_REQUIRED), + ( + evidence.current_version_expiry_days != profile.current_version_expiry_days, + StoreCapabilityReason.CURRENT_RETENTION_MISMATCH, + ), + ( + evidence.noncurrent_version_expiry_days != profile.noncurrent_version_expiry_days, + StoreCapabilityReason.NONCURRENT_RETENTION_MISMATCH, + ), + ) + reasons = tuple(reason for failed, reason in comparisons if failed) + status = StoreCapabilityStatus.UNSUPPORTED if reasons else StoreCapabilityStatus.READY + return StoreCapabilityReport(profile.purpose, status, reasons, _profile_digest(profile)) + + +def _configuration_reason(purpose: StorePurpose, reason: StoreConfigurationReason) -> StoreStartupReason: + return StoreStartupReason(f"{purpose.value}_configuration_{reason.value}") + + +def _evidence_missing_reason(purpose: StorePurpose) -> StoreStartupReason: + return StoreStartupReason(f"{purpose.value}_capability_evidence_missing") + + +def _unsupported_reason(purpose: StorePurpose) -> StoreStartupReason: + return StoreStartupReason(f"{purpose.value}_capability_unsupported") + + +def assess_store_startup( + environ: Mapping[str, str], + evidence_by_purpose: Mapping[StorePurpose, StoreCapabilityEvidence], + *, + current_expiry_days: int = 14, + noncurrent_expiry_days: int = 1, +) -> StoreStartupReport: + profiles = default_retention_profiles( + current_expiry_days=current_expiry_days, + noncurrent_expiry_days=noncurrent_expiry_days, + ) + startup_reasons: list[StoreStartupReason] = [] + reports: list[StoreCapabilityReport] = [] + settings_by_purpose: dict[StorePurpose, StoreSettings] = {} + for purpose in StorePurpose: + try: + settings_by_purpose[purpose] = load_store_settings(purpose, environ) + except StoreConfigurationError as error: + startup_reasons.append(_configuration_reason(purpose, error.reason)) + continue + evidence = evidence_by_purpose.get(purpose) + if evidence is None: + startup_reasons.append(_evidence_missing_reason(purpose)) + continue + report = verify_store_capabilities(profiles[purpose], evidence) + reports.append(report) + if report.status is StoreCapabilityStatus.UNSUPPORTED: + startup_reasons.append(_unsupported_reason(purpose)) + if len(settings_by_purpose) == len(StorePurpose) and _same_namespace( + settings_by_purpose[StorePurpose.DURABLE], + settings_by_purpose[StorePurpose.TRANSIENT], + ): + startup_reasons.append(StoreStartupReason.PURPOSE_CONFIGURATION_COLLISION) + if any("configuration" in reason.value for reason in startup_reasons): + status = StoreStartupStatus.MISSING_CONFIGURATION + elif startup_reasons: + status = StoreStartupStatus.UNSUPPORTED_CAPABILITY + else: + status = StoreStartupStatus.READY + return StoreStartupReport(status, tuple(startup_reasons), tuple(reports)) + + +def require_store_startup(report: StoreStartupReport) -> None: + if report.status is not StoreStartupStatus.READY: + raise StoreStartupError(report) + + +def canonical_startup_report_bytes(report: StoreStartupReport) -> bytes: + """Serialize only safe closed status, reasons, and policy identities.""" + capabilities: tuple[JsonValue, ...] = tuple( + { + "purpose": item.purpose.value, + "status": item.status.value, + "reasons": tuple(reason.value for reason in item.reasons), + "profile_digest": item.profile_digest, + } + for item in report.capabilities + ) + value: JsonValue = { + "schema_version": STORE_STARTUP_REPORT_SCHEMA, + "status": report.status.value, + "reasons": tuple(reason.value for reason in report.reasons), + "capabilities": capabilities, + } + return canonical_bytes(value) + + +def require_application_operation(operation: ApplicationStoreOperation) -> None: + operation = ApplicationStoreOperation(operation) + if operation in ADMINISTRATOR_OPERATIONS: + raise StoreAuthorityError(f"administrator_owned_operation:{operation.value}") diff --git a/tests/test_valid_benchmark_store_configuration.py b/tests/test_valid_benchmark_store_configuration.py new file mode 100644 index 00000000..320809eb --- /dev/null +++ b/tests/test_valid_benchmark_store_configuration.py @@ -0,0 +1,370 @@ +"""Store settings, retention, capability, and application-authority contracts.""" + +from __future__ import annotations + +import json +import sys +from dataclasses import replace +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from benchmarks.valid import store_configuration as store # noqa: E402 + + +def _environment() -> dict[str, str]: + return { + "VALID_BENCHMARK_DURABLE_S3_ENDPOINT": "https://durable.invalid:9000", + "VALID_BENCHMARK_DURABLE_S3_BUCKET": "valid-benchmark-durable", + "VALID_BENCHMARK_DURABLE_AWS_ACCESS_KEY_ID": "durable-key", + "VALID_BENCHMARK_DURABLE_AWS_SECRET_ACCESS_KEY": "durable-secret", + "VALID_BENCHMARK_TRANSIENT_S3_ENDPOINT": "https://transient.invalid:9000", + "VALID_BENCHMARK_TRANSIENT_S3_BUCKET": "valid-benchmark-runs", + "VALID_BENCHMARK_TRANSIENT_AWS_ACCESS_KEY_ID": "transient-key", + "VALID_BENCHMARK_TRANSIENT_AWS_SECRET_ACCESS_KEY": "transient-secret", + } + + +def _evidence( + purpose: store.StorePurpose, + *, + versioning: bool = True, + conditional_create: bool = True, + conditional_update: bool = True, +) -> store.StoreCapabilityEvidence: + current = None if purpose is store.StorePurpose.DURABLE else 14 + noncurrent = 30 if purpose is store.StorePurpose.DURABLE else 1 + return store.StoreCapabilityEvidence( + purpose=purpose, + versioning_enabled=versioning, + conditional_create=conditional_create, + conditional_update=conditional_update, + current_version_expiry_days=current, + noncurrent_version_expiry_days=noncurrent, + ) + + +def _all_evidence() -> dict[store.StorePurpose, store.StoreCapabilityEvidence]: + return {purpose: _evidence(purpose) for purpose in store.StorePurpose} + + +def test_loads_separate_runtime_settings_without_repr_disclosure() -> None: + environment = { + **_environment(), + "VALID_BENCHMARK_DURABLE_S3_REGION": "eu-test-1", + "VALID_BENCHMARK_DURABLE_AWS_SESSION_TOKEN": "durable-token", + } + + configuration = store.load_store_configuration(environment) + + assert configuration.durable.bucket == "valid-benchmark-durable" + assert configuration.durable.region == "eu-test-1" + assert configuration.durable.session_token == "durable-token" + assert configuration.transient.bucket == "valid-benchmark-runs" + displayed = repr(configuration) + for private_value in ( + "https://durable.invalid:9000", + "durable-key", + "durable-secret", + "durable-token", + "https://transient.invalid:9000", + "transient-key", + "transient-secret", + ): + assert private_value not in displayed + + +def test_direct_load_rejects_a_shared_purpose_namespace_without_disclosure() -> None: + environment = _environment() + environment["VALID_BENCHMARK_TRANSIENT_S3_ENDPOINT"] = environment["VALID_BENCHMARK_DURABLE_S3_ENDPOINT"] + environment["VALID_BENCHMARK_TRANSIENT_S3_BUCKET"] = environment["VALID_BENCHMARK_DURABLE_S3_BUCKET"] + + with pytest.raises(store.StoreConfigurationError) as caught: + store.load_store_configuration(environment) + + assert caught.value.reason is store.StoreConfigurationReason.INVALID + assert "purpose_namespace_collision" in str(caught.value) + for private_value in environment.values(): + assert private_value not in str(caught.value) + + +@pytest.mark.parametrize( + "durable_endpoint,transient_endpoint", + ( + ("HTTPS://STORE.INVALID:9000", "https://store.invalid:9000"), + ("https://store.invalid", "https://store.invalid:443"), + ("http://store.invalid", "http://store.invalid:80/"), + ("https://store.invalid/base", "https://store.invalid/base/"), + ("https://BÜCHER.invalid", "https://xn--bcher-kva.invalid:443/"), + ("https://[2001:db8::1]", "https://[2001:0DB8:0:0:0:0:0:1]:443/"), + ), +) +def test_equivalent_endpoint_spellings_cannot_bypass_purpose_isolation( + durable_endpoint: str, + transient_endpoint: str, +) -> None: + environment = _environment() + environment["VALID_BENCHMARK_DURABLE_S3_ENDPOINT"] = durable_endpoint + environment["VALID_BENCHMARK_TRANSIENT_S3_ENDPOINT"] = transient_endpoint + environment["VALID_BENCHMARK_TRANSIENT_S3_BUCKET"] = environment["VALID_BENCHMARK_DURABLE_S3_BUCKET"] + + with pytest.raises(store.StoreConfigurationError, match="purpose_namespace_collision") as caught: + store.load_store_configuration(environment) + report = store.assess_store_startup(environment, _all_evidence()) + + assert report.status is store.StoreStartupStatus.MISSING_CONFIGURATION + assert store.StoreStartupReason.PURPOSE_CONFIGURATION_COLLISION in report.reasons + encoded = store.canonical_startup_report_bytes(report) + for private_value in environment.values(): + assert private_value not in str(caught.value) + assert private_value.encode() not in encoded + + +@pytest.mark.parametrize( + "durable_endpoint,transient_endpoint", + ( + ("https://store.invalid/base", "https://store.invalid/Base"), + ("https://store.invalid/one/", "https://store.invalid/two/"), + ), +) +def test_distinct_case_sensitive_endpoint_prefixes_remain_separate( + durable_endpoint: str, + transient_endpoint: str, +) -> None: + environment = _environment() + environment["VALID_BENCHMARK_DURABLE_S3_ENDPOINT"] = durable_endpoint + environment["VALID_BENCHMARK_TRANSIENT_S3_ENDPOINT"] = transient_endpoint + environment["VALID_BENCHMARK_TRANSIENT_S3_BUCKET"] = environment["VALID_BENCHMARK_DURABLE_S3_BUCKET"] + + configuration = store.load_store_configuration(environment) + + assert configuration.durable.endpoint == durable_endpoint + assert configuration.transient.endpoint == transient_endpoint + + +@pytest.mark.parametrize( + "endpoint", + ( + "https://user@store.invalid", + "https://store.invalid/base?query=1", + "https://store.invalid/base#fragment", + "https://store.invalid:99999", + "https://host name.invalid", + "https://[not-an-ipv6-address]", + ), +) +def test_endpoint_namespace_rejects_ambiguous_or_malformed_urls_without_disclosure(endpoint: str) -> None: + environment = _environment() + environment["VALID_BENCHMARK_DURABLE_S3_ENDPOINT"] = endpoint + + with pytest.raises(store.StoreConfigurationError) as caught: + store.load_store_settings(store.StorePurpose.DURABLE, environment) + + assert caught.value.reason is store.StoreConfigurationReason.INVALID + assert endpoint not in str(caught.value) + + +@pytest.mark.parametrize("purpose", tuple(store.StorePurpose)) +def test_missing_and_invalid_configuration_name_only_environment_keys( + purpose: store.StorePurpose, +) -> None: + environment = _environment() + missing_key = store.environment_keys(purpose).secret_access_key + secret = environment.pop(missing_key) + + with pytest.raises(store.StoreConfigurationError) as caught: + store.load_store_settings(purpose, environment) + + assert caught.value.reason is store.StoreConfigurationReason.MISSING + assert missing_key in str(caught.value) + assert secret not in str(caught.value) + + environment[missing_key] = secret + environment[store.environment_keys(purpose).endpoint] = "host-without-scheme" + with pytest.raises(store.StoreConfigurationError) as invalid: + store.load_store_settings(purpose, environment) + assert invalid.value.reason is store.StoreConfigurationReason.INVALID + assert "host-without-scheme" not in str(invalid.value) + + +def test_default_profiles_separate_durable_and_transient_retention() -> None: + profiles = store.default_retention_profiles(current_expiry_days=14, noncurrent_expiry_days=1) + + durable = profiles[store.StorePurpose.DURABLE] + transient = profiles[store.StorePurpose.TRANSIENT] + assert durable.current_version_expiry_days is None + assert durable.noncurrent_version_expiry_days == 30 + assert transient.current_version_expiry_days == 14 + assert transient.noncurrent_version_expiry_days == 1 + assert all( + (profile.versioning_required, profile.conditional_create_required, profile.conditional_update_required) == (True, True, True) + for profile in profiles.values() + ) + + +@pytest.mark.parametrize( + "purpose,current,noncurrent", + ( + ("durable", 1, None), + ("durable", None, None), + ("durable", None, 0), + ("transient", None, 1), + ("transient", 14, 0), + ("transient", True, 1), + ), +) +def test_invalid_retention_profiles_are_refused( + purpose: str, + current: int | None, + noncurrent: int | None, +) -> None: + with pytest.raises(store.StoreConfigurationError): + store.RetentionProfile( + purpose=store.StorePurpose(purpose), + versioning_required=True, + conditional_create_required=True, + conditional_update_required=True, + current_version_expiry_days=current, + noncurrent_version_expiry_days=noncurrent, + ) + + +def test_capability_evidence_requires_closed_boolean_values() -> None: + with pytest.raises(store.StoreConfigurationError): + store.StoreCapabilityEvidence( + purpose=store.StorePurpose.DURABLE, + versioning_enabled=1, # type: ignore[arg-type] + conditional_create=True, + conditional_update=True, + current_version_expiry_days=None, + noncurrent_version_expiry_days=None, + ) + + +@pytest.mark.parametrize( + "mutation,reason", + ( + ({"versioning_enabled": False}, "versioning_required"), + ({"conditional_create": False}, "conditional_create_required"), + ({"conditional_update": False}, "conditional_update_required"), + ({"current_version_expiry_days": 15}, "current_retention_mismatch"), + ({"noncurrent_version_expiry_days": 2}, "noncurrent_retention_mismatch"), + ), +) +def test_capability_report_uses_closed_unsupported_reasons( + mutation: dict[str, object], + reason: str, +) -> None: + profiles = store.default_retention_profiles(current_expiry_days=14, noncurrent_expiry_days=1) + evidence = replace(_evidence(store.StorePurpose.TRANSIENT), **mutation) + + report = store.verify_store_capabilities(profiles[store.StorePurpose.TRANSIENT], evidence) + + assert report.status is store.StoreCapabilityStatus.UNSUPPORTED + assert store.StoreCapabilityReason(reason) in report.reasons + + +@pytest.mark.parametrize("noncurrent", (None, 31)) +def test_durable_noncurrent_expiry_is_required_and_exact(noncurrent: int | None) -> None: + profiles = store.default_retention_profiles(current_expiry_days=14, noncurrent_expiry_days=1) + evidence = replace( + _evidence(store.StorePurpose.DURABLE), + noncurrent_version_expiry_days=noncurrent, + ) + + report = store.verify_store_capabilities(profiles[store.StorePurpose.DURABLE], evidence) + + assert report.status is store.StoreCapabilityStatus.UNSUPPORTED + assert store.StoreCapabilityReason.NONCURRENT_RETENTION_MISMATCH in report.reasons + + +def test_startup_distinguishes_missing_and_unsupported_from_ready() -> None: + missing_environment = _environment() + missing_environment.pop("VALID_BENCHMARK_DURABLE_S3_BUCKET") + missing = store.assess_store_startup(missing_environment, _all_evidence()) + assert missing.status is store.StoreStartupStatus.MISSING_CONFIGURATION + assert store.StoreStartupReason.DURABLE_CONFIGURATION_MISSING in missing.reasons + + unsupported_evidence = _all_evidence() + unsupported_evidence[store.StorePurpose.TRANSIENT] = _evidence( + store.StorePurpose.TRANSIENT, + conditional_update=False, + ) + unsupported = store.assess_store_startup(_environment(), unsupported_evidence) + assert unsupported.status is store.StoreStartupStatus.UNSUPPORTED_CAPABILITY + assert store.StoreStartupReason.TRANSIENT_CAPABILITY_UNSUPPORTED in unsupported.reasons + + ready = store.assess_store_startup(_environment(), _all_evidence()) + assert ready.status is store.StoreStartupStatus.READY + assert ready.reasons == () + + +def test_startup_rejects_a_shared_purpose_namespace_with_closed_redacted_reason() -> None: + environment = _environment() + environment["VALID_BENCHMARK_TRANSIENT_S3_ENDPOINT"] = environment["VALID_BENCHMARK_DURABLE_S3_ENDPOINT"] + environment["VALID_BENCHMARK_TRANSIENT_S3_BUCKET"] = environment["VALID_BENCHMARK_DURABLE_S3_BUCKET"] + + report = store.assess_store_startup(environment, _all_evidence()) + + assert report.status is store.StoreStartupStatus.MISSING_CONFIGURATION + assert store.StoreStartupReason.PURPOSE_CONFIGURATION_COLLISION in report.reasons + encoded = store.canonical_startup_report_bytes(report) + for private_value in environment.values(): + assert private_value.encode() not in encoded + + +def test_missing_probe_evidence_is_an_unsupported_prerequisite() -> None: + evidence = _all_evidence() + evidence.pop(store.StorePurpose.DURABLE) + + report = store.assess_store_startup(_environment(), evidence) + + assert report.status is store.StoreStartupStatus.UNSUPPORTED_CAPABILITY + assert store.StoreStartupReason.DURABLE_CAPABILITY_EVIDENCE_MISSING in report.reasons + + +def test_startup_refusal_carries_only_closed_status_and_reasons() -> None: + evidence = _all_evidence() + evidence[store.StorePurpose.DURABLE] = _evidence(store.StorePurpose.DURABLE, versioning=False) + report = store.assess_store_startup(_environment(), evidence) + + with pytest.raises(store.StoreStartupError) as caught: + store.require_store_startup(report) + + assert caught.value.report == report + assert "clean" not in str(caught.value).lower() + assert "versioning" not in str(caught.value).lower() + + +def test_safe_startup_artifact_excludes_settings_and_is_deterministic() -> None: + report = store.assess_store_startup(_environment(), _all_evidence()) + + first = store.canonical_startup_report_bytes(report) + second = store.canonical_startup_report_bytes(report) + decoded = json.loads(first) + + assert first == second + assert decoded["status"] == "ready" + assert tuple(item["purpose"] for item in decoded["capabilities"]) == ("durable", "transient") + for private_value in _environment().values(): + assert private_value.encode() not in first + + +def test_application_authority_denies_every_administrator_operation() -> None: + for operation in store.ApplicationStoreOperation: + if operation in store.ADMINISTRATOR_OPERATIONS: + with pytest.raises(store.StoreAuthorityError, match="administrator_owned_operation"): + store.require_application_operation(operation) + else: + store.require_application_operation(operation) + + +def test_environment_example_lists_names_with_blank_values() -> None: + example = Path(".env.example").read_text() + for purpose in store.StorePurpose: + keys = store.environment_keys(purpose) + for key in keys.required + keys.optional: + assert f"{key}=" in example + assert not next(line for line in example.splitlines() if line.startswith(f"{key}="))[len(key) + 1 :]