From 190ad99d930741d28cbfb7da259d58d356660f82 Mon Sep 17 00:00:00 2001 From: Daniel Boles Date: Sun, 6 Dec 2026 07:38:26 +0700 Subject: [PATCH] Add store_organization_secret that keeps the value out of errors Who: Admins and CI jobs that store or rotate organization secrets. What: New store_organization_secret with local checks and name confirmation. set_/put_organization_secret keep their behavior and only gain redacted problem text and detached errors. Where: proofline/client.py, proofline/_transport.py, regenerated operations.py, scripts/contracts.py, README.md, tests/test_secrets.py. When: On every secret write and every problem it returns. Why: A problem that echoed the value reached ProoflineError.detail, and errors kept chains and frames that could hold the request body. How verified: pytest 352 passed, 0 failed, 0 errors (before: 237 passed, 1 known Windows failure); ruff, mypy, contracts, generate pass. --- README.md | 25 ++ proofline/_generated/api/operations.py | 76 ---- proofline/_transport.py | 54 ++- proofline/client.py | 224 +++++++++++ scripts/contracts.py | 9 +- tests/test_secrets.py | 506 +++++++++++++++++++++++++ 6 files changed, 812 insertions(+), 82 deletions(-) create mode 100644 tests/test_secrets.py diff --git a/README.md b/README.md index 7ac1b36f..ecaec348 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,31 @@ with ProoflineClient() as client: The response names the recorded report and its covered and instrumented line counts. An identical upload returns that report with `created=False`. Refused reports raise `ProoflineError`. Uploading a report does not establish a check verdict. +## Organization secrets + +`store_organization_secret` stores a write-only value under a name that configuration documents refer to. The token needs `org:configure`. Pass the value as a `SecretStr` so that it stays masked in your own frames too. + +```python +import os +from uuid import UUID +from pydantic import SecretStr +from proofline import ProoflineClient + +with ProoflineClient() as client: + stored = client.store_organization_secret( + UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), + "DEPLOY_KEY", + SecretStr(os.environ["DEPLOY_KEY"]), + ) + print(stored.name) +``` + +The name must be an ASCII letter followed by up to 63 ASCII letters, digits, `_` or `-`, and the value must be 1 to 32,768 bytes in UTF-8. Anything else raises `ValueError` before a request, and the error never chains the value. The write is sent once and never retried, even after a 429 or 503 with `Retry-After`. A timeout or lost connection leaves its outcome unknown; repeating the same call is safe because a write replaces the earlier value. The result counts only if the server confirms the name the write was sent under; any other success body raises `urn:proofline:sdk:invalid-response`. + +Server problem text that repeats the value, as sent, JSON-escaped or as a Python repr, carries `[redacted]` in its place, like the token. The redaction applies only to that call, including concurrent calls on one client. A raised `ProoflineError` keeps no chained exception and no HTTP-layer traceback frame, so no SDK frame gives an error reporter that records local variables the request body. Your own frames are another matter: a plain `str` or a `SecretValue` shows the value there, so pass a `SecretStr`. + +`set_organization_secret` and `put_organization_secret` keep their behavior. They take the same arguments, send the same request, leave the name, size and encoding checks to the server, return any 200 result and raise the same `ProoflineError` types as before. They gain only the redaction and the detached errors described above. The local checks and the name confirmation belong to `store_organization_secret` alone. + ## MCP organization selection With an MCP OAuth credential approved for several organizations, discover its currently authorized targets with `client.mcp.list_organizations()`. It returns a `KnowledgeResult`; inspect `isError` before reading `structuredContent["data"]["organizations"]`. Each entry contains `organization_id`, `github_login`, and `scopes`. diff --git a/proofline/_generated/api/operations.py b/proofline/_generated/api/operations.py index 141d102e..1ce1e991 100644 --- a/proofline/_generated/api/operations.py +++ b/proofline/_generated/api/operations.py @@ -28,9 +28,7 @@ from ..models.repository_configuration_overrides import RepositoryConfigurationOverrides from ..models.scan_request_body import ScanRequestBody from ..models.scan_response import ScanResponse -from ..models.secret_value import SecretValue from ..models.source_provider import SourceProvider -from ..models.stored_secret import StoredSecret from ..types import UNSET, Unset from .default import get_commit_deploy_verifications as operation_get_commit_deploy_verifications from .default import get_config as operation_get_config @@ -49,7 +47,6 @@ from .default import plan_enterprise_configuration as operation_plan_enterprise_configuration from .default import plan_organization_configuration as operation_plan_organization_configuration from .default import plan_repository_configuration as operation_plan_repository_configuration -from .default import put_organization_secret as operation_put_organization_secret from .default import read_enterprise_approval as operation_read_enterprise_approval from .default import read_enterprise_config as operation_read_enterprise_config from .default import read_enterprise_rule as operation_read_enterprise_rule @@ -57,7 +54,6 @@ from .default import read_organization_status as operation_read_organization_status from .default import request_scan as operation_request_scan from .default import resolve_source_repository as operation_resolve_source_repository -from .default import set_organization_secret as operation_set_organization_secret class Operations: @@ -355,24 +351,6 @@ def plan_repository_configuration( raise _transport.invalid_response() return cast(ConfigurationPlan, response.parsed) - def put_organization_secret( - self, - org_id: UUID, - name: str, - *, - body: SecretValue, - ) -> StoredSecret: - with _transport.operation_errors(): - response = operation_put_organization_secret.sync_detailed( - client=self._api, - org_id=org_id, - name=name, - body=body, - ) - if not (response.status_code == 200): - raise _transport.invalid_response() - return cast(StoredSecret, response.parsed) - def read_enterprise_approval( self, enterprise: UUID, @@ -495,24 +473,6 @@ def resolve_source_repository( raise _transport.invalid_response() return cast(RepositoryAddress, response.parsed) - def set_organization_secret( - self, - org_id: UUID, - name: str, - *, - body: SecretValue, - ) -> StoredSecret: - with _transport.operation_errors(): - response = operation_set_organization_secret.sync_detailed( - client=self._api, - org_id=org_id, - name=name, - body=body, - ) - if not (response.status_code == 200): - raise _transport.invalid_response() - return cast(StoredSecret, response.parsed) - class AsyncOperations: _api: AuthenticatedClient @@ -809,24 +769,6 @@ async def plan_repository_configuration( raise _transport.invalid_response() return cast(ConfigurationPlan, response.parsed) - async def put_organization_secret( - self, - org_id: UUID, - name: str, - *, - body: SecretValue, - ) -> StoredSecret: - with _transport.operation_errors(): - response = await operation_put_organization_secret.asyncio_detailed( - client=self._api, - org_id=org_id, - name=name, - body=body, - ) - if not (response.status_code == 200): - raise _transport.invalid_response() - return cast(StoredSecret, response.parsed) - async def read_enterprise_approval( self, enterprise: UUID, @@ -948,21 +890,3 @@ async def resolve_source_repository( if not (response.status_code == 200): raise _transport.invalid_response() return cast(RepositoryAddress, response.parsed) - - async def set_organization_secret( - self, - org_id: UUID, - name: str, - *, - body: SecretValue, - ) -> StoredSecret: - with _transport.operation_errors(): - response = await operation_set_organization_secret.asyncio_detailed( - client=self._api, - org_id=org_id, - name=name, - body=body, - ) - if not (response.status_code == 200): - raise _transport.invalid_response() - return cast(StoredSecret, response.parsed) diff --git a/proofline/_transport.py b/proofline/_transport.py index 747f0e31..95657196 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -3,6 +3,7 @@ from __future__ import annotations import ipaddress +import json import math import os import re @@ -119,6 +120,9 @@ class ApprovalRequiredProblem(BaseModel): DEADLINE: ContextVar[float | None] = ContextVar("proofline_request_deadline", default=None) RETRY_READS: ContextVar[bool] = ContextVar("proofline_retry_reads", default=True) +# Values a call sends that server problem text must never carry back. A context +# variable scopes them to one call, also among concurrent tasks on one client. +REDACTIONS: ContextVar[tuple[str, ...]] = ContextVar("proofline_redactions", default=()) T = TypeVar("T") @@ -315,16 +319,56 @@ def retry_delay(value: str | None, attempt: int) -> float | None: return delay if math.isfinite(delay) and delay <= 60 else None -def redacted(value: object, raw: str) -> object: +def redacted(value: object, *raw: str) -> object: + forms = sorted({form for form in raw if form}, key=len, reverse=True) + if not forms: + return value + # One pass with the longest form first, so no form matches inside another + # form's replacement or leaves the tail of a longer form behind. + return _redacted(value, re.compile("|".join(map(re.escape, forms)))) + + +def _redacted(value: object, pattern: re.Pattern[str]) -> object: if isinstance(value, str): - return value.replace(raw, "[redacted]") + return pattern.sub("[redacted]", value) if isinstance(value, list): - return [redacted(item, raw) for item in value] + return [_redacted(item, pattern) for item in value] if isinstance(value, dict): - return {key: redacted(item, raw) for key, item in value.items()} + return {key: _redacted(item, pattern) for key, item in value.items()} return value +@contextmanager +def redacting(secret: SecretStr | None) -> Iterator[None]: + """Redact a sent value from problems in this context: as sent, JSON-escaped and as repr. + + None redacts nothing more, for a value the SDK could not read as text. + """ + if secret is None: + yield + return + value = secret.get_secret_value() + forms = ( + value, + json.dumps(value)[1:-1], + json.dumps(value, ensure_ascii=False)[1:-1], + repr(value)[1:-1], + ) + marker = REDACTIONS.set((*REDACTIONS.get(), *forms)) + try: + yield + finally: + REDACTIONS.reset(marker) + + +def detached(error: ProoflineError) -> ProoflineError: + """Drop the chained exceptions and frames that can still hold a request body.""" + error.__cause__ = None + error.__context__ = None + error.__suppress_context__ = False + return error.with_traceback(None) + + def environment(value: object) -> bool: return isinstance(value, dict) and all( isinstance(value.get(key), str) for key in ("id", "external_key", "display_name", "status") @@ -370,7 +414,7 @@ def problem(response: httpx2.Response, token: SecretStr) -> ProoflineError: "about:blank", "Proofline returned an HTTP error without a problem document.", ) - body = cast(dict[str, Any], redacted(body, token.get_secret_value())) + body = cast(dict[str, Any], redacted(body, token.get_secret_value(), *REDACTIONS.get())) kind = body["type"] if isinstance(body.get("type"), str) else "about:blank" title = body["title"] if isinstance(body.get("title"), str) else None if isinstance(body.get("detail"), str): diff --git a/proofline/client.py b/proofline/client.py index 72f2514e..a5640e6d 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,8 +2,11 @@ from __future__ import annotations +import json import math +import re from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from dataclasses import dataclass, field from string import hexdigits from time import sleep from types import TracebackType @@ -30,11 +33,13 @@ list_pull_request_reviews, list_repositories, list_reviews, + put_organization_secret, request_commit_review, request_file_review, request_patch_review, request_review, rerun_review, + set_organization_secret, start_agent_session, stop_review, upload_coverage_reports, @@ -67,8 +72,10 @@ from ._generated.models.review_summary import ReviewSummary from ._generated.models.run_now_request import RunNowRequest from ._generated.models.run_now_response import RunNowResponse +from ._generated.models.secret_value import SecretValue from ._generated.models.start_session import StartSession from ._generated.models.stop_response import StopResponse +from ._generated.models.stored_secret import StoredSecret from ._generated.types import UNSET, Response, Unset from ._mcp import AsyncMcpClient, McpClient from ._transport import ProoflineError @@ -190,6 +197,83 @@ def _pagination_limit(resource: str = "Review") -> ProoflineError: ) +_SECRET_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_-]{0,63}", re.ASCII) +_SECRET_ROUTE = "/v2/orgs/{}/secrets/{}" +_LEGACY_SECRET_ROUTE = "/api/v2/organizations/{}/secrets/{}" + + +@dataclass(frozen=True) +class _SecretWrite: + """One checked secret write; repr shows only its path.""" + + path: str + content: bytes = field(repr=False) + value: SecretStr = field(repr=False) + + +def _secret_write( + route: str, organization_id: UUID, name: str, value: str | SecretStr +) -> _SecretWrite: + # No local here holds the plain value, so a traceback that captures + # locals shows at most the object the caller passed. + if not isinstance(organization_id, UUID): + raise ValueError("The organization ID must be a UUID.") + if not isinstance(name, str) or not _SECRET_NAME.fullmatch(name): + raise ValueError( + "A secret name is an ASCII letter, then up to 63 ASCII letters, digits, _ or -." + ) + if not isinstance(value, SecretStr): + if not isinstance(value, str): + raise ValueError("The secret value must be a str or SecretStr.") + value = SecretStr(value) + size = -1 + try: + size = len(value.get_secret_value().encode("utf-8")) + except UnicodeEncodeError: + # The encoding error holds the value, so it must not become the + # context of the error raised below. + pass + if size < 0: + raise ValueError("The secret value must be text that UTF-8 can encode.") + if not 1 <= size <= 32_768: + raise ValueError("The secret value must be 1 to 32,768 bytes in UTF-8.") + return _SecretWrite( + route.format(quote(str(organization_id), safe=""), name), + json.dumps({"value": value.get_secret_value()}).encode("ascii"), + value, + ) + + +def _stored_secret(response: httpx2.Response, name: str) -> StoredSecret: + # Only the name the write was sent under confirms that write. + try: + body = response.json() + except (ValueError, UnicodeError): + raise _transport.invalid_response() from None + if response.status_code != 200 or not isinstance(body, dict) or body.get("name") != name: + raise _transport.invalid_response() + return StoredSecret.from_dict(body) + + +def _sent_value(body: object) -> SecretStr | None: + # The legacy methods duck-type body through to_dict() and leave every check + # to the server, so a value that cannot be read as text is not redacted + # rather than refused here. + try: + to_dict = getattr(body, "to_dict") + value = to_dict().get("value") + except Exception: + return None + return SecretStr(value) if isinstance(value, str) else None + + +def _legacy_stored(response: Response[Any]) -> StoredSecret: + # The generated check: any 200 is the result. + if not (response.status_code == 200): + raise _transport.invalid_response() + return cast(StoredSecret, response.parsed) + + def _export_page_limit(max_pages: int) -> None: if isinstance(max_pages, bool) or not isinstance(max_pages, int) or not 1 <= max_pages <= 1_000: raise ValueError("Export pagination requires max_pages 1..1000.") @@ -540,6 +624,74 @@ def iter_reviews( params["cursor"] = cursor raise _pagination_limit() + def store_organization_secret( + self, organization_id: UUID, name: str, value: str | SecretStr + ) -> StoredSecret: + """Store a write-only organization secret without letting its value escape. + + The value is checked before any request and sent once, without retries. + Problem text that echoes it, as sent or JSON-escaped, carries + "[redacted]" instead, and a raised ProoflineError holds no chained + exception and no HTTP-layer frame that could keep the request body. + Pass a SecretStr to keep the value masked in your own frames as well. + """ + return self._store_secret(_SECRET_ROUTE, organization_id, name, value) + + def set_organization_secret( + self, org_id: UUID, name: str, *, body: SecretValue + ) -> StoredSecret: + """Store a secret as the generated method did; problems redact the value.""" + return self._legacy_secret(set_organization_secret.sync_detailed, org_id, name, body) + + def put_organization_secret( + self, org_id: UUID, name: str, *, body: SecretValue + ) -> StoredSecret: + """Store a secret as the generated method did; problems redact the value.""" + return self._legacy_secret(put_organization_secret.sync_detailed, org_id, name, body) + + def _legacy_secret( + self, + operation: Callable[..., Response[Any]], + org_id: UUID, + name: str, + body: SecretValue, + ) -> StoredSecret: + # The request, checks and results stay those of the generated method; + # only problem text and the raised error change. + failure: ProoflineError | None = None + with _transport.redacting(_sent_value(body)): + try: + with _transport.operation_errors(): + return _legacy_stored( + operation(client=self._api, org_id=org_id, name=name, body=body) + ) + except ProoflineError as error: + failure = error + raise _transport.detached(failure) + + def _store_secret( + self, route: str, organization_id: UUID, name: str, value: str | SecretStr + ) -> StoredSecret: + write = _secret_write(route, organization_id, name, value) + failure: ProoflineError | None = None + with _transport.redacting(write.value): + try: + return _stored_secret( + self._http.put( + write.path, + content=write.content, + headers={"Content-Type": "application/json"}, + ), + name, + ) + except ProoflineError as error: + failure = error + except httpx2.HTTPError as error: + failure = _transport.network_error(error) + except Exception: + failure = _transport.invalid_response() + raise _transport.detached(failure) + def wait_for_review( self, organization_id: UUID, @@ -937,6 +1089,78 @@ async def iter_reviews( params["cursor"] = cursor raise _pagination_limit() + async def store_organization_secret( + self, organization_id: UUID, name: str, value: str | SecretStr + ) -> StoredSecret: + """Store a write-only organization secret without letting its value escape. + + The value is checked before any request and sent once, without retries. + Problem text that echoes it, as sent or JSON-escaped, carries + "[redacted]" instead, and a raised ProoflineError holds no chained + exception and no HTTP-layer frame that could keep the request body. + Pass a SecretStr to keep the value masked in your own frames as well. + """ + return await self._store_secret(_SECRET_ROUTE, organization_id, name, value) + + async def set_organization_secret( + self, org_id: UUID, name: str, *, body: SecretValue + ) -> StoredSecret: + """Store a secret as the generated method did; problems redact the value.""" + return await self._legacy_secret( + set_organization_secret.asyncio_detailed, org_id, name, body + ) + + async def put_organization_secret( + self, org_id: UUID, name: str, *, body: SecretValue + ) -> StoredSecret: + """Store a secret as the generated method did; problems redact the value.""" + return await self._legacy_secret( + put_organization_secret.asyncio_detailed, org_id, name, body + ) + + async def _legacy_secret( + self, + operation: Callable[..., Awaitable[Response[Any]]], + org_id: UUID, + name: str, + body: SecretValue, + ) -> StoredSecret: + # The request, checks and results stay those of the generated method; + # only problem text and the raised error change. + failure: ProoflineError | None = None + with _transport.redacting(_sent_value(body)): + try: + with _transport.operation_errors(): + return _legacy_stored( + await operation(client=self._api, org_id=org_id, name=name, body=body) + ) + except ProoflineError as error: + failure = error + raise _transport.detached(failure) + + async def _store_secret( + self, route: str, organization_id: UUID, name: str, value: str | SecretStr + ) -> StoredSecret: + write = _secret_write(route, organization_id, name, value) + failure: ProoflineError | None = None + with _transport.redacting(write.value): + try: + return _stored_secret( + await self._http.put( + write.path, + content=write.content, + headers={"Content-Type": "application/json"}, + ), + name, + ) + except ProoflineError as error: + failure = error + except httpx2.HTTPError as error: + failure = _transport.network_error(error) + except Exception: + failure = _transport.invalid_response() + raise _transport.detached(failure) + async def wait_for_review( self, organization_id: UUID, diff --git a/scripts/contracts.py b/scripts/contracts.py index a8cdda1f..cdc71fce 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -48,7 +48,14 @@ def main() -> None: "get_repo_config_with_revision", } for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} + helpers = { + "close", + "aclose", + "iter_export_pages", + "iter_reviews", + "store_organization_secret", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/tests/test_secrets.py b/tests/test_secrets.py new file mode 100644 index 00000000..0b823c7b --- /dev/null +++ b/tests/test_secrets.py @@ -0,0 +1,506 @@ +"""Organization secret writes keep the value out of errors, reprs and tracebacks.""" + +from __future__ import annotations + +import inspect +import json +import logging +import os +import socket +import threading +import traceback +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any + +import anyio +import pytest +from pydantic import SecretStr + +from proofline import ( + AsyncProoflineClient, + ProoflineClient, + ProoflineError, + SecretValue, + StoredSecret, + _transport, +) + +from .fixtures import ORG, PRIVATE, TOKEN +from .http_server import Reply, Request, Server + +Client = ProoflineClient | AsyncProoflineClient +PACKAGE = str(Path(_transport.__file__).resolve().parent) + os.sep +MODES = pytest.mark.parametrize("mode", ["sync", "async"]) +NAME = "DEPLOY_KEY-2" +# Quotes, a backslash, a newline and a non-ASCII letter all change under JSON escaping. +VALUE = 'synthetic-secret-"canary"\\é\n' +METHODS = { + "store_organization_secret": f"/v2/orgs/{ORG}/secrets/{NAME}", + "set_organization_secret": f"/v2/orgs/{ORG}/secrets/{NAME}", + "put_organization_secret": f"/api/v2/organizations/{ORG}/secrets/{NAME}", +} + + +@asynccontextmanager +async def session(mode: str, url: str, **kwargs: Any) -> AsyncIterator[Client]: + if mode == "sync": + with ProoflineClient(SecretStr(TOKEN), base_url=url, **kwargs) as client: + yield client + else: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url, **kwargs) as async_client: + yield async_client + + +async def call(client: Client, name: str, *args: Any, **kwargs: Any) -> Any: + result = getattr(client, name)(*args, **kwargs) + return await result if inspect.isawaitable(result) else result + + +async def write(client: Client, method: str, value: str | SecretStr, name: str = NAME) -> Any: + if method == "store_organization_secret": + return await call(client, method, ORG, name, value) + raw = value.get_secret_value() if isinstance(value, SecretStr) else value + return await call(client, method, ORG, name, body=SecretValue(raw)) + + +def forms(value: str) -> set[str]: + return { + value, + json.dumps(value)[1:-1], + json.dumps(value, ensure_ascii=False)[1:-1], + repr(value)[1:-1], + } + + +def assert_detached(error: ProoflineError, value: str = VALUE) -> None: + # Neither a chained exception nor an HTTP-layer frame may keep the request body. + assert error.__cause__ is None and error.__context__ is None + frames = [frame for frame, _ in traceback.walk_tb(error.__traceback__)] + files = {frame.f_code.co_filename for frame in frames} + assert not [name for name in files if "httpx" in name or "httpcore" in name] + assert not [name for name in files if name.endswith(("_transport.py", "_sync_http.py"))] + diagnostic = repr(error) + str(error) + "".join(traceback.format_exception(error)) + diagnostic += repr(vars(error)) + # What a locals-capturing reporter reads from SDK frames. A SecretValue is + # the caller's own object (its repr shows the value), never one the SDK makes. + for frame in frames: + if frame.f_code.co_filename.startswith(PACKAGE): + diagnostic += "".join( + repr(local) + for local in frame.f_locals.values() + if not isinstance(local, SecretValue) + ) + for form in forms(value): + assert form not in diagnostic + assert TOKEN not in diagnostic + assert _transport.REDACTIONS.get() == () + + +@MODES +@pytest.mark.parametrize("method", list(METHODS)) +@pytest.mark.parametrize("masked", [False, True]) +async def test_secret_write_sends_one_put_and_returns_the_stored_name( + mode: str, method: str, masked: bool +) -> None: + def respond(request: Request, index: int) -> Reply: + assert request.method == "PUT" + assert request.path == METHODS[method] + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + assert request.headers["Content-Type"] == "application/json" + assert json.loads(request.body) == {"value": VALUE} + return Reply(body={"name": NAME}) + + value: str | SecretStr = SecretStr(VALUE) if masked else VALUE + with Server(respond) as server: + async with session(mode, server.url) as client: + stored = await write(client, method, value) + assert isinstance(stored, StoredSecret) + assert stored.name == NAME + assert TOKEN not in repr(client) + assert len(server.requests) == 1 + assert _transport.REDACTIONS.get() == () + + +@MODES +async def test_secret_write_accepts_the_documented_bounds(mode: str) -> None: + longest_name = "K" * 64 + largest = "é" * 16_384 # 32,768 bytes in UTF-8 + with Server(lambda request, index: Reply(body={"name": longest_name})) as server: + async with session(mode, server.url) as client: + stored = await write(client, "store_organization_secret", largest, longest_name) + assert stored.name == longest_name + assert json.loads(server.requests[0].body) == {"value": largest} + assert server.requests[0].path.endswith(f"/secrets/{longest_name}") + + +@MODES +@pytest.mark.parametrize( + ("status", "extensions"), + [ + (400, {}), + (409, {"type": "urn:proofline:api:v2:key_locked"}), + (422, {"type": "urn:proofline:api:v2:invalid_configuration"}), + (429, {"retry": "0"}), + (503, {"retry": "0"}), + ], +) +async def test_problem_text_never_returns_the_value_in_any_encoding( + mode: str, status: int, extensions: dict[str, str] +) -> None: + ascii_escaped = json.dumps(VALUE)[1:-1] + unicode_escaped = json.dumps(VALUE, ensure_ascii=False)[1:-1] + python_repr = repr(VALUE)[1:-1] + kind = extensions.get("type", "urn:proofline:api:v2:invalid_secret") + + def respond(request: Request, index: int) -> Reply: + # The peer echoes what it received, so the value exists only on the wire. + sent = json.loads(request.body)["value"] + body: dict[str, Any] = { + "type": kind, + "title": json.dumps(sent)[1:-1], + "detail": f"{PRIVATE} {sent} {TOKEN} {repr(sent)[1:-1]}", + } + if kind.endswith("key_locked"): + body.update(key=sent, owner={"layer": "organization", "resource_id": sent}) + if kind.endswith("invalid_configuration"): + reason = json.dumps(sent, ensure_ascii=False)[1:-1] + body["errors"] = [{"key": "secrets.deploy", "reason": f"rejected {reason}"}] + headers = {"Retry-After": extensions["retry"]} if "retry" in extensions else {} + return Reply(status, body, headers) + + assert len({VALUE, ascii_escaped, unicode_escaped, python_repr}) == 4 + with Server(respond) as server: + async with session(mode, server.url) as client: + for method in METHODS: + with pytest.raises(ProoflineError) as raised: + await write(client, method, SecretStr(VALUE)) + error = raised.value + assert (error.status, error.type) == (status, kind) + assert error.title == "[redacted]" + assert error.detail == f"{PRIVATE} [redacted] [redacted] [redacted]" + problem = error.configuration_problem + if kind.endswith("key_locked"): + assert problem is not None + assert problem.model_dump() == { + "type": kind, + "key": "[redacted]", + "owner": {"layer": "organization", "resource_id": "[redacted]"}, + } + elif kind.endswith("invalid_configuration"): + assert problem is not None + assert problem.model_dump()["errors"] == [ + {"key": "secrets.deploy", "reason": "rejected [redacted]"} + ] + else: + assert problem is None + assert_detached(error) + # A write is sent once: a rate limit or outage with Retry-After is not retried. + assert len(server.requests) == len(METHODS) + + +@MODES +async def test_redaction_is_scoped_to_the_write(mode: str) -> None: + # A later call on the same client is not redacted for an earlier write's value. + replies = [ + Reply(400, {"type": "urn:proofline:api:v2:invalid_secret", "detail": PRIVATE}), + Reply(404, {"type": "urn:proofline:api:v2:not_found", "detail": PRIVATE}), + ] + with Server(lambda request, index: replies[index]) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as written: + await write(client, "store_organization_secret", PRIVATE) + assert written.value.detail == "[redacted]" + with pytest.raises(ProoflineError) as read: + await call(client, "get_config", ORG) + assert read.value.detail == PRIVATE + + +def echoing_barrier() -> Any: + # Both writes must be in flight at once before either problem is answered. + barrier = threading.Barrier(2, timeout=10) + + def respond(request: Request, index: int) -> Reply: + barrier.wait() + sent = json.loads(request.body)["value"] + return Reply(400, {"type": "urn:proofline:api:v2:invalid_secret", "detail": sent}) + + return respond + + +VALUES = ("synthetic-first-secret-canary", "synthetic-second-secret-canary") + + +@pytest.mark.parametrize("backend", ["asyncio", "trio"]) +def test_concurrent_async_writes_each_redact_their_own_value(backend: str) -> None: + respond = echoing_barrier() + # Errors are keyed by index: the calling frames hold only masked values. + errors: dict[int, ProoflineError] = {} + + async def run(url: str) -> None: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url) as client: + + async def one(index: int, secret: SecretStr) -> None: + try: + await client.store_organization_secret(ORG, NAME, secret) + except ProoflineError as error: + errors[index] = error + + async with anyio.create_task_group() as group: + for index, value in enumerate(VALUES): + group.start_soon(one, index, SecretStr(value)) + + with Server(respond) as server: + anyio.run(run, server.url, backend=backend) + assert len(server.requests) == 2 + assert set(errors) == {0, 1} + for index, error in errors.items(): + assert error.detail == "[redacted]" + assert_detached(error, VALUES[index]) + assert_detached(error, VALUES[1 - index]) + + +def test_concurrent_sync_writes_on_one_client_each_redact_their_own_value() -> None: + respond = echoing_barrier() + errors: dict[int, ProoflineError] = {} + with Server(respond) as server: + with ProoflineClient(SecretStr(TOKEN), base_url=server.url) as client: + + def one(index: int, secret: SecretStr) -> None: + try: + client.store_organization_secret(ORG, NAME, secret) + except ProoflineError as error: + errors[index] = error + + threads = [ + threading.Thread(target=one, args=(index, SecretStr(value))) + for index, value in enumerate(VALUES) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=15) + assert len(server.requests) == 2 + assert set(errors) == {0, 1} + for index, error in errors.items(): + assert error.detail == "[redacted]" + assert_detached(error, VALUES[index]) + assert_detached(error, VALUES[1 - index]) + + +@MODES +@pytest.mark.parametrize( + ("organization_id", "name", "value"), + [ + (str(ORG), NAME, VALUE), + (ORG, "", VALUE), + (ORG, "1KEY", VALUE), + (ORG, "_KEY", VALUE), + (ORG, "K" * 65, VALUE), + (ORG, "KEY NAME", VALUE), + (ORG, "KEY/NAME", VALUE), + (ORG, "KEY.NAME", VALUE), + (ORG, "..", VALUE), + (ORG, "KEY\n", VALUE), + (ORG, "KÉY", VALUE), + (ORG, None, VALUE), + (ORG, NAME, ""), + (ORG, NAME, SecretStr("")), + (ORG, NAME, "é" * 16_384 + "x"), + (ORG, NAME, VALUE + "\ud800"), + (ORG, NAME, 42), + ], +) +async def test_invalid_writes_are_refused_before_any_request( + mode: str, organization_id: Any, name: Any, value: Any +) -> None: + with Server(lambda request, index: Reply(body={"name": NAME})) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError) as raised: + await call(client, "store_organization_secret", organization_id, name, value) + error = raised.value + # An encoding error holds the value, so it is never chained. + assert error.__cause__ is None and error.__context__ is None + assert VALUE not in str(error) + repr(error) + assert not server.requests + assert _transport.REDACTIONS.get() == () + + +LEGACY = ("set_organization_secret", "put_organization_secret") + + +@MODES +@pytest.mark.parametrize("method", LEGACY) +@pytest.mark.parametrize( + ("name", "value"), + [ + ("1KEY", VALUE), + ("K" * 65, VALUE), + ("KEY NAME", VALUE), + ("KEY.NAME", VALUE), + (NAME, ""), + (NAME, "\u00e9" * 16_384 + "x"), + ], +) +async def test_legacy_methods_leave_the_checks_to_the_server( + mode: str, method: str, name: str, value: str +) -> None: + # As at HEAD: no local ValueError; the server judges and answers a problem. + def respond(request: Request, index: int) -> Reply: + sent = json.loads(request.body)["value"] + return Reply(422, {"type": "urn:proofline:api:v2:invalid_secret", "detail": f"x{sent}"}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, method, ORG, name, body=SecretValue(value)) + error = raised.value + assert error.status == 422 + assert error.detail == ("x" if not value else "x[redacted]") + assert error.__cause__ is None and error.__context__ is None + assert len(server.requests) == 1 + assert json.loads(server.requests[0].body) == {"value": value} + assert _transport.REDACTIONS.get() == () + + +class DuckBody: + def __init__(self, value: object) -> None: + self.value = value + + def to_dict(self) -> dict[str, Any]: + return {"value": self.value} + + +@MODES +@pytest.mark.parametrize("method", LEGACY) +async def test_legacy_methods_keep_head_inputs_and_results(mode: str, method: str) -> None: + replies = [ + Reply(body={"name": "OTHER_KEY"}), + Reply(400, {"type": "urn:proofline:api:v2:invalid_secret", "detail": f"x{VALUE}"}), + Reply(400, {"type": "urn:proofline:api:v2:invalid_secret", "detail": "x42"}), + ] + with Server(lambda request, index: replies[index]) as server: + async with session(mode, server.url) as client: + # A str organization ID still works, and any 200 is the result. + stored = await call(client, method, str(ORG), NAME, body=SecretValue(VALUE)) + assert isinstance(stored, StoredSecret) + assert stored.name == "OTHER_KEY" + # A duck-typed body is sent through to_dict() and its str value redacted. + with pytest.raises(ProoflineError) as duck: + await call(client, method, ORG, NAME, body=DuckBody(VALUE)) + assert duck.value.detail == "x[redacted]" + assert_detached(duck.value) + # A value that is not text is sent as before and simply not redacted. + with pytest.raises(ProoflineError) as number: + await call(client, method, ORG, NAME, body=DuckBody(42)) + assert number.value.detail == "x42" + # Bodies the generated method could not send fail as they did at HEAD. + for body in (object(), SecretValue(VALUE + "\ud800")): + with pytest.raises(ProoflineError) as unsent: + await call(client, method, ORG, NAME, body=body) + assert unsent.value.type == "urn:proofline:sdk:invalid-response" + assert_detached(unsent.value) + assert len(server.requests) == len(replies) + assert server.requests[0].path.endswith(f"{ORG}/secrets/{NAME}") + assert json.loads(server.requests[2].body) == {"value": 42} + assert _transport.REDACTIONS.get() == () + + +@MODES +@pytest.mark.parametrize("method", LEGACY) +async def test_legacy_secret_methods_keep_their_call_shape(mode: str, method: str) -> None: + with Server(lambda request, index: Reply(body={"name": NAME})) as server: + async with session(mode, server.url) as client: + bound = getattr(client, method) + stored = bound(org_id=ORG, name=NAME, body=SecretValue("v")) + stored = await stored if inspect.isawaitable(stored) else stored + assert stored.name == NAME + with pytest.raises(TypeError): + bound(ORG, NAME, SecretValue("v")) + assert len(server.requests) == 1 + for cls in (ProoflineClient, AsyncProoflineClient): + signature = inspect.signature(getattr(cls, method)) + assert [(p.name, p.kind.name) for p in signature.parameters.values()] == [ + ("self", "POSITIONAL_OR_KEYWORD"), + ("org_id", "POSITIONAL_OR_KEYWORD"), + ("name", "POSITIONAL_OR_KEYWORD"), + ("body", "KEYWORD_ONLY"), + ] + assert signature.return_annotation in (StoredSecret, "StoredSecret") + + +@MODES +@pytest.mark.parametrize("body", [f"{VALUE}".encode(), [VALUE]]) +async def test_a_problem_body_that_is_not_a_document_is_never_echoed( + mode: str, body: Any, caplog: pytest.LogCaptureFixture +) -> None: + caplog.set_level(logging.DEBUG) + with Server(lambda request, index: Reply(500, body)) as server: + async with session(mode, server.url) as client: + for method in METHODS: + with pytest.raises(ProoflineError) as raised: + await write(client, method, SecretStr(VALUE)) + assert raised.value.status == 500 + assert all(form not in raised.value.detail for form in forms(VALUE)) + assert_detached(raised.value) + assert all(form not in caplog.text for form in forms(VALUE)) + + +@MODES +@pytest.mark.parametrize( + "reply", + [ + Reply(body={"name": "OTHER_KEY"}), + Reply(body={"value": VALUE}), + Reply(body=f"not json {VALUE}".encode()), + Reply(body=[VALUE]), + Reply(201, {"name": NAME}), + ], +) +async def test_unconfirmed_writes_raise_a_static_invalid_response(mode: str, reply: Reply) -> None: + with Server(lambda request, index: reply) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await write(client, "store_organization_secret", SecretStr(VALUE)) + error = raised.value + assert error.type == "urn:proofline:sdk:invalid-response" + assert error.detail == "Proofline returned an invalid API response." + assert_detached(error) + assert len(server.requests) == 1 + + +@MODES +async def test_a_write_that_times_out_is_not_repeated(mode: str) -> None: + with Server(lambda request, index: Reply(body={"name": NAME}, header_pause=1.0)) as server: + async with session(mode, server.url, timeout=0.2) as client: + with pytest.raises(ProoflineError) as raised: + await write(client, "store_organization_secret", SecretStr(VALUE)) + error = raised.value + assert error.type == "urn:proofline:sdk:timeout" + assert_detached(error) + assert len(server.requests) == 1 + + +@MODES +async def test_an_unreachable_server_keeps_no_request_in_the_error(mode: str) -> None: + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + url = f"http://127.0.0.1:{probe.getsockname()[1]}" + async with session(mode, url, timeout=5) as client: + with pytest.raises(ProoflineError) as raised: + await write(client, "store_organization_secret", SecretStr(VALUE)) + error = raised.value + assert error.type in ( + "urn:proofline:sdk:transport-unavailable", + "urn:proofline:sdk:timeout", + ) + assert_detached(error) + + +def test_store_organization_secret_keeps_sync_and_async_signatures() -> None: + for method in METHODS: + sync = inspect.signature(getattr(ProoflineClient, method)) + asynchronous = inspect.signature(getattr(AsyncProoflineClient, method)) + assert sync == asynchronous + assert inspect.iscoroutinefunction(getattr(AsyncProoflineClient, method))