My Trust Center API contract#

The synchronous and asynchronous clients implement all five documented read operations and explicit store-backed PAT refresh.

Sources and verification boundary#

The local specification supplies the detailed field inventory below. The current rendered reference was checked for all six operations, request constraints, pagination, error behavior, and the top-level tenant-list and event-detail response schemas; these agree with the local copy. The reference’s linked YAML download returned HTTP 404, so a byte-for-byte comparison and independent verification of every nested schema were unavailable. No live API calls were made. The vendor file remains local and is excluded from the package.

On 2026-11-02, the rendered reference did not expose its operation content. The current Salesforce getting-started guide confirmed Bearer authentication, PAT-scoped results, sorting by ID and cloud, continuation via nextPageToken and pageToken, and locale fallback. The local specification supplied the exact method and path, parameter defaults and limits, cursor error status, and detailed response schema for the implementation.

On 2026-11-03, the rendered reference again exposed no operation content. The official overview and getting-started guide confirmed the snapshot grouping, repeated patch IDs, PAT-scoped results, locale fallback, and the availability of event search, timelines, and tenant history. The authentication guide confirmed Bearer authentication and 401 behavior. The local YAML supplies the exact methods, paths, input limits, wire schemas, history window, and endpoint-specific errors. No conflict was found in the overlapping guide content. The current nested schemas and request details could not be independently compared with the rendered reference.

Shared contract#

Base URL: https://api.salesforce.com/platform/mytrust/v1. Every operation requires Authorization: Bearer <PAT>; this is not org OAuth. Successful responses are JSON. All data is limited to the PAT’s authorized tenants. Empty results never establish Salesforce-wide health.

All five read operations declare an optional locale query string: BCP 47, default en-US; unsupported or malformed values fall back to en-US. The shared parameter description says it applies to every endpoint, but refresh does not declare it. Do not add a refresh locale argument without clarification. Tenant IDs are opaque strings, not necessarily Core org IDs.

Operations#

All paths below are relative to the base URL. Every success is HTTP 200.

Method and path

Operation ID

Inputs

Success schema

Documented errors

GET /tenants

getTenants

Optional query locale, pageSize, pageToken

TenantListResponse

400, 401, 429, 500

GET /tenants/{tenantId}

getTenant

Required string path tenantId; optional query locale

TenantDetail

401, 404, 429, 500

GET /status

getFleetStatus

Optional query locale

StatusSnapshot

401, 429, 500

POST /events/search

searchEvents

Optional query locale; required JSON EventSearchRequest

EventSearchResponse

400, 401, 429, 500

GET /events/{eventId}

getEvent

Required string path eventId; optional query locale

EventDetail

401, 404, 429, 500

POST /pats/refresh

refreshPat

Optional JSON PatRefreshRequest

PatCredential

401, 429, 500

Search is a read operation despite its HTTP method. There is no separate timeline or tenant-history endpoint: event detail supplies timelines, and tenant detail embeds history. Refresh is available through the store-backed client and uses the dedicated transport path described below.

Pagination and search inputs#

  • Tenant listing: query pageSize is an integer from 1 to 200, default 100. Query pageToken is an opaque string of at most 4096 characters. Results are ordered by tenant ID and cloud. Send nextPageToken back as pageToken, preserving all other parameters. An absent token marks the final page. Invalid, stale, or mismatched tokens return 400.

  • EventSearchScope: required type (only tenant) and id (nonempty string).

  • EventSearchRequest: required scopes (1–50 scope objects; duplicate tenants removed), startTime (inclusive), and endTime (exclusive and later than start). Timestamps must be full ISO 8601 with Z or ±HH:MM; date-only, year-only, and space-separated values fail with 400.

  • Optional body eventTypes: nonempty array of unique EventType values. Omit it for all types. Optional body pageSize and pageToken have the same limits as tenant listing. Search returns a stable order; repeat the unchanged body with the new token, also preserving locale. Changed matching results can invalidate the cursor with 400. Surface the error so the caller can restart deliberately; silently restarting could duplicate prior results.

  • EventSearchResponse: required events (at most 200 EventSearchResult items) and optional nextPageToken, absent on the final page. Unauthorized tenant IDs are ignored; zero authorized matches can return {"events": []} with 200.

  • Snapshot, event detail, and tenant detail declare no pagination controls. Tenant detail covers lifecycle overlap within 365 days before/after request time; informational messages cover the preceding 365 days. Do not add arbitrary history-window arguments to that endpoint.

Schema inventory#

Names and field casing below are Salesforce wire names. Required and nullable are separate: a required nullable field must still be present. Unless identified as nullable, an optional field may be omitted but is not declared to accept JSON null. Date-time fields are ISO 8601 strings on the wire. Most response objects disallow additional properties in the vendor schema; Tenant leaves them unspecified. The SDK’s forward-compatible extra-field policy is described separately below.

Tenants and status (5 schemas)#

Schema

Required fields

Optional fields and structure

Tenant

id, cloud, name: strings

environment, myDomain: strings; My Domain only for applicable Core tenants

TenantListResponse

tenants: array of Tenant, max 200

nextPageToken: string

TenantDetail

Inherits Tenant; events: array of EventSummary

region, version, maintenanceWindow: nullable strings; location: object

EventTypeBuckets

patch, incident, maintenance, informationalMessage: arrays of EventSummary

Preserve each category, including empty arrays

StatusSnapshot

ongoing, upcoming: EventTypeBuckets

No flattening or automatic deduplication

TenantDetail.location, when present, requires string city, stateName, stateCode, countryName, and countryCode (empty strings when unavailable). Instance fields describe the primary instance and are omitted when instance information is unavailable.

Events, scopes, and enums (7 schemas)#

Schema

Contract

Event

Requires string eventId, eventType, status, string arrays products/services, and date-time createdAt. Optional nullable strings: title, description, duration, displayDuration; optional nullable date-times: startTime, endTime. Optional data, timeline, and scope depend on endpoint.

EventDetail

Event without a top-level scope. Optional timeline is an array of TimelineItem; can be absent when there are no entries.

EventSummary

Event with required scope: SubEventScope and no timeline. Used in snapshot and tenant history.

EventSearchResult

Inherits EventSummary. Lifecycle values reflect the matched tenant scope.

SubEventScope

Required tenants: map of tenant ID to object (documented as empty). Key presence identifies membership.

EventType

patch, incident, maintenance, informationalMessage

EventStatus

active, resolved, confirmed, canceled; canceled applies only to maintenance.

data is a oneOf the four event-data shapes below; the schema has no discriminator. duration is an ISO 8601 duration string, including elapsed time for ongoing events; displayDuration is localized presentation text. Do not parse localized text for calculations. An empty products array can mean a platform-wide informational message, and an empty services array can mean impact information is unavailable.

Preserve duplicates and scope: snapshot patches may repeat across tenant lifecycles and both buckets; tenant history patches may repeat per lifecycle. Search can return an event once per matched tenant, with different status/times/duration for each result. Neither event ID alone nor a set keyed by it is a safe lossless representation.

Type-specific event data (4 schemas)#

All listed fields are required; ? here means the value may be null.

Schema

Fields

PatchEventData

String releaseId, releaseName, releaseVersion; date-time plannedStartTime?, plannedEndTime?

IncidentEventData

String additionalInformation?, rcaLink?; date-time rcaCreatedAt?

MaintenanceEventData

Date-time plannedStartTime?, plannedEndTime?; string additionalInformation?

InformationalMessageEventData

String informationalMessageType?; documented categories informationalMessage / productSpecific, not a schema enum

Timeline (5 schemas)#

TimelineItem is an anyOf the following four shapes. Each requires string subEventId, string subEventType, scope: SubEventScope, and date-time createdAt. Each allows optional nullable string message and nullable date-time updatedAt.

Schema

subEventType values

Other optional fields

PatchTimelineItem

patch_release_scheduled, patch_release_started, patch_release_ended, patch_release_notes

Nullable date-times publicationDate, plannedStartTime, plannedEndTime; contents: array of objects with optional string relatedItem and description

IncidentTimelineItem

incident_started, incident_update, incident_resolved

None

MaintenanceTimelineItem

maintenance_scheduled, maintenance_update, maintenance_started, maintenance_completed, maintenance_canceled

Nullable date-times plannedStartTime, plannedEndTime

InformationalMessageTimelineItem

im_created, im_update_added

None

Do not assume every timeline entry has scheduling fields, a message, or an update time.

Search, PAT, and errors (6 schemas)#

The four search schemas (EventSearchScope, EventSearchRequest, EventSearchResult, EventSearchResponse) are detailed above; EventSearchResult is counted in the event group. The remaining schemas are:

  • PatRefreshRequest: optional body; optional integer expiresInDays, 1–30, default 30. Additional fields are forbidden.

  • PatCredential: required tokenId (UUID string), secret and label (strings), createdAt and expiresAt (date-times). secret is returned once and must never enter ordinary response logging, exception context, or serialization used by agent tools.

  • Error: required string error, enum badRequest, unauthorized, notFound, internalError; optional string message, omitted for unauthorized responses.

Across the groups, all 27 distinct schema names are covered (the search-result alias belongs to both discussions but is counted once).

Errors and PAT lifecycle#

400 means invalid arguments/cursor where declared. A detail 404 can mean nonexistent or unauthorized; do not distinguish these without evidence. All operations document JSON 401/500 errors. All six reference the gateway’s 429 response: plain text local_rate_limited, without Retry-After; authentication docs also exclude RateLimit-* headers for refresh. Do not assume that every failure body is JSON or has message.

The authentication guide documents one active PAT, UI lifetimes of 7/15/30 days, refresh lifetimes of 1–30 days, and a 365-day maximum lineage. Refresh immediately revokes the old PAT; it is non-idempotent. Invalid refresh lifetime is reported as the same 401 as an invalid PAT. A refresh 429 leaves the old PAT active; retry can use backoff and jitter. A refresh timeout/500 has an ambiguous result: first test the old token with a harmless read. If it succeeds, a later refresh may be retried; a 401 requires manual recovery in My Trust Center. Never apply generic automatic refresh retries or refresh automatically after 401. See Salesforce’s recovery instructions.

Foundation changes and implementation decisions#

Runtime dependencies are now only httpx>=0.28.1,<1 and pydantic>=2.14.2,<3. The Pydantic lower bound is retained from this repository. Use HTTPX’s pool, explicit timeouts, and MockTransport; use Pydantic v2 validation/serialization directly. Let those packages manage their own pydantic-core, typing-extensions, and concurrency dependencies. Existing pytest, coverage, Ruff, Bandit, Twine, and optional Sphinx tooling are retained. Milestone 8 adds pytest-asyncio to the development group for offline async tests. A type checker and its configuration are a separate tooling decision. See HTTPX and Pydantic models.

Removed the unused copied _models, _types, _compat, and _utils cluster: it contained unchecked model construction, Pydantic compatibility machinery, async conversion, generic transformers, proxies, multipart/streaming-related types, and dangling helper imports. No code outside that cluster imported it. Removed unrelated org-ID/YAML validation constants, Stainless response flags, audio queue sizing, and oversized HTTP defaults. Retained the package identity, verified base URL/default locale, empty resource/model/integration namespaces, py.typed, and existing base exception. Removed the redundant public version.py module; use sfdctrust.__version__ for the package version. Fixed the checkout version fallback (it previously looked one directory above the repository) and exposed package __version__. The PEP 621 version remains authoritative and unchanged.

The following SDK policies are distinct from Salesforce requirements. The credential, exception, and transport decisions are implemented as described below. All five read operations apply the model policies below. Tenant listing and event search each offer a single-page method and traversal helpers.

Area

SDK policy

Credentials

Explicit required pat for construction; opt-in from_env() reads only SFDCTRUST_PAT. An explicit override takes precedence; empty overrides fail rather than silently fall back. Store-backed mode uses its configured store as the sole PAT source. Hide the PAT from repr/logs/errors.

Ownership

Internally created httpx.Client and httpx.AsyncClient instances are SDK-owned and closed by close(), await aclose(), or context exit. Injected clients remain caller-owned. Construction makes no network requests.

Network defaults

Connect and pool timeouts default to 5 seconds, read and write to 30 seconds. The owned pool allows 20 total and 10 idle connections. Two retries by default, configurable from 0 to 5. Fallback waits start at 0.5 seconds and double, plus up to 0.25 seconds of jitter. Applicable Retry-After waits are capped at 30 seconds.

Safe retry classification

Retry the five documented reads on connection establishment failures, timeouts, and HTTP 429/500/502/503/504. Other errors fail immediately. The transport rejects PAT refresh.

Credential destination

Fixed production HTTPS origin and API base path with redirects disabled per request. The owned client verifies TLS and ignores environment proxy and CA settings. Injection requires a trusted client.

Models

Python snake_case attributes with explicit camelCase aliases; deliberate JSON serialization with by_alias=True. Validate known field types/requiredness; preserve response extras with extra='allow' even where vendor schemas are closed. Strict request validation.

Optionality/time

Preserve omitted versus explicit-null via Pydantic field-set information and exclude_unset. Reject null on optional non-nullable wire fields. Require aware input timestamps; preserve response offsets, with explicit UTC conversion when needed. Keep ISO durations lossless as strings initially.

Event evolution

Validate outgoing enum filters; preserve unknown response enum strings/data. Dispatch known data shapes using eventType, rather than an untagged permissive union that could select the wrong shape. Design this before event models.

Pagination

Single-page access and lazy or collecting traversal. Repeated cursors or a required page beyond the limit raise PaginationError. HTTP 400 cursor errors propagate without restart.

Errors

Retain TrustCenterError; add a small hierarchy for configuration, network/timeout, API status, authentication, rate limiting, not found, and malformed responses. Preserve status and a verified safe request ID when available; do not retain raw credential-bearing requests or unsanitized server messages. Header name for request IDs is not specified by this API.

Freshness

No caching initially. Defer an SDK retrieved_at envelope until its return-shape implications are decided; do not add it to Salesforce’s wire schema.

Authentication and exceptions implemented (2026-11-02)#

_auth.PATAuth is an internal HTTPX auth component with required explicit pat construction and opt-in from_env() reading only SFDCTRUST_PAT. An explicit override wins without an environment read; empty, blank, non-string, and explicit None overrides fail rather than fall back. PAT values are opaque visible-ASCII strings: whitespace/control characters are rejected without trimming, and JWT parsing is not performed. Construction performs no I/O. Pydantic SecretStr protects ordinary representations; pickling is disabled. Only the fixed production HTTPS origin without URL user information may receive the Bearer header. The auth flow sends once and passes 401 responses through unchanged, without parsing, retrying, or refreshing. The transport disables redirects on every request.

The public exception hierarchy is exported from sfdctrust: TrustCenterError, ConfigurationError, NetworkError / RequestTimeoutError, APIStatusError / AuthenticationError (401), RateLimitError (429), NotFoundError (404), and MalformedResponseError. Status errors retain only a validated integer status_code and an SDK-authored message, with no raw request, response, or server message. Request-ID capture is deferred because no safe header source has been verified. Other exception messages must likewise be SDK-authored and secret-free.

The current Salesforce authentication guide was rechecked for Bearer authentication and 401 semantics. HTTPX’s custom auth protocol was checked against its official documentation. Tests use synthetic credentials and mock requests; no live API calls or real credential discovery occurred. See the authentication boundaries and exception reference.

Minimal synchronous transport implemented (2026-11-02)#

The private transport builds requests under the production API base, applies PATAuth per request, translates HTTP errors before reading the response body, and decodes successful responses as strict UTF-8 JSON. It returns the decoded value for resource-level validation. Request IDs and async support remain deferred. See the transport reference for ownership, timeout precedence, and retry details.

The current Salesforce overview, getting-started guide, and authentication guide were accessible for this milestone. The rendered endpoint reference did not expose its operation content to the fetch tools. The retry allowlist uses the operation inventory above and the local OpenAPI copy. Transport behavior is tested offline with synthetic PATs.

Recommended sequence:

  1. Complete: _auth.py input/environment validation and safe secret handling, plus the small _exceptions.py hierarchy and offline tests for missing/blank inputs, precedence, redaction, destination restrictions, and unchanged 401 behavior.

  2. Complete: _transport.py with ownership, HTTPS destination checks, redirect blocking, finite timeouts, bounded retries, status translation, strict JSON, and offline mock tests.

  3. Complete: TrustCenterClient and client.tenants.list(*, page_size=None, page_token=None, locale=None) -> TenantListResponse. The resource validates supplied arguments, forwards opaque tokens and locale strings, and leaves unspecified values to Salesforce. A cursor error surfaces as an HTTP 400 APIStatusError.

The public client reuses PAT authentication and the private transport. One call returns one page scoped to the PAT’s authorized tenants. Empty results establish no Salesforce-wide health claim. See the Quickstart and tenant reference for explicit pagination, model imports, wire serialization and validation behavior.

Remaining synchronous reads implemented (2026-11-03)#

client.status.snapshot(), client.events.search(), client.events.get(), and client.tenants.get() share the existing transport. Detail IDs are quoted as one segment and checked by the transport against its existing decoded-path restrictions. The transport continues to retry POST only for /events/search. Search forwards duplicate scope entries within the 1–50 input limit, leaving deduplication to Salesforce. Timestamp inputs use minute-aligned ISO 8601 offsets and are compared as instants. The response models dispatch event data by eventType and known timeline shapes by subEventType, checking known subtype compatibility with a known parent. Unknown response enums and extra fields survive validation. The SDK uses a static MalformedResponseError for response schema failures. See the status and event reference and tenant reference for signatures and model imports.

Synchronous pagination and resilience (2026-11-03)#

The Salesforce getting-started guide confirms that tenant pagination repeats the request with pageToken from nextPageToken and stops when the token is absent. The rendered reference supplied no operation content during this check. The local vendor YAML supplies event search cursor placement, argument matching, cursor invalidation, and the five reads’ plain-text gateway 429 without Retry-After. The authentication guide separately confirms a plain-text, headerless 429 for refresh. The SDK supports optional Retry-After according to RFC 9110, section 10.2.3.

The one-page tenants.list() and events.search() methods retain their contracts. tenants.iter_all(), tenants.list_all(), events.iter_search(), and events.search_all() accept the same arguments plus max_pages: int = 1000. They preserve omissions, server order, duplicate entries, and opaque cursors, including an empty string. An empty page counts and can have a continuation. Retries do not count as pages. PaginationError is an SDK guard against a repeated cursor or a required page beyond the limit. Server-rejected cursors raise HTTP 400 APIStatusError without restarting. See the tenant reference and event reference.

Both constructors accept max_retries: int = 2, with a range of 0 through 5. Header-directed waits on HTTP 429 or 503 accept integer seconds or HTTP dates. Past dates yield zero delay. The SDK’s 30-second cap can cause a retry sooner than the server requested. See the transport reference.

Explicit PAT refresh and secure persistence (2026-11-04)#

The current Salesforce authentication guide confirms Bearer auth, the optional request body, the 1–30-day range, replacement in secret, immediate revocation of the old PAT, 401 semantics, plain-text 429 without retry headers, and the old-PAT check after 500 or timeout. The rendered API reference exposed no operation content. The local vendor YAML supplies the production base, HTTP 200 response and exact PatRefreshRequest and PatCredential schemas. The vendor file is excluded from distribution artifacts.

TrustCenterClient.from_store(store, *, http_client=None, max_retries=2) loads a seeded lineage. A conditional durable pending write gates the single POST /pats/refresh. A conditional commit stores the replacement and removes the marker atomically before the client activates it. The SDK validates the opaque replacement against its PAT header rules and reports response metadata validation as a boolean. Metadata drift leaves a usable replacement eligible for commit. refresh_pat(*, expires_in_days=None) and retry_pat_persistence() return PATRefreshResult without server-supplied values. A previously loaded store-backed client must be recreated after a different client rotates the PAT.

Known 401 and 429 responses allow conditional marker removal. An ambiguous outcome probes the old PAT once and leaves the marker for operator recovery. A failed or unacknowledged replacement write blocks the initiating client until it confirms persistence. Recovery of the held replacement uses the original attempt and candidate revision, with no additional POST. See the authentication reference for the public adapter guarantees and recovery runbook.

Asynchronous client (2026-11-04)#

AsyncTrustCenterClient implements the merged synchronous wire contract using native HTTPX asyncio I/O. The five reads share request preparation, validation, model parsing, and retry decisions with the sync client. The resource methods and collectors are awaited. The traversal factories return lazy async iterators directly, with search sequences copied at iterator creation and fetches starting on first advancement. Cancellation propagates from requests, backoff, and traversal.

await AsyncTrustCenterClient.from_store(store, ...) awaits an explicit AsyncPATStore that provides the same strongly consistent load and durable CAS semantics as PATStore. Refresh awaits marker confirmation before one POST, preserves unresolved attempts after cancellation or ambiguous outcomes, and retains a decoded usable replacement before another await. Persistence recovery reconciles the exact attempt or committed replacement with store I/O alone. See the authentication reference.

Milestone 8 preserves the existing API methods, fields, and errors. The wire details above retain their original Salesforce guide and local vendor YAML provenance.

Built-in single-host SQLite store (0.2.0)#

SQLitePATStore implements the synchronous PATStore contract without a new third-party runtime dependency. Ordinary construction opens an existing store; initialize(*, pat, path=None, alias=None) exclusively creates and seeds one. The installed python -m sfdctrust.pat_store init command uses hidden input or an explicitly selected environment variable. The default is ~/.sfdctrust/pat.sqlite3; aliases choose another basename in that directory.

The versioned format uses application_id=0x53464454, user_version=1, and a single credential slot with revision, PAT, and pending attempt. Conditional writes compare both identifiers and durably commit the complete record. Each connection uses rollback DELETE journaling, synchronous EXTRA, and macOS fullfsync. Missing, unsafe, incompatible, or corrupt stores fail closed. The old unversioned example is not automatically migrated.

macOS/Linux ownership and mode checks, macOS ACL inspection, and native Windows ACL creation/inspection protect the database and private directory. Store identities and sidecars are rechecked on access. The supported boundary is one local encrypted volume, one host, and one OS account, with every rotator using the same database. SQLite does not encrypt the PAT, and volume encryption and placement outside sync/network folders remain operator responsibilities.

This adapter uses the existing refresh state machine without new endpoint or retry behavior. Real SQLite offline tests cover process competition, persisted markers, process exit, rollback, lock/write failure, and lost acknowledgment. Hosted tests and installed-wheel walkthroughs passed on macOS, Windows, and Ubuntu. See the platform qualification results for the verified run and the authentication reference for API, format, platform policy, and operator recovery.

Validation of the original foundation#

On Python 3.12, the eight offline version tests, Ruff lint, formatting of changed Python files, Bandit, Poetry configuration checks, wheel/sdist builds, and Twine metadata checks passed. A clean wheel installation imported every retained module and passed pip check; an uninstalled source checkout also imported successfully. The wheel includes py.typed and declares exactly two runtime dependencies. The sdist includes this contract and the tests, and excludes local vendor/private files and virtual environments. All 68 local OpenAPI references resolve and all 27 schema names are covered in this inventory; this is a structural check, not full OpenAPI semantic validation or live-response verification.

Repository-wide ruff format --check . still flags four unchanged files: AGENTS.md and the models, resources, and integrations namespace __init__.py files. Their existing formatting was left intact. No hosted CI, Python-version matrix, live Salesforce, or Sphinx build was run; Sphinx has no configuration in this checkout.