Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
76 changes: 0 additions & 76 deletions proofline/_generated/api/operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -49,15 +47,13 @@
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
from .default import read_organization_rule as operation_read_organization_rule
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:
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
54 changes: 49 additions & 5 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import ipaddress
import json
import math
import os
import re
Expand Down Expand Up @@ -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")


Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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):
Expand Down
Loading