diff --git a/docs/v0.1.0/getting-started.md b/docs/v0.1.0/getting-started.md index b9ba9a9..ab1dd5d 100644 --- a/docs/v0.1.0/getting-started.md +++ b/docs/v0.1.0/getting-started.md @@ -69,7 +69,7 @@ example on Linux or macOS. On Windows, use a Linux environment such as WSL. Start the minimal Provider-side Bootstrap server: -```console title="Terminal 1 — Provider runtime" +```console title="Terminal 1 - Provider runtime" python -m examples.bootstrap.server \ unix:/tmp/stateforge-bootstrap.sock \ 7f7db7d8-68b4-4f71-9769-065b5c4f941c \ @@ -80,7 +80,7 @@ The server binds one local endpoint for the supplied Provider instance and endpoint generation. Leave it running, then open a second terminal with the same virtual environment activated: -```console title="Terminal 2 — Agent runtime" +```console title="Terminal 2 - Agent runtime" python -m examples.bootstrap.client \ unix:/tmp/stateforge-bootstrap.sock \ 7f7db7d8-68b4-4f71-9769-065b5c4f941c \ diff --git a/docs/v0.1.0/procedures/operation-admission.md b/docs/v0.1.0/procedures/operation-admission.md index c89099d..8eb8e7a 100644 --- a/docs/v0.1.0/procedures/operation-admission.md +++ b/docs/v0.1.0/procedures/operation-admission.md @@ -148,6 +148,12 @@ only; an existing terminal operation still resolves to the same admission record, while its retained terminal outcome is read through the operation lifecycle procedure. +Provider presentation is not an admission input. An operation request surface +may help a user construct an invocation, but only the accepted operation +identifier and authoritative `input_schema` govern validation. +`presentation_revision` is not part of the invocation or its canonical request +fingerprint. + ## Request model `StartOperationRequest` deliberately separates the immutable semantic diff --git a/docs/v0.1.0/procedures/provider-manifest.md b/docs/v0.1.0/procedures/provider-manifest.md index 329f084..387e80b 100644 --- a/docs/v0.1.0/procedures/provider-manifest.md +++ b/docs/v0.1.0/procedures/provider-manifest.md @@ -88,8 +88,8 @@ python -m pip install stateforge-protocol grpcio | Source | Responsibility | | --- | --- | | [`manifest.proto`](https://github.com/stateforge-org/stateforge-protocol/blob/mvp/implementation/proto/stateforge_protocol/sfp/manifest/v1/manifest.proto) | Owns messages, field numbers, and the unary `ManifestService.GetManifest` RPC. | -| [`contract.py`](https://github.com/stateforge-org/stateforge-protocol/blob/mvp/implementation/src/stateforge_protocol/sfp/manifest/v1/contract.py) | Owns the canonical service identity and request, response, declaration, schema, and revision resource limits. | -| [`validation.py`](https://github.com/stateforge-org/stateforge-protocol/blob/mvp/implementation/src/stateforge_protocol/sfp/manifest/v1/validation.py) | Owns packaged-schema validation, embedded-schema inspection, bounded canonicalization, revision calculation and verification, and cache-key validation. | +| [`contract.py`](https://github.com/stateforge-org/stateforge-protocol/blob/mvp/implementation/src/stateforge_protocol/sfp/manifest/v1/contract.py) | Owns the canonical service identity and the limits for declarations, presentation overlays, assets, schemas, and revisions. | +| [`validation.py`](https://github.com/stateforge-org/stateforge-protocol/blob/mvp/implementation/src/stateforge_protocol/sfp/manifest/v1/validation.py) | Owns complete exchange validation, independent manifest and presentation acceptance, embedded-schema inspection, canonical revisions, and cache keys. | | [`manifest.schema.json`](https://github.com/stateforge-org/stateforge-protocol/blob/mvp/implementation/src/stateforge_protocol/sfp/manifest/v1/manifest.schema.json) | Defines the request and response ProtoJSON projections and manifest schema-1 structure. | ### Python API surface @@ -101,9 +101,11 @@ python -m pip install stateforge-protocol grpcio | Server interface and registration | `manifest_pb2_grpc.ManifestServiceServicer` and `add_ManifestServiceServicer_to_server` | | Service identity and resource limits | `stateforge_protocol.sfp.manifest.v1.contract` | | Complete response validation | `validation.validate_manifest_response` | +| Operational and presentation snapshot validation | `validation.validate_manifest_exchange` | | Declaration and embedded-schema validation | `validation.validate_manifest_document` and `validation.validate_schema` | -| Deterministic revision | `validation.compute_manifest_revision` | -| Cache-key validation | `validation.validate_manifest_key` | +| Presentation overlay validation | `validation.validate_presentation_document` | +| Deterministic revisions | `validation.compute_manifest_revision` and `validation.compute_presentation_revision` | +| Cache-key validation | `validation.validate_manifest_key` and `validation.validate_presentation_key` | Import the complete public surface from the versioned package: @@ -146,6 +148,8 @@ revisioned declaration snapshot. | Response | `manifest_schema_version` | Highest manifest schema version supported by both peers. | | Response | `manifest` | Complete Provider declaration for the selected schema. | | Response | `manifest_revision` | Deterministic SHA-256 revision of the accepted declaration snapshot. | + | Response | `presentation` | Optional Provider, operation, and trigger surfaces described by bounded component trees, renderer requirements, and embedded assets. | + | Response | `presentation_revision` | Independent SHA-256 revision bound to this manifest; present exactly when `presentation` is present. | === "Example request" @@ -251,9 +255,8 @@ different response fences. ### Session binding `GetManifestRequest.expected_session_id` uses field **4** and -`GetManifestResponse.session_id` uses field **6**. Existing field numbers and -meanings are preserved. Both are required opaque strings of 1–255 Unicode -code points, matching capability assessment. Preserve exact case and contents; +`GetManifestResponse.session_id` uses field **6**. Both are required opaque strings of +1–255 Unicode code points, matching capability assessment. Preserve exact case and contents; do not trim, normalize, parse as UUID, or derive them from endpoint identity. No mandatory session metadata header is introduced. @@ -276,6 +279,24 @@ express negotiated context; they are not authentication credentials or permission to execute operations. Existing channel trust requirements still apply. +## Presentation snapshot + +The operational manifest already contains everything needed to build a correct +default interface. Its JSON Schemas define fields, types, required values, +validation, and secret-bearing inputs. The optional `presentation` snapshot +selects versioned renderer components and binds them to defined data sources +without changing any of those facts. + +The presentation and its revision are present as a pair. The Agent validates +the operational manifest first and can use it even when presentation is +absent or rejected. A valid presentation is revised independently and bound +to the accepted `manifest_revision`. + +The [Provider presentation guide](provider-presentation.md) explains surfaces, +the generic component tree, core renderers, custom renderer metadata and +fallback, data bindings, and embedded assets. The wire fields, validation +pipeline, and limits remain defined on this page. + ## Declaration model The public Provider framework constructs these declarations from Python @@ -422,7 +443,12 @@ flowchart TB Decode --> Document["Validate the packaged
document schema"] Document --> Embedded["Validate embedded
Draft 2020-12 schemas"] Embedded --> Semantic["Validate session fences,
declaration semantics, and revision"] - Semantic --> Accept["Manifest accepted"] + Semantic --> Accept["Operational manifest accepted"] + Accept --> Overlay{"Presentation present
and supported?"} + Overlay -->|No| Fallback["Use schema-derived rendering"] + Overlay -->|Yes| Presentation["Validate overlay references,
assets, and revision"] + Presentation -->|Valid| Enhanced["Accept presentation snapshot"] + Presentation -->|Invalid| Fallback ``` | Stage | Question answered | @@ -432,6 +458,7 @@ flowchart TB | Packaged document schema | Is the complete request or response structurally valid? | | Embedded-schema validation | Are operation, result, configuration, and trigger schemas safe Draft 2020-12 documents? | | Semantic validation | Do identities, session fences, declaration rules, and the deterministic revision agree? | +| Presentation validation | Do optional views refer only to declared capabilities and schema fields, use compatible preferences, carry safe assets, and match their independent revision? | !!! important "Decoding is not validation" @@ -470,7 +497,7 @@ validation or revision calculation. | --- | --- | | `manifest.proto` | Field names, numbers, wire types, messages, and service shape. | | `manifest.schema.json` | Required fields, identifier syntax, uniqueness, counts, and nested structural constraints. | -| `validation.py` | Embedded-schema inspection, bounded canonicalization, revision calculation, and revision verification. | +| `validation.py` | Embedded-schema and presentation semantics, bounded canonicalization, independent revision calculation, and cache-key validation. | | Provider and Agent runtimes | Live-session lookup, declaration construction, request correlation, cache storage, and admission decisions. | The protocol package exposes validation functions; callers invoke them @@ -487,6 +514,8 @@ declarations, or maintain Agent caches. | Operation, trigger, requirement, and profile identifiers | Their respective canonical identifier syntax. | | Manifest schema version | A known supported version. | | Manifest revision | `sha256:` followed by 64 lowercase hexadecimal characters. | +| Presentation schema version | Version `1` when a presentation snapshot is included. | +| Presentation revision | `sha256:` followed by 64 lowercase hexadecimal characters and bound to the accepted manifest revision. | | Repeated declarations | Unique where the contract defines set-like semantics. | ### Bounded validation @@ -498,12 +527,15 @@ Implementations enforce these limits before accepting a snapshot: | Serialized request | 8 KiB | | Serialized response | 2 MiB | | Canonical revision preimage | 1 MiB | +| Canonical presentation revision preimage | 2 MiB | | JSON nodes processed during validation | 100,000 | | Schema nodes processed per embedded document | 25,000 | | Each operations, triggers, or requirements map | 1,024 entries | | Platform pairs | 256 unique pairs | | Profile claims per operation | 64 unique claims | | Embedded JSON nesting | 64 containers | +| Presentation assets | 64 assets; 256 KiB each; 1 MiB total | +| Presentation dimensions | 8192 × 8192 pixels | !!! warning "Reject expensive input early" @@ -516,13 +548,13 @@ Implementations enforce these limits before accepting a snapshot: Input, result, configuration, and trigger schemas are Draft 2020-12 documents carried in `google.protobuf.Struct`. -| Area | Rule | -| --- | --- | -| Root | Explicitly declare `$schema` and `type: object`. Boolean subschemas are allowed below the root. | -| References | Use only local fragment references that resolve inside the same document. Never retrieve a remote schema. | -| Base URI | `$id` is prohibited, so nested content cannot change the reference base. | -| JSON values | Reject duplicate object keys, NaN, infinity, invalid Unicode, non-JSON values, and numbers outside RFC 8785's interoperable domain. | -| Content | Carry types, constraints, and safe static metadata—not configured values, credentials, customer data, or component bindings. | +| Area | Rule | +| --- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Root | Explicitly declare `$schema` and `type: object`. Boolean subschemas are allowed below the root. | +| References | Use only local fragment references that resolve inside the same document. Never retrieve a remote schema. | +| Base URI | `$id` is prohibited, so nested content cannot change the reference base. | +| JSON values | Reject duplicate object keys, NaN, infinity, invalid Unicode, non-JSON values, and numbers outside RFC 8785's interoperable domain. | +| Content | Carry types, constraints, and safe static metadata, not configured values, credentials, customer data, or component bindings. | | Secrets | Mark secret-bearing inputs with `writeOnly: true`. They cannot expose `default`, `examples`, `const`, or `enum` values, directly or through references and composed schemas. | ### What validation cannot prove @@ -598,7 +630,11 @@ is `sha256:6bfdf3aedc2d4e45d77d4787cc0e744a488208b2510d81788291f51d24a623e8`. limits, and canonical digest. Store only accepted snapshots. A revision is a change detector, not authentication. Profile-specific conformance still requires the validators and behavior tests defined by that profile. -5. An invalid manifest leaves the integration unusable even if gRPC health is +5. Validate `presentation` independently. Cache it by Provider identity, + accepted manifest revision, presentation schema version, and presentation + revision. If it is absent, unsupported, or invalid, discard it and retain + complete schema-derived rendering from the accepted manifest. +6. An invalid manifest leaves the integration unusable even if gRPC health is `SERVING`. Block operational requests. A valid changed manifest replaces the normalized declaration and triggers Agent-owned reconciliation. @@ -617,6 +653,7 @@ protocol package does not implement the cache or inventory. | Session unknown/inactive, handshake missing, or instance/generation does not match the requested active session | Provider returns `FAILED_PRECONDITION`; Agent re-establishes a session (rediscovering if needed) before a new attempt. | | No common manifest schema version | Provider returns `UNIMPLEMENTED`; Agent marks the endpoint incompatible instead of indefinitely retrying unchanged capabilities. | | Provider cannot produce a valid snapshot | Fail startup before ready publication where possible; otherwise return `INTERNAL` with sanitized diagnostics, never partial success. | +| Presentation is absent, unsupported, invalid, or its revision does not match | Accept the operational manifest, discard the presentation snapshot, and render directly from the manifest schemas. | | Transport lost or temporarily unavailable | `UNAVAILABLE`; bounded read retries with backoff are safe after validating/re-establishing the session. | | Client deadline or cancellation | Standard `DEADLINE_EXCEEDED` / `CANCELLED`; no operation is started or cancelled by this read. | | Success payload fails Agent validation or revision check | Local manifest rejection, independently of transport health; it is not a successful capability negotiation. | @@ -645,13 +682,19 @@ no generic target-kind declaration or configured resource. An operation's `input_schema` defines any resource information that operation needs. The manifest contains schemas, not configuration values or operation inputs. +`ProviderPresentation` is a separate optional snapshot in the same response. +It describes the Provider itself and overlays declared operations, triggers, +and schema fields. It cannot add or hide capabilities, redefine schemas, carry +runtime values, or affect operation and trigger protocol semantics. + The `manifest_revision` hashes the canonical declaration, schema version, and -Provider instance identity. Session ID and endpoint generation are not part of -that preimage. Consumers must validate the full response and revision before -caching it; a changed declaration has a different revision. +Provider instance identity. `presentation_revision` separately hashes the +presentation snapshot while binding it to that accepted manifest revision. +Session ID and endpoint generation are not part of either preimage. Consumers +must validate each snapshot before caching it. This package defines wire messages, validation schemas, and conformance vectors, not Provider session storage or an Agent client. The portable -`tests/fixtures/manifest/request.json`, `response.json`, and -`session-binding.json` fixtures exercise the current schema and session -binding. +`tests/fixtures/manifest/request.json`, `response.json`, +`presentation-response.json`, and `session-binding.json` fixtures exercise the +schema, presentation overlay, and session binding. diff --git a/docs/v0.1.0/procedures/provider-presentation.md b/docs/v0.1.0/procedures/provider-presentation.md new file mode 100644 index 0000000..165abcb --- /dev/null +++ b/docs/v0.1.0/procedures/provider-presentation.md @@ -0,0 +1,337 @@ +# Provider presentation + +A Provider presentation is an optional, independently revised interface +declaration attached to an accepted [Provider manifest](provider-manifest.md). +It tells a Control Plane which surfaces a Provider offers and describes each +surface as a bounded tree of renderer components. + +Presentation does not change an operation, trigger, schema, authorization +decision, or runtime value. If it is absent, unsupported, or invalid, the +operational manifest remains usable and the Control Plane can render directly +from its JSON Schemas. + +## From manifest to interface + +```mermaid +flowchart LR + Manifest["ProviderManifest
capabilities + JSON Schemas"] --> Sources["Control Plane data sources"] + Presentation["ProviderPresentation
surfaces + component trees"] --> Validate{"SFP presentation
valid?"} + Validate -->|yes| Registry["Control Plane
renderer registry"] + Validate -.->|no| Defaults["Schema-derived interface"] + Sources --> Registry + Assets["Embedded PNG / SVG assets"] --> Registry + Extensions["Installed renderer extensions"] --> Registry + Registry --> Render["Rendered Provider, operation,
trigger, and evidence surfaces"] + Defaults --> Render +``` + +| Layer | Owns | +| --- | --- | +| Operational manifest | Capability identifiers, JSON Schemas, requirements, and execution semantics | +| SFP presentation contract | Surface identifiers, component-tree structure, bindings, conditions, repetition, extension metadata, safe assets, and limits | +| Control Plane renderer registry | The property schema and rendering behavior for each component identifier | +| Control Plane skin | Typography, color, spacing, framing, and product-wide visual language | + +SFP carries declarative data only. It never carries HTML, CSS, JavaScript, +executable renderer bytes, an installation command, or a remote asset URL. + +## Presentation targets and surfaces + +A `ProviderPresentation` can attach a `PresentationTarget` to the Provider +itself and to any operation or trigger declared by the same manifest. Operation +and trigger map keys must match exact manifest identifiers. + +Each target contains one or more named surfaces: + +| Target | Surface identifier | Intended use | +| --- | --- | --- | +| Provider | `stateforge.ui/surface.provider.overview@1` | Provider identity, status, capabilities, and summary information | +| Operation | `stateforge.ui/surface.operation.request@1` | Construct and review an operation request | +| Operation | `stateforge.ui/surface.operation.run@1` | Follow an admitted operation while it runs | +| Operation | `stateforge.ui/surface.operation.result@1` | Inspect a terminal operation result | +| Trigger | `stateforge.ui/surface.trigger.policy@1` | Configure how a trigger participates in policy | +| Trigger | `stateforge.ui/surface.trigger.event@1` | Inspect one published trigger event | +| Operation or trigger | `stateforge.ui/surface.evidence@1` | Inspect evidence and audit material associated with that target | + +Groups are optional. A Provider author creates visual grouping with ordinary +layout components such as a section, grid, tabs, or steps; the Protocol does +not impose a separate grouping model. + +## The generic component tree + +Every `PresentationSurface` has one root `ComponentNode`. A node selects a +renderer by versioned string identifier and supplies only the data needed to +configure it. + +```mermaid +flowchart TD + Surface["PresentationSurface"] --> Root["ComponentNode root"] + Root --> ID["component_identifier"] + Root --> Props["properties"] + Root --> Bindings["bindings"] + Root --> Children["children"] + Root --> Assets["asset_bindings"] + Root -. optional .-> Condition["condition"] + Root -. optional .-> Repeat["repeat"] + Root -. custom only .-> Fallback["core fallback"] +``` + +| Node field | Meaning | +| --- | --- | +| `component_identifier` | Versioned identifier resolved by the Control Plane renderer registry | +| `properties` | Renderer-specific static configuration; SFP treats it as inert JSON | +| `bindings` | Named inputs resolved from the data sources available to the current surface | +| `children` | Ordered child components | +| `asset_bindings` | Renderer slot names mapped to embedded asset digests | +| `condition` | Optional declarative existence or equality test controlling visibility | +| `repeat` | Optional bounded repetition over a collection binding | +| `fallback` | Required core-only tree used when a custom renderer is unavailable | + +The Protocol validates the identifier and tree, bounds the document, verifies +references, and constrains which data sources exist on each surface. It does +not interpret component properties. The Control Plane validates those +properties against the renderer definition registered for the component +identifier. + +## Core component catalog + +SFP 1.0 defines a compact core catalog that every conforming Control Plane can +render: + +| Category | Component identifiers | +| --- | --- | +| Layout | `layout.stack`, `layout.grid`, `layout.section`, `layout.tabs`, `layout.steps` | +| Input | `input.form`, `input.field`, `input.object`, `input.array`, `input.key_value`, `input.code`, `input.secret` | +| Content and structured data | `content.text`, `content.markdown`, `data.key_value`, `data.table`, `data.tree`, `data.code`, `data.diff`, `data.log` | +| Status and visualization | `status.badge`, `status.progress`, `status.timeline`, `data.metric`, `data.chart`, `data.topology`, `data.artifacts` | +| Media and actions | `media.image`, `action.operation_submit`, `action.operation_cancel` | + +Each value above uses the `stateforge.ui` namespace and `@1` major version. +For example, the complete table identifier is +`stateforge.ui/data.table@1`. + +These are identifiers, not protobuf message types. Adding a renderer does not +require adding a new component-specific message or enum to SFP. + +### Portable core structure + +Core identifiers also carry a small Protocol-owned structural contract. This +does not define styling or renderer properties; it guarantees that an accepted +core tree, including a custom component's fallback, can be interpreted the same +way by every conforming Control Plane. + +| Core family | Surfaces | Children | Binding and asset slots | +| --- | --- | --- | --- | +| Layout | All | One or more | No bindings or assets | +| Form, object, array | Operation request or trigger policy | Optional nested controls | Required `schema`; optional public `value` | +| Field, key/value, code input | Operation request or trigger policy | None | Required `schema`; optional public `value` | +| Secret input | Operation request or trigger policy | None | Required `schema`; secret value remains private host state | +| Text and Markdown | All | None | Optional `value` | +| Key/value, tree, code, badge, progress, and metric | All | None | Required `value` | +| Table, log, timeline, chart, and artifacts | All | None | Required `rows`, `entries`, `events`, `series`, or `items` respectively | +| Diff | All | None | Required `before` and `after` | +| Topology | All | None | Required `nodes` and `edges` | +| Image | All | None | Required `source` asset | +| Submit action | Operation request | None | Host-controlled action; no binding or asset | +| Cancel action | Operation run | None | Host-controlled action; no binding or asset | + +A core component cannot declare a fallback. Custom components must declare a +core-only fallback, and every node in that fallback is checked against this +same structural registry. Renderer-specific `properties` remain owned by the +Control Plane registry. + +## Data bindings + +A `DataBinding` selects one Control Plane-provided source and optionally a +JSON Pointer within it. An empty pointer selects the complete source. The +sources available depend on the surface, preventing a Provider from referring +to data that does not exist in that rendering context. + +Examples include: + +| Surface | Representative binding sources | +| --- | --- | +| Provider overview | Provider manifest and Provider runtime state | +| Operation request | Request schema and the public request draft | +| Operation run | Public admitted-request projection and live operation state | +| Operation result | Public request projection, result schema, result value, and operation evidence | +| Trigger policy | Trigger payload schema | +| Trigger event | Payload schema and published payload value | +| Evidence | Operation evidence or trigger value plus audit data | + +A repetition creates a named item scope. Descendants can bind to +`stateforge.binding/repetition.item@1` only by naming an active scope. Each +repetition also declares a positive `max_items` ceiling. + +Conditions support `EXISTS`, `NOT_EXISTS`, `EQUALS`, and `NOT_EQUALS`. +Existence conditions omit a comparison value; equality conditions require one, +including an explicitly supplied JSON `null`. + +The request-value source is +`stateforge.binding/operation.request.public_value@1`. It is a safe projection, +not the submitted request: every value whose applicable input schema marks it +`writeOnly` is omitted. If an implementation cannot prove that a value is +public, it must omit that value. Secret-entry state remains private to the form +renderer and is never addressable by a presentation binding. The raw request +has no presentation binding identifier. + +## Core example + +The manifest fixture uses a core form for the operation request: + +```json +{ + "componentIdentifier": "stateforge.ui/input.form@1", + "properties": { + "submitLabel": "Resolve reference" + }, + "bindings": { + "schema": { + "sourceIdentifier": "stateforge.binding/operation.request.schema@1", + "pointer": "", + "scope": "" + }, + "value": { + "sourceIdentifier": "stateforge.binding/operation.request.public_value@1", + "pointer": "", + "scope": "" + } + }, + "children": [], + "assetBindings": {} +} +``` + +The operation input JSON Schema remains authoritative. The renderer can produce +an appropriate form because the schema and public draft arrive through +bindings. Secret fields keep their values in private form state, so the +presentation cannot bind or display them. Presentation also cannot relax +validation or manufacture an operation field. + +## Custom components and renderer extensions + +A Provider may use its own component identifier, such as +`example.git/data.commit_graph@1`. A custom node has two additional +requirements: + +1. its namespace has one matching `RendererRequirement`; and +2. the node includes a fallback tree composed only of core + `stateforge.ui` components. + +```json +{ + "componentIdentifier": "example.git/data.commit_graph@1", + "properties": {}, + "bindings": { + "result": { + "sourceIdentifier": "stateforge.binding/operation.result.value@1", + "pointer": "", + "scope": "" + } + }, + "children": [], + "assetBindings": {}, + "fallback": { + "componentIdentifier": "stateforge.ui/data.tree@1", + "properties": {}, + "bindings": { + "value": { + "sourceIdentifier": "stateforge.binding/operation.result.value@1", + "pointer": "", + "scope": "" + } + }, + "children": [], + "assetBindings": {} + } +} +``` + +The matching requirement carries identity and compatibility metadata: + +```json +{ + "example.git": { + "extensionIdentifier": "example.git/renderer@1", + "extensionVersion": "1.0.0", + "rendererApiVersion": "1.0.0", + "artifactDigest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "permissions": [] + } +} +``` + +Every namespace beginning with `stateforge.` is reserved for identifiers +defined by StateForge contracts. A Provider-owned renderer must use a namespace +it owns; it cannot introduce custom components or renderer requirements under +`stateforge.ui`, `stateforge.ui.*`, or another `stateforge.*` namespace. + +The renderer artifact is distributed separately from SFP. The Control Plane +uses the metadata to locate an already trusted or separately acquired bundle, +checks compatibility and permissions in its extension host, and registers the +component identifiers exposed by that bundle. SFP never downloads or executes +it. + +If the extension is missing, incompatible, disabled, or rejected, the Control +Plane renders the core fallback. This preserves a functional interface without +limiting advanced Provider authors to the built-in catalog. + +## Embedded assets + +`PresentationAsset` carries bounded, content-addressed PNG or sanitized SVG +media. Nodes refer to assets through named `asset_bindings`. Every digest must +match the exact bytes, every reference must resolve, and unreferenced assets +are rejected. PNG validation also verifies the complete compressed stream, +decoded scanline layout and filter bytes under a decoded-size ceiling; valid +chunk framing and CRCs alone are not sufficient. + +Assets provide Provider-owned icons and visuals. The active Control Plane skin +still controls their framing, size, background, and placement. + +## Validation and fallback + +The Agent accepts the operational manifest before considering presentation. +The presentation is then evaluated independently: + +| Presentation state | Result | +| --- | --- | +| Absent | Keep the manifest and render from its JSON Schemas. | +| Supported and valid | Cache the component tree and its independent revision. | +| Unsupported schema version | Keep the manifest and ignore presentation. | +| Invalid tree, source, extension metadata, asset, or revision | Keep the manifest and discard the complete presentation snapshot. | + +The Protocol enforces limits for tree depth, total component count, children, +bindings, properties, repetition, extensions, permissions, assets, and +canonical bytes. Partial acceptance is not allowed. + +`manifest_revision` excludes presentation. `presentation_revision` hashes the +complete presentation and is bound to the accepted manifest revision, so a +presentation cannot be reused with a different capability declaration. + +## How it reaches the Control Plane + +The Provider returns `ProviderPresentation` through the existing +`ManifestService.GetManifest` response. The Agent validates and caches the +manifest and presentation independently. + +A future SF-AOP contract will transport the accepted snapshots to the Control +Plane. No second SFP presentation RPC is introduced. Once received, the +Control Plane resolves component identifiers through its renderer registry, +binds the current runtime data, applies its active skin, and renders the +surface. + +For the exact service envelope, revision construction, limits, and public +Python validators, return to +[Provider manifest exchange](provider-manifest.md). + +## Using the Python contract + +| Module | Responsibility | +| --- | --- | +| [`contract.py`](https://github.com/stateforge-org/stateforge-protocol/blob/mvp/implementation/src/stateforge_protocol/sfp/manifest/v1/contract.py) | Owns the supported surface identifiers, core component catalog, binding-source identifiers, renderer metadata limits, and component-tree bounds. | +| [`validation.py`](https://github.com/stateforge-org/stateforge-protocol/blob/mvp/implementation/src/stateforge_protocol/sfp/manifest/v1/validation.py) | Exposes complete Manifest Exchange validation, independent presentation acceptance, presentation revision calculation, and presentation fallback. | + +Provider and Agent implementations should import these canonical definitions +instead of duplicating component identifiers, source identifiers, or limits. +Renderer-specific property schemas belong to the Control Plane renderer +registry and are deliberately not defined by these Protocol modules. diff --git a/docs/v0.1.0/procedures/triggers.md b/docs/v0.1.0/procedures/triggers.md index 5f4fcef..2b198d2 100644 --- a/docs/v0.1.0/procedures/triggers.md +++ b/docs/v0.1.0/procedures/triggers.md @@ -232,6 +232,13 @@ The bound `manifest_revision` selects the declaration snapshot, so a publication has no separate schema-version field and cannot negotiate a schema independently. +Provider presentation does not participate in publication or acknowledgement. +Trigger policy and event surfaces may improve how a consumer configures or +renders a declared trigger, but the trigger identifier and authoritative +`payload_schema` remain the complete wire contract. +`presentation_revision` is not part of the stream binding or publication +content fingerprint. + The Provider normalizes and validates its payload before publishing. The Agent validates the decoded payload again against the exact accepted declaration. Trigger-specific repository, resource, project, or source identity belongs in diff --git a/docs/v0.1.0/reference/ci-automation.md b/docs/v0.1.0/reference/ci-automation.md index ed62d5d..9cdca87 100644 --- a/docs/v0.1.0/reference/ci-automation.md +++ b/docs/v0.1.0/reference/ci-automation.md @@ -24,7 +24,8 @@ flowchart LR

The contract is internally consistent

Protobuf sources, generated bindings, schemas, fixtures, validators, - documentation, and compatibility checks agree before packaging begins. + documentation, descriptor checks, and conformance fixtures agree before + packaging begins.

@@ -79,9 +80,9 @@ installation. No downstream job rebuilds the package. | Gate | What runs | What it proves | | --- | --- | --- | -| Source contracts | Dependency-lock check, Actionlint, Zizmor, Buf lint and format, deterministic generation, Buf compatibility, the complete test suite with coverage, Ruff, mypy, and strict documentation build | The source tree, generated outputs, automation, and documented contract agree | +| Source contracts | Dependency-lock check, Actionlint, Zizmor, Buf lint and format, deterministic generation, the complete test suite with coverage, Ruff, mypy, and strict documentation build | The source tree, generated outputs, automation, and documented contract agree, including Provider presentation overlays, revisions, assets, and fallback | | Distribution build | One wheel and one source distribution, followed by metadata, checksum, and provenance generation | The candidate has one attributable artifact identity | -| Installed package | Wheel and source-distribution installation in isolated virtual environments with the checkout removed from Python import resolution | The package contains its generated modules, public contracts, schemas, typing marker, and conformance fixtures | +| Installed package | Wheel and source-distribution installation in isolated virtual environments with the checkout removed from Python import resolution | The package contains its generated modules, public contracts, schemas, typing marker, Provider presentation fixture, and conformance fixtures | | Agent consumer | Exact wheel installation, package-origin verification, Protocol-ownership audit, and the complete Agent quality suite | The Agent consumes this candidate through public Protocol APIs | | Provider consumer | Exact wheel installation, package-origin verification, Protocol-ownership audit, and the complete Provider quality suite | StateForge Provider Python consumes this candidate through public Protocol APIs | diff --git a/docs/v0.1.0/reference/conformance-coverage.md b/docs/v0.1.0/reference/conformance-coverage.md index 55425d6..07ec9a5 100644 --- a/docs/v0.1.0/reference/conformance-coverage.md +++ b/docs/v0.1.0/reference/conformance-coverage.md @@ -68,7 +68,7 @@ documentation. | [`endpoint-discovery`](../procedures/endpoint-discovery.md) | `sfp.endpoint_discovery.v1.contract` | Descriptor parsing, canonical serialization, filename, identity, generation, socket path, permissions, and size limits | | [`bootstrap`](../bootstrap.md) | `sfp.bootstrap.v1.contract` and `validation` | Handshake request and response validity, identity correlation, version selection, generation fencing, and session bounds | | [`health`](../procedures/health.md) | `sfp.health_contract` with `grpc.health.v1` | Standard service identity, Provider-wide Watch key, lifecycle states, eligibility inputs, failure scenarios, and diagnostic bounds | -| [`manifest`](../procedures/provider-manifest.md) | `sfp.manifest.v1.contract` and `validation` | Declaration shape, embedded schemas, identifiers, canonical revision, session binding, and invalid documents | +| [`manifest`](../procedures/provider-manifest.md) | `sfp.manifest.v1.contract` and `validation` | Declaration shape, embedded schemas, identifiers, session binding, independent revisions, bounded component trees, surface bindings, renderer requirements, core fallback, safe assets, and invalid documents | | [`capability-assessment`](../procedures/capability-assessment.md) | `sfp.capability_assessment.v1.contract` and `validation` | Request and response validity, session and manifest correlation, mixed support findings, invalid invariants, and requirement states | ### Exchange and recover diff --git a/docs/v0.1.0/reference/python-contracts.md b/docs/v0.1.0/reference/python-contracts.md index 64cdae2..9fb5f16 100644 --- a/docs/v0.1.0/reference/python-contracts.md +++ b/docs/v0.1.0/reference/python-contracts.md @@ -112,7 +112,7 @@ The same pattern applies to each procedure: | Procedure | Message validation | Correlation and derived values | | --- | --- | --- | | Bootstrap | `validate_handshake_request`, `validate_handshake_response` | `validate_protocol_version` | -| Provider Manifest | `validate_manifest_document`, `validate_manifest_response` | `compute_manifest_revision`, `validate_manifest_key` | +| Provider Manifest | `validate_manifest_document`, `validate_presentation_document`, `validate_manifest_response`, `validate_manifest_exchange` | Independent manifest/presentation revision and cache-key helpers; `PresentationValidationStatus` for safe fallback | | Capability Assessment | `validate_assess_capabilities_request`, `validate_assess_capabilities_response` | `validate_assessment_exchange` | | Operation Admission | Request, response, record, and error-detail validators | `validate_admission_exchange`, `canonical_invocation`, `compute_request_fingerprint` | | Operation Lifecycle | Watch, Cancel, snapshot, and error-detail validators | Watch/Cancel exchange, transition, and terminal-replay validators | @@ -126,6 +126,32 @@ Endpoint Discovery is a filesystem contract rather than a protobuf procedure. Its public `contract` module owns `EndpointDescriptor`, `parse_descriptor`, filename derivation, permissions, size bounds, and generation validation. +### Manifest and presentation acceptance + +`validate_manifest_exchange` always validates the operational manifest first. +Its result reports whether the optional presentation snapshot was accepted, +absent, unsupported, or invalid without making presentation a prerequisite for +using the declared operations and triggers. + +```python +from stateforge_protocol.sfp.manifest.v1 import validation + +exchange = validation.validate_manifest_exchange(response) +manifest_bytes = exchange.manifest_document + +if ( + exchange.presentation_status + is validation.PresentationValidationStatus.ACCEPTED +): + presentation_bytes = exchange.presentation_document +else: + presentation_bytes = None # Render from the authoritative JSON Schemas. +``` + +Cache the two snapshots independently. A presentation cache key includes the +accepted `manifest_revision`, so an overlay can never move to a different +operational declaration by revision alone. + ## Contract constants Protobuf defines field types, but it cannot configure gRPC message ceilings or diff --git a/mkdocs.yml b/mkdocs.yml index 1e8a364..f73df75 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -23,7 +23,9 @@ nav: - Procedure map: v0.1.0/procedures/index.md - Endpoint discovery and channel establishment: v0.1.0/procedures/endpoint-discovery.md - Handshake and version negotiation: v0.1.0/bootstrap.md - - Provider manifest exchange: v0.1.0/procedures/provider-manifest.md + - Provider manifest exchange: + - Contract and exchange: v0.1.0/procedures/provider-manifest.md + - Provider presentation: v0.1.0/procedures/provider-presentation.md - Health and availability monitoring: v0.1.0/procedures/health.md - Capability assessment: v0.1.0/procedures/capability-assessment.md - Trigger publication and acknowledgement: v0.1.0/procedures/triggers.md diff --git a/proto/stateforge_protocol/sfp/manifest/v1/manifest.proto b/proto/stateforge_protocol/sfp/manifest/v1/manifest.proto index 6e3185f..df79273 100644 --- a/proto/stateforge_protocol/sfp/manifest/v1/manifest.proto +++ b/proto/stateforge_protocol/sfp/manifest/v1/manifest.proto @@ -52,6 +52,15 @@ message GetManifestResponse { // The Agent must match it to both the request and its current session before // accepting or reusing a cached declaration. Not part of manifest_revision. string session_id = 6; + // Optional declarative presentation snapshot. Operational JSON Schemas + // remain sufficient to render every declared capability when this field is + // absent, unsupported or rejected. Presentation never changes execution + // semantics and is not part of manifest_revision. + ProviderPresentation presentation = 7; + // Present exactly when presentation is present. "sha256:" plus 64 lowercase + // hex digits over the canonical presentation preimage defined by this + // package. Session ID and endpoint generation are excluded. + optional string presentation_revision = 8; } // ProviderManifest describes implementation-wide declarations, not configured @@ -119,3 +128,107 @@ message TriggerDeclaration { // Required Draft 2020-12 object schema, never an event instance. google.protobuf.Struct payload_schema = 1; } + +// ProviderPresentation is an optional, independently revised visual overlay +// on an accepted ProviderManifest. Maps use the exact operation and trigger +// identifiers declared by that manifest. Presentation cannot add, remove or +// redefine capabilities or their JSON Schemas. +message ProviderPresentation { + // Presentation document version. Version 1 is defined by this package. + uint32 presentation_schema_version = 1; + // Optional Provider-level surfaces. + PresentationTarget provider = 2; + // Optional surfaces keyed by declared operation identifier. + map operations = 3; + // Optional surfaces keyed by declared trigger identifier. + map triggers = 4; + // Embedded content-addressed visuals keyed by their sha256 digest. + map assets = 5; + // Renderer metadata keyed by the custom component namespace it serves. + // Every stateforge.* namespace is reserved and cannot require an extension. + map renderer_requirements = 6; +} + +// PresentationTarget owns the surfaces declared for one Provider, operation or +// trigger. Keys are versioned surface identifiers defined by this contract. +message PresentationTarget { + map surfaces = 1; +} + +// PresentationSurface is one bounded declarative component tree. +message PresentationSurface { + ComponentNode root = 1; +} + +// ComponentNode selects a renderer by identifier and supplies only declarative +// data. Properties are interpreted by the Control Plane renderer registry, not +// by SFP. Custom components require renderer metadata and a core-only fallback. +message ComponentNode { + string component_identifier = 1; + google.protobuf.Struct properties = 2; + map bindings = 3; + repeated ComponentNode children = 4; + ComponentNode fallback = 5; + Condition condition = 6; + Repetition repeat = 7; + // Renderer-defined slot name to embedded asset digest. + map asset_bindings = 8; +} + +// DataBinding points at immutable data supplied by the Control Plane for the +// current surface. Empty pointer selects the complete source document. Scope is +// empty except for bindings to a named repetition item. +message DataBinding { + string source_identifier = 1; + string pointer = 2; + string scope = 3; +} + +// ConditionOperator controls whether a node is rendered. Equality compares +// JSON values exactly after resolving the binding. +enum ConditionOperator { + CONDITION_OPERATOR_UNSPECIFIED = 0; + CONDITION_OPERATOR_EXISTS = 1; + CONDITION_OPERATOR_NOT_EXISTS = 2; + CONDITION_OPERATOR_EQUALS = 3; + CONDITION_OPERATOR_NOT_EQUALS = 4; +} + +// Condition is optional. EXISTS and NOT_EXISTS omit value; equality operators +// require value, including an explicitly supplied JSON null. +message Condition { + DataBinding binding = 1; + ConditionOperator operator = 2; + google.protobuf.Value value = 3; +} + +// Repetition renders a node once per item in one bound collection. max_items is +// a required positive safety ceiling; item_scope names the item for descendant +// bindings. +message Repetition { + DataBinding collection = 1; + string item_scope = 2; + uint32 max_items = 3; +} + +// RendererRequirement identifies a separately distributed renderer extension. +// SFP transports metadata only: no executable bytes, URL or install command is +// carried by this message. Permissions are versioned identifiers understood by +// the Control Plane extension host. +message RendererRequirement { + string extension_identifier = 1; + string extension_version = 2; + string renderer_api_version = 3; + string artifact_digest = 4; + repeated string permissions = 5; +} + +// PresentationAsset is embedded, content-addressed media. The map key is the +// sha256 digest of content. Remote URLs and filesystem paths have no wire field. +message PresentationAsset { + string media_type = 1; + bytes content = 2; + uint32 width = 3; + uint32 height = 4; + string alt_text = 5; +} diff --git a/scripts/ci/verify_installed.py b/scripts/ci/verify_installed.py index 28867e5..6ca8f19 100644 --- a/scripts/ci/verify_installed.py +++ b/scripts/ci/verify_installed.py @@ -30,6 +30,7 @@ from stateforge_protocol.sfp.endpoint_discovery.v1 import ( contract as endpoint_discovery_contract, ) +from stateforge_protocol.sfp.manifest.v1 import contract as manifest_contract from stateforge_protocol.sfp.manifest.v1 import manifest_pb2 from stateforge_protocol.sfp.manifest.v1 import ( validation as manifest_validation, @@ -212,7 +213,34 @@ def _verify_manifest_validation(fixture_root: Path) -> int: ) if key.revision != response.manifest_revision: raise ValueError("Installed Manifest key validation is invalid") - return 2 + + presented = ParseDict( + _read_json_object( + fixture_root / "manifest" / "presentation-response.json" + ), + manifest_pb2.GetManifestResponse(), + ) + exchange = manifest_validation.validate_manifest_exchange(presented) + if ( + exchange.presentation_status + is not manifest_validation.PresentationValidationStatus.ACCEPTED + or exchange.presentation_key is None + or exchange.presentation_document is None + ): + raise ValueError("Installed Provider presentation was not accepted") + + presented.presentation.provider.surfaces[ + manifest_contract.PROVIDER_OVERVIEW_SURFACE + ].root.properties.update({"tampered": True}) + rejected = manifest_validation.validate_manifest_exchange(presented) + if ( + rejected.presentation_status + is not manifest_validation.PresentationValidationStatus.INVALID + or rejected.presentation_document is not None + or rejected.manifest_document != exchange.manifest_document + ): + raise ValueError("Installed Provider presentation fallback is invalid") + return 4 def _verify_trigger_publication_validation(fixture_root: Path) -> int: diff --git a/src/stateforge_protocol/sfp/manifest/v1/_presentation.py b/src/stateforge_protocol/sfp/manifest/v1/_presentation.py new file mode 100644 index 0000000..b1bca07 --- /dev/null +++ b/src/stateforge_protocol/sfp/manifest/v1/_presentation.py @@ -0,0 +1,849 @@ +"""Validate Provider presentation overlays and embedded visual assets.""" + +from __future__ import annotations + +import hashlib +import re +import struct +import zlib +from typing import Any, Final, Never, cast +from xml.etree import ElementTree + +import rfc8785 + +from stateforge_protocol.sfp.manifest.v1 import contract, manifest_pb2 + +_LOCAL_ASSET_REFERENCE: Final = re.compile( + r"url\(#[A-Za-z_][A-Za-z0-9_.:-]*\)" +) +_SVG_NAMESPACE: Final = "http://www.w3.org/2000/svg" +_SAFE_SVG_TAGS: Final = frozenset( + { + "circle", + "clipPath", + "defs", + "desc", + "ellipse", + "g", + "line", + "linearGradient", + "mask", + "path", + "polygon", + "polyline", + "radialGradient", + "rect", + "stop", + "svg", + "symbol", + "title", + } +) +_SAFE_SVG_ATTRIBUTES: Final = frozenset( + { + "aria-hidden", + "aria-label", + "clip-path", + "cx", + "cy", + "d", + "fill", + "fill-opacity", + "gradientTransform", + "gradientUnits", + "height", + "id", + "mask", + "offset", + "opacity", + "points", + "preserveAspectRatio", + "r", + "role", + "rx", + "ry", + "stop-color", + "stop-opacity", + "stroke", + "stroke-linecap", + "stroke-linejoin", + "stroke-opacity", + "stroke-width", + "transform", + "viewBox", + "width", + "x", + "x1", + "x2", + "y", + "y1", + "y2", + } +) +_PNG_SIGNATURE: Final = b"\x89PNG\r\n\x1a\n" +_PNG_CHUNK_OVERHEAD: Final = 12 +_PNG_IHDR_BYTES: Final = 13 +_PNG_DECODE_CHUNK_BYTES: Final = 64 * 1024 +_PNG_MAX_FILTER_TYPE: Final = 4 +_SAFE_PNG_CHUNKS: Final = frozenset( + {b"IHDR", b"PLTE", b"IDAT", b"IEND", b"tRNS"} +) + + +def validate_presentation_semantics( + presentation: dict[str, Any], + manifest: dict[str, Any], + message: manifest_pb2.ProviderPresentation, + *, + error_type: type[ValueError], +) -> None: + """Validate a bounded component tree and all of its references.""" + operations = cast(dict[str, dict[str, Any]], manifest["operations"]) + triggers = cast(dict[str, dict[str, Any]], manifest["triggers"]) + operation_targets = cast( + dict[str, dict[str, Any]], presentation["operations"] + ) + trigger_targets = cast(dict[str, dict[str, Any]], presentation["triggers"]) + requirements = cast( + dict[str, dict[str, Any]], presentation["rendererRequirements"] + ) + + if not operation_targets.keys() <= operations.keys(): + raise error_type( + "presentation: operation target does not name a declared operation" + ) + if not trigger_targets.keys() <= triggers.keys(): + raise error_type( + "presentation: trigger target does not name a declared trigger" + ) + if any(_is_stateforge_owned(namespace) for namespace in requirements): + raise error_type( + "presentation: renderer requirements cannot use a " + "StateForge-owned namespace" + ) + + state = _PresentationState() + provider = presentation.get("provider") + if isinstance(provider, dict): + _validate_target( + provider, + target_kind="provider", + permitted_surfaces=contract.PROVIDER_SURFACES, + state=state, + requirements=requirements, + error_type=error_type, + ) + for target in operation_targets.values(): + _validate_target( + target, + target_kind="operation", + permitted_surfaces=contract.OPERATION_SURFACES, + state=state, + requirements=requirements, + error_type=error_type, + ) + for target in trigger_targets.values(): + _validate_target( + target, + target_kind="trigger", + permitted_surfaces=contract.TRIGGER_SURFACES, + state=state, + requirements=requirements, + error_type=error_type, + ) + + if requirements.keys() != state.custom_namespaces: + raise error_type( + "presentation: renderer requirements must exactly match custom " + "component namespaces" + ) + for namespace, requirement in requirements.items(): + if ( + _namespace(cast(str, requirement["extensionIdentifier"])) + != namespace + ): + raise error_type( + "presentation: renderer extension namespace must match its " + "component namespace" + ) + + _validate_assets(message, state.asset_references, error_type) + + +class _PresentationState: + """Track document-wide component and reference budgets.""" + + def __init__(self) -> None: + self.component_count = 0 + self.custom_namespaces: set[str] = set() + self.asset_references: set[str] = set() + + +def _validate_target( + target: dict[str, Any], + *, + target_kind: str, + permitted_surfaces: frozenset[str], + state: _PresentationState, + requirements: dict[str, dict[str, Any]], + error_type: type[ValueError], +) -> None: + surfaces = cast(dict[str, dict[str, Any]], target["surfaces"]) + unsupported = surfaces.keys() - permitted_surfaces + if unsupported: + raise error_type( + f"presentation: surface is not valid for {target_kind} targets" + ) + for surface_identifier, surface in surfaces.items(): + _validate_component( + cast(dict[str, Any], surface["root"]), + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=frozenset(), + depth=1, + core_only=False, + state=state, + requirements=requirements, + error_type=error_type, + ) + + +def _validate_component( + node: dict[str, Any], + *, + surface_identifier: str, + target_kind: str, + scopes: frozenset[str], + depth: int, + core_only: bool, + state: _PresentationState, + requirements: dict[str, dict[str, Any]], + error_type: type[ValueError], +) -> None: + if depth > contract.MAX_PRESENTATION_COMPONENT_DEPTH: + raise error_type("presentation: component depth limit exceeded") + state.component_count += 1 + if state.component_count > contract.MAX_PRESENTATION_COMPONENTS: + raise error_type("presentation: component count limit exceeded") + + core_contract = _validate_component_identity( + node, + core_only=core_only, + state=state, + requirements=requirements, + error_type=error_type, + ) + properties = cast(dict[str, Any], node["properties"]) + if ( + len(rfc8785.dumps(properties)) + > contract.MAX_COMPONENT_PROPERTIES_BYTES + ): + raise error_type("presentation: component properties limit exceeded") + + current_scopes = _extend_repetition_scopes( + node, + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=scopes, + error_type=error_type, + ) + + for binding in cast(dict[str, dict[str, Any]], node["bindings"]).values(): + _validate_binding( + binding, + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=current_scopes, + error_type=error_type, + ) + _validate_optional_condition( + node, + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=current_scopes, + error_type=error_type, + ) + state.asset_references.update( + cast(dict[str, str], node["assetBindings"]).values() + ) + if core_contract is not None: + _validate_core_component_contract( + node, + surface_identifier=surface_identifier, + component_contract=core_contract, + error_type=error_type, + ) + + _validate_optional_fallback( + node, + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=current_scopes, + depth=depth, + state=state, + requirements=requirements, + error_type=error_type, + ) + for child in cast(list[dict[str, Any]], node["children"]): + _validate_component( + child, + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=current_scopes, + depth=depth + 1, + core_only=core_only, + state=state, + requirements=requirements, + error_type=error_type, + ) + + +def _validate_component_identity( + node: dict[str, Any], + *, + core_only: bool, + state: _PresentationState, + requirements: dict[str, dict[str, Any]], + error_type: type[ValueError], +) -> contract.CoreComponentContract | None: + identifier = cast(str, node["componentIdentifier"]) + namespace = _namespace(identifier) + is_core = namespace == contract.CORE_COMPONENT_NAMESPACE + if is_core: + try: + component_contract = contract.CORE_COMPONENT_CONTRACTS[identifier] + except KeyError: + raise error_type( + "presentation: unknown core component identifier" + ) from None + if "fallback" in node: + raise error_type( + "presentation: core component cannot declare a fallback" + ) + return component_contract + if _is_stateforge_owned(namespace): + raise error_type( + "presentation: custom component cannot use a StateForge-owned " + "namespace" + ) + if core_only and not is_core: + raise error_type( + "presentation: custom component fallback must use core components" + ) + if not is_core: + if namespace not in requirements: + raise error_type( + "presentation: custom component has no renderer requirement" + ) + if "fallback" not in node: + raise error_type( + "presentation: custom component requires a core fallback" + ) + state.custom_namespaces.add(namespace) + return None + + +def _validate_core_component_contract( + node: dict[str, Any], + *, + surface_identifier: str, + component_contract: contract.CoreComponentContract, + error_type: type[ValueError], +) -> None: + if surface_identifier not in component_contract.permitted_surfaces: + raise error_type( + "presentation: core component is unavailable on this surface" + ) + + child_count = len(cast(list[dict[str, Any]], node["children"])) + if not ( + component_contract.minimum_children + <= child_count + <= component_contract.maximum_children + ): + raise error_type( + "presentation: core component child contract is violated" + ) + + bindings = cast(dict[str, dict[str, Any]], node["bindings"]) + binding_names = set(bindings) + permitted_bindings = ( + component_contract.required_bindings + | component_contract.optional_bindings + ) + if not component_contract.required_bindings <= binding_names: + raise error_type( + "presentation: core component is missing a required binding" + ) + if not binding_names <= permitted_bindings: + raise error_type( + "presentation: core component binding slot is not permitted" + ) + for slot, permitted_sources in component_contract.binding_source_rules: + binding = bindings.get(slot) + if binding is not None and binding["sourceIdentifier"] not in ( + permitted_sources + ): + raise error_type( + "presentation: binding source is invalid for core " + "component slot" + ) + + asset_bindings = cast(dict[str, str], node["assetBindings"]) + asset_names = set(asset_bindings) + permitted_assets = ( + component_contract.required_assets | component_contract.optional_assets + ) + if not component_contract.required_assets <= asset_names: + raise error_type( + "presentation: core component is missing a required asset" + ) + if not asset_names <= permitted_assets: + raise error_type( + "presentation: core component asset slot is not permitted" + ) + + +def _extend_repetition_scopes( + node: dict[str, Any], + *, + surface_identifier: str, + target_kind: str, + scopes: frozenset[str], + error_type: type[ValueError], +) -> frozenset[str]: + repeat = node.get("repeat") + if not isinstance(repeat, dict): + return scopes + _validate_binding( + cast(dict[str, Any], repeat["collection"]), + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=scopes, + error_type=error_type, + ) + item_scope = cast(str, repeat["itemScope"]) + if item_scope in scopes: + raise error_type("presentation: repetition scopes must be unique") + return scopes | {item_scope} + + +def _validate_optional_condition( + node: dict[str, Any], + *, + surface_identifier: str, + target_kind: str, + scopes: frozenset[str], + error_type: type[ValueError], +) -> None: + condition = node.get("condition") + if isinstance(condition, dict): + _validate_condition( + condition, + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=scopes, + error_type=error_type, + ) + + +def _validate_optional_fallback( + node: dict[str, Any], + *, + surface_identifier: str, + target_kind: str, + scopes: frozenset[str], + depth: int, + state: _PresentationState, + requirements: dict[str, dict[str, Any]], + error_type: type[ValueError], +) -> None: + fallback = node.get("fallback") + if isinstance(fallback, dict): + _validate_component( + fallback, + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=scopes, + depth=depth + 1, + core_only=True, + state=state, + requirements=requirements, + error_type=error_type, + ) + + +def _validate_condition( + condition: dict[str, Any], + *, + surface_identifier: str, + target_kind: str, + scopes: frozenset[str], + error_type: type[ValueError], +) -> None: + _validate_binding( + cast(dict[str, Any], condition["binding"]), + surface_identifier=surface_identifier, + target_kind=target_kind, + scopes=scopes, + error_type=error_type, + ) + operator = cast(str, condition["operator"]) + has_value = "value" in condition + if ( + operator + in { + "CONDITION_OPERATOR_EXISTS", + "CONDITION_OPERATOR_NOT_EXISTS", + } + and has_value + ): + raise error_type( + "presentation: existence condition cannot declare a value" + ) + if ( + operator + in { + "CONDITION_OPERATOR_EQUALS", + "CONDITION_OPERATOR_NOT_EQUALS", + } + and not has_value + ): + raise error_type("presentation: equality condition requires a value") + + +def _validate_binding( + binding: dict[str, Any], + *, + surface_identifier: str, + target_kind: str, + scopes: frozenset[str], + error_type: type[ValueError], +) -> None: + source = cast(str, binding["sourceIdentifier"]) + scope = cast(str, binding["scope"]) + if source == contract.REPETITION_ITEM_BINDING: + if not scope or scope not in scopes: + raise error_type( + "presentation: repetition item binding has no active scope" + ) + return + if scope: + raise error_type( + "presentation: only repetition item bindings may name a scope" + ) + allowed = set(contract.SURFACE_BINDING_SOURCES[surface_identifier]) + if surface_identifier == contract.EVIDENCE_SURFACE: + if target_kind == "operation": + allowed.discard(contract.TRIGGER_PAYLOAD_VALUE_BINDING) + elif target_kind == "trigger": + allowed.discard(contract.OPERATION_EVIDENCE_BINDING) + if source not in allowed: + raise error_type( + "presentation: binding source is unavailable on this surface" + ) + + +def _namespace(identifier: str) -> str: + return identifier.split("/", 1)[0] + + +def _is_stateforge_owned(namespace: str) -> bool: + return ( + namespace == contract.STATEFORGE_NAMESPACE_ROOT + or namespace.startswith(f"{contract.STATEFORGE_NAMESPACE_ROOT}.") + ) + + +def _validate_assets( + message: manifest_pb2.ProviderPresentation, + references: set[str], + error_type: type[ValueError], +) -> None: + assets = message.assets + total_bytes = sum(len(asset.content) for asset in assets.values()) + if total_bytes > contract.MAX_PRESENTATION_ASSET_TOTAL_BYTES: + raise error_type("presentation: aggregate asset limit exceeded") + for digest, asset in assets.items(): + if ( + not asset.content + or len(asset.content) > contract.MAX_PRESENTATION_ASSET_BYTES + ): + raise error_type("presentation: asset byte limit exceeded") + expected = "sha256:" + hashlib.sha256(asset.content).hexdigest() + if digest != expected: + raise error_type("presentation: asset digest mismatch") + _validate_asset_content(asset, error_type) + + if not references <= assets.keys(): + raise error_type("presentation: asset reference is missing") + if assets.keys() - references: + raise error_type("presentation: unreferenced asset is not permitted") + + +def _validate_asset_content( + asset: manifest_pb2.PresentationAsset, + error_type: type[ValueError], +) -> None: + if asset.media_type not in contract.ALLOWED_PRESENTATION_MEDIA_TYPES: + raise error_type("presentation: asset media type is not permitted") + if asset.media_type == "image/svg+xml": + _validate_svg(asset.content, error_type) + return + dimensions = _png_dimensions(asset.content, error_type) + if dimensions != (asset.width, asset.height): + raise error_type("presentation: asset dimensions do not match content") + + +def _validate_svg(content: bytes, error_type: type[ValueError]) -> None: + upper = content.upper() + if b" contract.MAX_SCHEMA_NODES: + raise error_type("presentation: SVG node limit exceeded") + namespace, tag = _split_name(element.tag) + if namespace not in {"", _SVG_NAMESPACE} or tag not in _SAFE_SVG_TAGS: + raise error_type("presentation: unsafe SVG element") + for attribute, value in element.attrib.items(): + attribute_namespace, name = _split_name(attribute) + if attribute_namespace or name not in _SAFE_SVG_ATTRIBUTES: + raise error_type("presentation: unsafe SVG attribute") + lowered = value.lower() + if "javascript:" in lowered or "data:" in lowered: + raise error_type("presentation: unsafe SVG reference") + if "url(" in lowered and not _LOCAL_ASSET_REFERENCE.fullmatch( + value + ): + raise error_type("presentation: unsafe SVG reference") + + +def _split_name(value: str) -> tuple[str, str]: + if value.startswith("{") and "}" in value: + namespace, name = value[1:].split("}", 1) + return namespace, name + return "", value + + +def _local_name(value: str) -> str: + return _split_name(value)[1] + + +def _png_dimensions( + content: bytes, + error_type: type[ValueError], +) -> tuple[int, int]: + """Validate a bounded, static PNG and return its declared dimensions.""" + if not content.startswith(_PNG_SIGNATURE): + _reject_png(error_type) + offset = len(_PNG_SIGNATURE) + dimensions: tuple[int, int] | None = None + bit_depth: int | None = None + color_type: int | None = None + interlace_method: int | None = None + image_data: list[bytes] = [] + saw_image_data = False + while offset + _PNG_CHUNK_OVERHEAD <= len(content): + length = struct.unpack(">I", content[offset : offset + 4])[0] + chunk_type = content[offset + 4 : offset + 8] + data_start = offset + 8 + data_end = data_start + length + chunk_end = data_end + 4 + if chunk_end > len(content) or chunk_type not in _SAFE_PNG_CHUNKS: + _reject_png(error_type) + expected_crc = struct.unpack(">I", content[data_end:chunk_end])[0] + actual_crc = zlib.crc32(chunk_type) + actual_crc = zlib.crc32(content[data_start:data_end], actual_crc) + if expected_crc != actual_crc & 0xFFFFFFFF: + _reject_png(error_type) + if dimensions is None: + ( + dimensions, + bit_depth, + color_type, + interlace_method, + ) = _read_png_header( + chunk_type, + content[data_start:data_end], + error_type, + ) + elif chunk_type == b"IHDR": + _reject_png(error_type) + if chunk_type == b"IDAT": + saw_image_data = True + image_data.append(content[data_start:data_end]) + elif saw_image_data and chunk_type != b"IEND": + _reject_png(error_type) + if chunk_type == b"IEND": + if length or not saw_image_data or chunk_end != len(content): + _reject_png(error_type) + if ( + dimensions is None + or bit_depth is None + or color_type is None + or interlace_method is None + ): + _reject_png(error_type) + _validate_png_image_data( + b"".join(image_data), + width=dimensions[0], + height=dimensions[1], + bit_depth=bit_depth, + color_type=color_type, + interlace_method=interlace_method, + error_type=error_type, + ) + return dimensions + offset = chunk_end + _reject_png(error_type) + + +def _read_png_header( + chunk_type: bytes, + data: bytes, + error_type: type[ValueError], +) -> tuple[tuple[int, int], int, int, int]: + if chunk_type != b"IHDR" or len(data) != _PNG_IHDR_BYTES: + _reject_png(error_type) + width, height = struct.unpack(">II", data[:8]) + bit_depth = data[8] + color_type = data[9] + interlace_method = data[12] + valid_depths = { + 0: {1, 2, 4, 8, 16}, + 2: {8, 16}, + 3: {1, 2, 4, 8}, + 4: {8, 16}, + 6: {8, 16}, + } + if ( + not width + or not height + or width > contract.MAX_PRESENTATION_ASSET_DIMENSION + or height > contract.MAX_PRESENTATION_ASSET_DIMENSION + or bit_depth not in valid_depths.get(color_type, set()) + or data[10:12] != b"\x00\x00" + or interlace_method not in {0, 1} + ): + _reject_png(error_type) + return (width, height), bit_depth, color_type, interlace_method + + +def _validate_png_image_data( + compressed: bytes, + *, + width: int, + height: int, + bit_depth: int, + color_type: int, + interlace_method: int, + error_type: type[ValueError], +) -> None: + """Decode bounded IDAT data and validate its complete scanline framing.""" + scanline_lengths = _png_scanline_lengths( + width, + height, + bit_depth, + color_type, + interlace_method, + ) + decoded_bytes = sum(length + 1 for length in scanline_lengths) + if decoded_bytes > contract.MAX_PRESENTATION_PNG_DECODED_BYTES: + _reject_png(error_type) + + decoder = zlib.decompressobj() + pending = compressed + row_index = 0 + row_remaining = 0 + try: + while True: + pending_bytes = len(pending) + decoded = decoder.decompress(pending, _PNG_DECODE_CHUNK_BYTES) + pending = decoder.unconsumed_tail + row_index, row_remaining = _consume_png_scanlines( + decoded, + scanline_lengths=scanline_lengths, + row_index=row_index, + row_remaining=row_remaining, + error_type=error_type, + ) + if decoder.eof: + if pending or decoder.unused_data: + _reject_png(error_type) + break + if (not pending and not decoded) or ( + not decoded and len(pending) == pending_bytes + ): + _reject_png(error_type) + except zlib.error: + _reject_png(error_type) + + if row_index != len(scanline_lengths) or row_remaining: + _reject_png(error_type) + + +def _consume_png_scanlines( + decoded: bytes, + *, + scanline_lengths: tuple[int, ...], + row_index: int, + row_remaining: int, + error_type: type[ValueError], +) -> tuple[int, int]: + for value in decoded: + if not row_remaining: + if ( + row_index >= len(scanline_lengths) + or value > _PNG_MAX_FILTER_TYPE + ): + _reject_png(error_type) + row_remaining = scanline_lengths[row_index] + row_index += 1 + else: + row_remaining -= 1 + return row_index, row_remaining + + +def _png_scanline_lengths( + width: int, + height: int, + bit_depth: int, + color_type: int, + interlace_method: int, +) -> tuple[int, ...]: + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[color_type] + bits_per_pixel = channels * bit_depth + if not interlace_method: + row_bytes = (width * bits_per_pixel + 7) // 8 + return (row_bytes,) * height + + passes = ( + (0, 0, 8, 8), + (4, 0, 8, 8), + (0, 4, 4, 8), + (2, 0, 4, 4), + (0, 2, 2, 4), + (1, 0, 2, 2), + (0, 1, 1, 2), + ) + rows: list[int] = [] + for x_start, y_start, x_step, y_step in passes: + if width <= x_start or height <= y_start: + continue + pass_width = (width - x_start + x_step - 1) // x_step + pass_height = (height - y_start + y_step - 1) // y_step + row_bytes = (pass_width * bits_per_pixel + 7) // 8 + rows.extend((row_bytes,) * pass_height) + return tuple(rows) + + +def _reject_png(error_type: type[ValueError]) -> Never: + raise error_type("presentation: invalid PNG content") diff --git a/src/stateforge_protocol/sfp/manifest/v1/contract.py b/src/stateforge_protocol/sfp/manifest/v1/contract.py index e174950..ccf9a67 100644 --- a/src/stateforge_protocol/sfp/manifest/v1/contract.py +++ b/src/stateforge_protocol/sfp/manifest/v1/contract.py @@ -1,5 +1,6 @@ """Expose the normative SFP Provider Manifest v1 wire contract.""" +from dataclasses import dataclass from typing import Final from stateforge_protocol.sfp import primitives @@ -16,6 +17,7 @@ # Canonicalization and embedded JSON limits enforced outside JSON Schema. MAX_CANONICAL_REVISION_PREIMAGE_BYTES: Final = 1 * 1024 * 1024 +MAX_PRESENTATION_REVISION_PREIMAGE_BYTES: Final = 2 * 1024 * 1024 MAX_EMBEDDED_JSON_DEPTH: Final = 64 MAX_JSON_NODES: Final = 100_000 MAX_SCHEMA_NODES: Final = 25_000 @@ -33,3 +35,282 @@ MAX_RUNTIME_REQUIREMENTS: Final = 1_024 MAX_PLATFORMS: Final = 256 MAX_PROFILE_CLAIMS_PER_OPERATION: Final = 64 + +# Optional presentation-tree limits mirrored by the packaged schema. +PRESENTATION_SCHEMA_VERSION: Final = 1 +MAX_PRESENTATION_OPERATIONS: Final = MAX_OPERATIONS +MAX_PRESENTATION_TRIGGERS: Final = MAX_TRIGGERS +MAX_PRESENTATION_SURFACES_PER_TARGET: Final = 8 +MAX_PRESENTATION_COMPONENTS: Final = 4_096 +MAX_PRESENTATION_COMPONENT_DEPTH: Final = 16 +MAX_COMPONENT_CHILDREN: Final = 256 +MAX_COMPONENT_BINDINGS: Final = 64 +MAX_COMPONENT_ASSET_BINDINGS: Final = 32 +MAX_COMPONENT_PROPERTIES_BYTES: Final = 64 * 1024 +MAX_RENDERER_REQUIREMENTS: Final = 64 +MAX_RENDERER_PERMISSIONS: Final = 32 +MAX_REPETITION_ITEMS: Final = 1_024 +MAX_PRESENTATION_ASSETS: Final = 64 +MAX_PRESENTATION_ASSET_BYTES: Final = 256 * 1024 +MAX_PRESENTATION_ASSET_TOTAL_BYTES: Final = 1 * 1024 * 1024 +MAX_PRESENTATION_ASSET_DIMENSION: Final = 8_192 +MAX_PRESENTATION_PNG_DECODED_BYTES: Final = 64 * 1024 * 1024 +MAX_PRESENTATION_POINTER_CODE_POINTS: Final = 2_048 +MAX_PRESENTATION_SCOPE_CODE_POINTS: Final = 64 + +STATEFORGE_NAMESPACE_ROOT: Final = "stateforge" +CORE_COMPONENT_NAMESPACE: Final = "stateforge.ui" + +PROVIDER_OVERVIEW_SURFACE: Final = "stateforge.ui/surface.provider.overview@1" +OPERATION_REQUEST_SURFACE: Final = "stateforge.ui/surface.operation.request@1" +OPERATION_RUN_SURFACE: Final = "stateforge.ui/surface.operation.run@1" +OPERATION_RESULT_SURFACE: Final = "stateforge.ui/surface.operation.result@1" +TRIGGER_POLICY_SURFACE: Final = "stateforge.ui/surface.trigger.policy@1" +TRIGGER_EVENT_SURFACE: Final = "stateforge.ui/surface.trigger.event@1" +EVIDENCE_SURFACE: Final = "stateforge.ui/surface.evidence@1" + +PROVIDER_SURFACES: Final = frozenset({PROVIDER_OVERVIEW_SURFACE}) +OPERATION_SURFACES: Final = frozenset( + { + OPERATION_REQUEST_SURFACE, + OPERATION_RUN_SURFACE, + OPERATION_RESULT_SURFACE, + EVIDENCE_SURFACE, + } +) +TRIGGER_SURFACES: Final = frozenset( + { + TRIGGER_POLICY_SURFACE, + TRIGGER_EVENT_SURFACE, + EVIDENCE_SURFACE, + } +) +ALL_PRESENTATION_SURFACES: Final = ( + PROVIDER_SURFACES | OPERATION_SURFACES | TRIGGER_SURFACES +) +INPUT_PRESENTATION_SURFACES: Final = frozenset( + {OPERATION_REQUEST_SURFACE, TRIGGER_POLICY_SURFACE} +) + +PROVIDER_MANIFEST_BINDING: Final = "stateforge.binding/provider.manifest@1" +PROVIDER_RUNTIME_BINDING: Final = "stateforge.binding/provider.runtime@1" +OPERATION_REQUEST_SCHEMA_BINDING: Final = ( + "stateforge.binding/operation.request.schema@1" +) +# Presentation-safe projection only. The data-source owner must recursively +# omit every value whose applicable input schema marks it writeOnly. Secret +# form state is never exposed through a presentation binding. +OPERATION_REQUEST_PUBLIC_VALUE_BINDING: Final = ( + "stateforge.binding/operation.request.public_value@1" +) +OPERATION_RUN_BINDING: Final = "stateforge.binding/operation.run@1" +OPERATION_RESULT_SCHEMA_BINDING: Final = ( + "stateforge.binding/operation.result.schema@1" +) +OPERATION_RESULT_VALUE_BINDING: Final = ( + "stateforge.binding/operation.result.value@1" +) +OPERATION_EVIDENCE_BINDING: Final = "stateforge.binding/operation.evidence@1" +TRIGGER_PAYLOAD_SCHEMA_BINDING: Final = ( + "stateforge.binding/trigger.payload.schema@1" +) +TRIGGER_PAYLOAD_VALUE_BINDING: Final = ( + "stateforge.binding/trigger.payload.value@1" +) +AUDIT_BINDING: Final = "stateforge.binding/audit@1" +REPETITION_ITEM_BINDING: Final = "stateforge.binding/repetition.item@1" + +SURFACE_BINDING_SOURCES: Final = { + PROVIDER_OVERVIEW_SURFACE: frozenset( + {PROVIDER_MANIFEST_BINDING, PROVIDER_RUNTIME_BINDING} + ), + OPERATION_REQUEST_SURFACE: frozenset( + { + PROVIDER_MANIFEST_BINDING, + OPERATION_REQUEST_SCHEMA_BINDING, + OPERATION_REQUEST_PUBLIC_VALUE_BINDING, + } + ), + OPERATION_RUN_SURFACE: frozenset( + { + PROVIDER_MANIFEST_BINDING, + OPERATION_REQUEST_PUBLIC_VALUE_BINDING, + OPERATION_RUN_BINDING, + } + ), + OPERATION_RESULT_SURFACE: frozenset( + { + PROVIDER_MANIFEST_BINDING, + OPERATION_REQUEST_PUBLIC_VALUE_BINDING, + OPERATION_RESULT_SCHEMA_BINDING, + OPERATION_RESULT_VALUE_BINDING, + OPERATION_EVIDENCE_BINDING, + } + ), + TRIGGER_POLICY_SURFACE: frozenset( + {PROVIDER_MANIFEST_BINDING, TRIGGER_PAYLOAD_SCHEMA_BINDING} + ), + TRIGGER_EVENT_SURFACE: frozenset( + { + PROVIDER_MANIFEST_BINDING, + TRIGGER_PAYLOAD_SCHEMA_BINDING, + TRIGGER_PAYLOAD_VALUE_BINDING, + } + ), + EVIDENCE_SURFACE: frozenset( + { + PROVIDER_MANIFEST_BINDING, + OPERATION_EVIDENCE_BINDING, + TRIGGER_PAYLOAD_VALUE_BINDING, + AUDIT_BINDING, + } + ), +} + + +@dataclass(frozen=True, slots=True) +class CoreComponentContract: + """Define Protocol-owned structure for one portable core component.""" + + permitted_surfaces: frozenset[str] + minimum_children: int = 0 + maximum_children: int = 0 + required_bindings: frozenset[str] = frozenset() + optional_bindings: frozenset[str] = frozenset() + binding_source_rules: tuple[tuple[str, frozenset[str]], ...] = () + required_assets: frozenset[str] = frozenset() + optional_assets: frozenset[str] = frozenset() + + +_LAYOUT_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + minimum_children=1, + maximum_children=MAX_COMPONENT_CHILDREN, +) +_INPUT_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=INPUT_PRESENTATION_SURFACES, + required_bindings=frozenset({"schema"}), + optional_bindings=frozenset({"value"}), + binding_source_rules=( + ( + "schema", + frozenset( + { + OPERATION_REQUEST_SCHEMA_BINDING, + TRIGGER_PAYLOAD_SCHEMA_BINDING, + } + ), + ), + ("value", frozenset({OPERATION_REQUEST_PUBLIC_VALUE_BINDING})), + ), +) +_INPUT_CONTAINER_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=INPUT_PRESENTATION_SURFACES, + maximum_children=MAX_COMPONENT_CHILDREN, + required_bindings=_INPUT_COMPONENT.required_bindings, + optional_bindings=_INPUT_COMPONENT.optional_bindings, + binding_source_rules=_INPUT_COMPONENT.binding_source_rules, +) +_SECRET_INPUT_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=INPUT_PRESENTATION_SURFACES, + required_bindings=frozenset({"schema"}), + binding_source_rules=( + ( + "schema", + frozenset( + { + OPERATION_REQUEST_SCHEMA_BINDING, + TRIGGER_PAYLOAD_SCHEMA_BINDING, + } + ), + ), + ), +) +_STATIC_CONTENT_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + optional_bindings=frozenset({"value"}), +) +_BOUND_VALUE_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_bindings=frozenset({"value"}), +) +_TABLE_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_bindings=frozenset({"rows"}), +) +_DIFF_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_bindings=frozenset({"before", "after"}), +) +_LOG_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_bindings=frozenset({"entries"}), +) +_TIMELINE_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_bindings=frozenset({"events"}), +) +_CHART_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_bindings=frozenset({"series"}), +) +_TOPOLOGY_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_bindings=frozenset({"nodes", "edges"}), +) +_ARTIFACTS_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_bindings=frozenset({"items"}), +) +_IMAGE_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=ALL_PRESENTATION_SURFACES, + required_assets=frozenset({"source"}), +) +_SUBMIT_ACTION_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=frozenset({OPERATION_REQUEST_SURFACE}), +) +_CANCEL_ACTION_COMPONENT: Final = CoreComponentContract( + permitted_surfaces=frozenset({OPERATION_RUN_SURFACE}), +) + +CORE_COMPONENT_CONTRACTS: Final = { + "stateforge.ui/layout.stack@1": _LAYOUT_COMPONENT, + "stateforge.ui/layout.grid@1": _LAYOUT_COMPONENT, + "stateforge.ui/layout.section@1": _LAYOUT_COMPONENT, + "stateforge.ui/layout.tabs@1": _LAYOUT_COMPONENT, + "stateforge.ui/layout.steps@1": _LAYOUT_COMPONENT, + "stateforge.ui/input.form@1": _INPUT_CONTAINER_COMPONENT, + "stateforge.ui/input.field@1": _INPUT_COMPONENT, + "stateforge.ui/input.object@1": _INPUT_CONTAINER_COMPONENT, + "stateforge.ui/input.array@1": _INPUT_CONTAINER_COMPONENT, + "stateforge.ui/input.key_value@1": _INPUT_COMPONENT, + "stateforge.ui/input.code@1": _INPUT_COMPONENT, + "stateforge.ui/input.secret@1": _SECRET_INPUT_COMPONENT, + "stateforge.ui/content.text@1": _STATIC_CONTENT_COMPONENT, + "stateforge.ui/content.markdown@1": _STATIC_CONTENT_COMPONENT, + "stateforge.ui/data.key_value@1": _BOUND_VALUE_COMPONENT, + "stateforge.ui/data.table@1": _TABLE_COMPONENT, + "stateforge.ui/data.tree@1": _BOUND_VALUE_COMPONENT, + "stateforge.ui/data.code@1": _BOUND_VALUE_COMPONENT, + "stateforge.ui/data.diff@1": _DIFF_COMPONENT, + "stateforge.ui/data.log@1": _LOG_COMPONENT, + "stateforge.ui/status.badge@1": _BOUND_VALUE_COMPONENT, + "stateforge.ui/status.progress@1": _BOUND_VALUE_COMPONENT, + "stateforge.ui/status.timeline@1": _TIMELINE_COMPONENT, + "stateforge.ui/data.metric@1": _BOUND_VALUE_COMPONENT, + "stateforge.ui/data.chart@1": _CHART_COMPONENT, + "stateforge.ui/data.topology@1": _TOPOLOGY_COMPONENT, + "stateforge.ui/data.artifacts@1": _ARTIFACTS_COMPONENT, + "stateforge.ui/media.image@1": _IMAGE_COMPONENT, + "stateforge.ui/action.operation_submit@1": _SUBMIT_ACTION_COMPONENT, + "stateforge.ui/action.operation_cancel@1": _CANCEL_ACTION_COMPONENT, +} + +CORE_COMPONENT_IDENTIFIERS: Final = frozenset(CORE_COMPONENT_CONTRACTS) + +ALLOWED_PRESENTATION_MEDIA_TYPES: Final = frozenset( + { + "image/png", + "image/svg+xml", + } +) diff --git a/src/stateforge_protocol/sfp/manifest/v1/manifest.schema.json b/src/stateforge_protocol/sfp/manifest/v1/manifest.schema.json index 3d92170..db488f1 100644 --- a/src/stateforge_protocol/sfp/manifest/v1/manifest.schema.json +++ b/src/stateforge_protocol/sfp/manifest/v1/manifest.schema.json @@ -242,7 +242,7 @@ }, "versionConstraint": { "type": "string", - "minLength": 0, + "minItems": 0, "maxLength": 255 } }, @@ -286,6 +286,325 @@ ], "additionalProperties": false }, + "jsonPointer": { + "type": "string", + "minLength": 1, + "maxLength": 2048, + "pattern": "^(/([^~/]|~0|~1)*)+$(?![\\s\\S])" + }, + "bindingPointer": { + "oneOf": [ + { + "const": "" + }, + { + "$ref": "#/$defs/jsonPointer" + } + ] + }, + "presentationScope": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^[a-z][a-z0-9_]*(?![\\s\\S])" + }, + "dataBinding": { + "type": "object", + "properties": { + "sourceIdentifier": { + "$ref": "#/$defs/identifier" + }, + "pointer": { + "$ref": "#/$defs/bindingPointer" + }, + "scope": { + "oneOf": [ + { + "const": "" + }, + { + "$ref": "#/$defs/presentationScope" + } + ] + } + }, + "required": [ + "sourceIdentifier", + "pointer", + "scope" + ], + "additionalProperties": false + }, + "condition": { + "type": "object", + "properties": { + "binding": { + "$ref": "#/$defs/dataBinding" + }, + "operator": { + "enum": [ + "CONDITION_OPERATOR_EXISTS", + "CONDITION_OPERATOR_NOT_EXISTS", + "CONDITION_OPERATOR_EQUALS", + "CONDITION_OPERATOR_NOT_EQUALS" + ] + }, + "value": true + }, + "required": [ + "binding", + "operator" + ], + "additionalProperties": false + }, + "repetition": { + "type": "object", + "properties": { + "collection": { + "$ref": "#/$defs/dataBinding" + }, + "itemScope": { + "$ref": "#/$defs/presentationScope" + }, + "maxItems": { + "type": "integer", + "minimum": 1, + "maximum": 1024 + } + }, + "required": [ + "collection", + "itemScope", + "maxItems" + ], + "additionalProperties": false + }, + "componentNode": { + "type": "object", + "properties": { + "componentIdentifier": { + "$ref": "#/$defs/identifier" + }, + "properties": { + "type": "object" + }, + "bindings": { + "type": "object", + "propertyNames": { + "$ref": "#/$defs/presentationScope" + }, + "additionalProperties": { + "$ref": "#/$defs/dataBinding" + }, + "minProperties": 0, + "maxProperties": 64 + }, + "children": { + "type": "array", + "items": { + "$ref": "#/$defs/componentNode" + }, + "minLength": 0, + "maxItems": 256 + }, + "fallback": { + "$ref": "#/$defs/componentNode" + }, + "condition": { + "$ref": "#/$defs/condition" + }, + "repeat": { + "$ref": "#/$defs/repetition" + }, + "assetBindings": { + "type": "object", + "propertyNames": { + "$ref": "#/$defs/presentationScope" + }, + "additionalProperties": { + "$ref": "#/$defs/revision" + }, + "minProperties": 0, + "maxProperties": 32 + } + }, + "required": [ + "componentIdentifier", + "properties", + "bindings", + "children", + "assetBindings" + ], + "additionalProperties": false + }, + "presentationSurface": { + "type": "object", + "properties": { + "root": { + "$ref": "#/$defs/componentNode" + } + }, + "required": [ + "root" + ], + "additionalProperties": false + }, + "presentationTarget": { + "type": "object", + "properties": { + "surfaces": { + "type": "object", + "propertyNames": { + "$ref": "#/$defs/identifier" + }, + "additionalProperties": { + "$ref": "#/$defs/presentationSurface" + }, + "minProperties": 1, + "maxProperties": 8 + } + }, + "required": [ + "surfaces" + ], + "additionalProperties": false + }, + "rendererRequirement": { + "type": "object", + "properties": { + "extensionIdentifier": { + "$ref": "#/$defs/identifier" + }, + "extensionVersion": { + "$ref": "#/$defs/semver" + }, + "rendererApiVersion": { + "$ref": "#/$defs/semver" + }, + "artifactDigest": { + "$ref": "#/$defs/revision" + }, + "permissions": { + "type": "array", + "items": { + "$ref": "#/$defs/identifier" + }, + "minItems": 0, + "maxItems": 32, + "uniqueItems": true + } + }, + "required": [ + "extensionIdentifier", + "extensionVersion", + "rendererApiVersion", + "artifactDigest", + "permissions" + ], + "additionalProperties": false + }, + "presentationAsset": { + "type": "object", + "properties": { + "mediaType": { + "enum": [ + "image/png", + "image/svg+xml" + ] + }, + "content": { + "type": "string", + "minLength": 4, + "pattern": "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$(?![\\s\\S])" + }, + "width": { + "type": "integer", + "minimum": 1, + "maximum": 8192 + }, + "height": { + "type": "integer", + "minimum": 1, + "maximum": 8192 + }, + "altText": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } + }, + "required": [ + "mediaType", + "content", + "width", + "height", + "altText" + ], + "additionalProperties": false + }, + "providerPresentation": { + "type": "object", + "properties": { + "presentationSchemaVersion": { + "const": 1 + }, + "provider": { + "$ref": "#/$defs/presentationTarget" + }, + "operations": { + "type": "object", + "propertyNames": { + "$ref": "#/$defs/identifier" + }, + "additionalProperties": { + "$ref": "#/$defs/presentationTarget" + }, + "minProperties": 0, + "maxProperties": 1024 + }, + "triggers": { + "type": "object", + "propertyNames": { + "$ref": "#/$defs/identifier" + }, + "additionalProperties": { + "$ref": "#/$defs/presentationTarget" + }, + "minProperties": 0, + "maxProperties": 1024 + }, + "assets": { + "type": "object", + "propertyNames": { + "$ref": "#/$defs/revision" + }, + "additionalProperties": { + "$ref": "#/$defs/presentationAsset" + }, + "minProperties": 0, + "maxProperties": 64 + }, + "rendererRequirements": { + "type": "object", + "propertyNames": { + "$ref": "#/$defs/dottedIdentifier" + }, + "additionalProperties": { + "$ref": "#/$defs/rendererRequirement" + }, + "minProperties": 0, + "maxProperties": 64 + } + }, + "required": [ + "presentationSchemaVersion", + "operations", + "triggers", + "assets", + "rendererRequirements" + ], + "additionalProperties": false + }, "providerManifest": { "type": "object", "properties": { @@ -410,6 +729,23 @@ }, "sessionId": { "$ref": "#/$defs/sessionId" + }, + "presentation": { + "type": "object", + "required": [ + "presentationSchemaVersion" + ], + "properties": { + "presentationSchemaVersion": { + "type": "integer", + "minimum": 1, + "maximum": 4294967295 + } + }, + "additionalProperties": true + }, + "presentationRevision": { + "$ref": "#/$defs/revision" } }, "required": [ @@ -418,9 +754,35 @@ "manifestSchemaVersion", "manifestRevision", "manifest", - "sessionId" + "sessionId" ], - "additionalProperties": false + "additionalProperties": false, + "allOf": [ + { + "if": { + "required": [ + "presentation" + ] + }, + "then": { + "required": [ + "presentationRevision" + ], + "properties": { + "presentationRevision": { + "$ref": "#/$defs/revision" + } + } + }, + "else": { + "not": { + "required": [ + "presentationRevision" + ] + } + } + } + ] }, "sessionId": { "type": "string", diff --git a/src/stateforge_protocol/sfp/manifest/v1/manifest_pb2.py b/src/stateforge_protocol/sfp/manifest/v1/manifest_pb2.py index 8a02ecb..5949287 100644 --- a/src/stateforge_protocol/sfp/manifest/v1/manifest_pb2.py +++ b/src/stateforge_protocol/sfp/manifest/v1/manifest_pb2.py @@ -25,7 +25,7 @@ from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n2stateforge_protocol/sfp/manifest/v1/manifest.proto\x12\x1astateforge.sfp.manifest.v1\x1a\x1cgoogle/protobuf/struct.proto\"\x96\x02\n\x12GetManifestRequest\x12\x41\n\x1d\x65xpected_provider_instance_id\x18\x01 \x01(\tR\x1a\x65xpectedProviderInstanceId\x12@\n\x1c\x65xpected_endpoint_generation\x18\x02 \x01(\x04R\x1a\x65xpectedEndpointGeneration\x12K\n\"supported_manifest_schema_versions\x18\x03 \x03(\rR\x1fsupportedManifestSchemaVersions\x12.\n\x13\x65xpected_session_id\x18\x04 \x01(\tR\x11\x65xpectedSessionId\"\xc6\x02\n\x13GetManifestResponse\x12\x30\n\x14provider_instance_id\x18\x01 \x01(\tR\x12providerInstanceId\x12/\n\x13\x65ndpoint_generation\x18\x02 \x01(\x04R\x12\x65ndpointGeneration\x12\x36\n\x17manifest_schema_version\x18\x03 \x01(\rR\x15manifestSchemaVersion\x12+\n\x11manifest_revision\x18\x04 \x01(\tR\x10manifestRevision\x12H\n\x08manifest\x18\x05 \x01(\x0b\x32,.stateforge.sfp.manifest.v1.ProviderManifestR\x08manifest\x12\x1d\n\nsession_id\x18\x06 \x01(\tR\tsessionId\"\xbc\x07\n\x10ProviderManifest\x12+\n\x11provider_identity\x18\x01 \x01(\tR\x10providerIdentity\x12\x35\n\x16implementation_version\x18\x02 \x01(\tR\x15implementationVersion\x12!\n\x0c\x64isplay_name\x18\x03 \x01(\tR\x0b\x64isplayName\x12\\\n\noperations\x18\x04 \x03(\x0b\x32<.stateforge.sfp.manifest.v1.ProviderManifest.OperationsEntryR\noperations\x12x\n\x14runtime_requirements\x18\x06 \x03(\x0b\x32\x45.stateforge.sfp.manifest.v1.ProviderManifest.RuntimeRequirementsEntryR\x13runtimeRequirements\x12O\n\tplatforms\x18\x07 \x03(\x0b\x32\x31.stateforge.sfp.manifest.v1.PlatformCompatibilityR\tplatforms\x12J\n\x14\x63onfiguration_schema\x18\x08 \x01(\x0b\x32\x17.google.protobuf.StructR\x13\x63onfigurationSchema\x12V\n\x08triggers\x18\t \x03(\x0b\x32:.stateforge.sfp.manifest.v1.ProviderManifest.TriggersEntryR\x08triggers\x1ao\n\x0fOperationsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x46\n\x05value\x18\x02 \x01(\x0b\x32\x30.stateforge.sfp.manifest.v1.OperationDeclarationR\x05value:\x02\x38\x01\x1av\n\x18RuntimeRequirementsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x44\n\x05value\x18\x02 \x01(\x0b\x32..stateforge.sfp.manifest.v1.RuntimeRequirementR\x05value:\x02\x38\x01\x1ak\n\rTriggersEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x44\n\x05value\x18\x02 \x01(\x0b\x32..stateforge.sfp.manifest.v1.TriggerDeclarationR\x05value:\x02\x38\x01\"\xb0\x01\n\x14OperationDeclaration\x12:\n\x0cinput_schema\x18\x01 \x01(\x0b\x32\x17.google.protobuf.StructR\x0binputSchema\x12<\n\rresult_schema\x18\x02 \x01(\x0b\x32\x17.google.protobuf.StructR\x0cresultSchema\x12\x1e\n\nimplements\x18\x03 \x03(\tR\nimplements\"e\n\x12RuntimeRequirement\x12 \n\x0b\x64\x65scription\x18\x01 \x01(\tR\x0b\x64\x65scription\x12-\n\x12version_constraint\x18\x02 \x01(\tR\x11versionConstraint\"f\n\x15PlatformCompatibility\x12)\n\x10operating_system\x18\x01 \x01(\tR\x0foperatingSystem\x12\"\n\x0c\x61rchitecture\x18\x02 \x01(\tR\x0c\x61rchitecture\"T\n\x12TriggerDeclaration\x12>\n\x0epayload_schema\x18\x01 \x01(\x0b\x32\x17.google.protobuf.StructR\rpayloadSchema2\x81\x01\n\x0fManifestService\x12n\n\x0bGetManifest\x12..stateforge.sfp.manifest.v1.GetManifestRequest\x1a/.stateforge.sfp.manifest.v1.GetManifestResponseb\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n2stateforge_protocol/sfp/manifest/v1/manifest.proto\x12\x1astateforge.sfp.manifest.v1\x1a\x1cgoogle/protobuf/struct.proto\"\x96\x02\n\x12GetManifestRequest\x12\x41\n\x1d\x65xpected_provider_instance_id\x18\x01 \x01(\tR\x1a\x65xpectedProviderInstanceId\x12@\n\x1c\x65xpected_endpoint_generation\x18\x02 \x01(\x04R\x1a\x65xpectedEndpointGeneration\x12K\n\"supported_manifest_schema_versions\x18\x03 \x03(\rR\x1fsupportedManifestSchemaVersions\x12.\n\x13\x65xpected_session_id\x18\x04 \x01(\tR\x11\x65xpectedSessionId\"\xf0\x03\n\x13GetManifestResponse\x12\x30\n\x14provider_instance_id\x18\x01 \x01(\tR\x12providerInstanceId\x12/\n\x13\x65ndpoint_generation\x18\x02 \x01(\x04R\x12\x65ndpointGeneration\x12\x36\n\x17manifest_schema_version\x18\x03 \x01(\rR\x15manifestSchemaVersion\x12+\n\x11manifest_revision\x18\x04 \x01(\tR\x10manifestRevision\x12H\n\x08manifest\x18\x05 \x01(\x0b\x32,.stateforge.sfp.manifest.v1.ProviderManifestR\x08manifest\x12\x1d\n\nsession_id\x18\x06 \x01(\tR\tsessionId\x12T\n\x0cpresentation\x18\x07 \x01(\x0b\x32\x30.stateforge.sfp.manifest.v1.ProviderPresentationR\x0cpresentation\x12\x38\n\x15presentation_revision\x18\x08 \x01(\tH\x00R\x14presentationRevision\x88\x01\x01\x42\x18\n\x16_presentation_revision\"\xbc\x07\n\x10ProviderManifest\x12+\n\x11provider_identity\x18\x01 \x01(\tR\x10providerIdentity\x12\x35\n\x16implementation_version\x18\x02 \x01(\tR\x15implementationVersion\x12!\n\x0c\x64isplay_name\x18\x03 \x01(\tR\x0b\x64isplayName\x12\\\n\noperations\x18\x04 \x03(\x0b\x32<.stateforge.sfp.manifest.v1.ProviderManifest.OperationsEntryR\noperations\x12x\n\x14runtime_requirements\x18\x06 \x03(\x0b\x32\x45.stateforge.sfp.manifest.v1.ProviderManifest.RuntimeRequirementsEntryR\x13runtimeRequirements\x12O\n\tplatforms\x18\x07 \x03(\x0b\x32\x31.stateforge.sfp.manifest.v1.PlatformCompatibilityR\tplatforms\x12J\n\x14\x63onfiguration_schema\x18\x08 \x01(\x0b\x32\x17.google.protobuf.StructR\x13\x63onfigurationSchema\x12V\n\x08triggers\x18\t \x03(\x0b\x32:.stateforge.sfp.manifest.v1.ProviderManifest.TriggersEntryR\x08triggers\x1ao\n\x0fOperationsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x46\n\x05value\x18\x02 \x01(\x0b\x32\x30.stateforge.sfp.manifest.v1.OperationDeclarationR\x05value:\x02\x38\x01\x1av\n\x18RuntimeRequirementsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x44\n\x05value\x18\x02 \x01(\x0b\x32..stateforge.sfp.manifest.v1.RuntimeRequirementR\x05value:\x02\x38\x01\x1ak\n\rTriggersEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x44\n\x05value\x18\x02 \x01(\x0b\x32..stateforge.sfp.manifest.v1.TriggerDeclarationR\x05value:\x02\x38\x01\"\xb0\x01\n\x14OperationDeclaration\x12:\n\x0cinput_schema\x18\x01 \x01(\x0b\x32\x17.google.protobuf.StructR\x0binputSchema\x12<\n\rresult_schema\x18\x02 \x01(\x0b\x32\x17.google.protobuf.StructR\x0cresultSchema\x12\x1e\n\nimplements\x18\x03 \x03(\tR\nimplements\"e\n\x12RuntimeRequirement\x12 \n\x0b\x64\x65scription\x18\x01 \x01(\tR\x0b\x64\x65scription\x12-\n\x12version_constraint\x18\x02 \x01(\tR\x11versionConstraint\"f\n\x15PlatformCompatibility\x12)\n\x10operating_system\x18\x01 \x01(\tR\x0foperatingSystem\x12\"\n\x0c\x61rchitecture\x18\x02 \x01(\tR\x0c\x61rchitecture\"T\n\x12TriggerDeclaration\x12>\n\x0epayload_schema\x18\x01 \x01(\x0b\x32\x17.google.protobuf.StructR\rpayloadSchema\"\xf7\x07\n\x14ProviderPresentation\x12>\n\x1bpresentation_schema_version\x18\x01 \x01(\rR\x19presentationSchemaVersion\x12J\n\x08provider\x18\x02 \x01(\x0b\x32..stateforge.sfp.manifest.v1.PresentationTargetR\x08provider\x12`\n\noperations\x18\x03 \x03(\x0b\x32@.stateforge.sfp.manifest.v1.ProviderPresentation.OperationsEntryR\noperations\x12Z\n\x08triggers\x18\x04 \x03(\x0b\x32>.stateforge.sfp.manifest.v1.ProviderPresentation.TriggersEntryR\x08triggers\x12T\n\x06\x61ssets\x18\x05 \x03(\x0b\x32<.stateforge.sfp.manifest.v1.ProviderPresentation.AssetsEntryR\x06\x61ssets\x12\x7f\n\x15renderer_requirements\x18\x06 \x03(\x0b\x32J.stateforge.sfp.manifest.v1.ProviderPresentation.RendererRequirementsEntryR\x14rendererRequirements\x1am\n\x0fOperationsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x44\n\x05value\x18\x02 \x01(\x0b\x32..stateforge.sfp.manifest.v1.PresentationTargetR\x05value:\x02\x38\x01\x1ak\n\rTriggersEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x44\n\x05value\x18\x02 \x01(\x0b\x32..stateforge.sfp.manifest.v1.PresentationTargetR\x05value:\x02\x38\x01\x1ah\n\x0b\x41ssetsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x43\n\x05value\x18\x02 \x01(\x0b\x32-.stateforge.sfp.manifest.v1.PresentationAssetR\x05value:\x02\x38\x01\x1ax\n\x19RendererRequirementsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x45\n\x05value\x18\x02 \x01(\x0b\x32/.stateforge.sfp.manifest.v1.RendererRequirementR\x05value:\x02\x38\x01\"\xdc\x01\n\x12PresentationTarget\x12X\n\x08surfaces\x18\x01 \x03(\x0b\x32<.stateforge.sfp.manifest.v1.PresentationTarget.SurfacesEntryR\x08surfaces\x1al\n\rSurfacesEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x45\n\x05value\x18\x02 \x01(\x0b\x32/.stateforge.sfp.manifest.v1.PresentationSurfaceR\x05value:\x02\x38\x01\"T\n\x13PresentationSurface\x12=\n\x04root\x18\x01 \x01(\x0b\x32).stateforge.sfp.manifest.v1.ComponentNodeR\x04root\"\xf0\x05\n\rComponentNode\x12\x31\n\x14\x63omponent_identifier\x18\x01 \x01(\tR\x13\x63omponentIdentifier\x12\x37\n\nproperties\x18\x02 \x01(\x0b\x32\x17.google.protobuf.StructR\nproperties\x12S\n\x08\x62indings\x18\x03 \x03(\x0b\x32\x37.stateforge.sfp.manifest.v1.ComponentNode.BindingsEntryR\x08\x62indings\x12\x45\n\x08\x63hildren\x18\x04 \x03(\x0b\x32).stateforge.sfp.manifest.v1.ComponentNodeR\x08\x63hildren\x12\x45\n\x08\x66\x61llback\x18\x05 \x01(\x0b\x32).stateforge.sfp.manifest.v1.ComponentNodeR\x08\x66\x61llback\x12\x43\n\tcondition\x18\x06 \x01(\x0b\x32%.stateforge.sfp.manifest.v1.ConditionR\tcondition\x12>\n\x06repeat\x18\x07 \x01(\x0b\x32&.stateforge.sfp.manifest.v1.RepetitionR\x06repeat\x12\x63\n\x0e\x61sset_bindings\x18\x08 \x03(\x0b\x32<.stateforge.sfp.manifest.v1.ComponentNode.AssetBindingsEntryR\rassetBindings\x1a\x64\n\rBindingsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12=\n\x05value\x18\x02 \x01(\x0b\x32\'.stateforge.sfp.manifest.v1.DataBindingR\x05value:\x02\x38\x01\x1a@\n\x12\x41ssetBindingsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value:\x02\x38\x01\"j\n\x0b\x44\x61taBinding\x12+\n\x11source_identifier\x18\x01 \x01(\tR\x10sourceIdentifier\x12\x18\n\x07pointer\x18\x02 \x01(\tR\x07pointer\x12\x14\n\x05scope\x18\x03 \x01(\tR\x05scope\"\xc7\x01\n\tCondition\x12\x41\n\x07\x62inding\x18\x01 \x01(\x0b\x32\'.stateforge.sfp.manifest.v1.DataBindingR\x07\x62inding\x12I\n\x08operator\x18\x02 \x01(\x0e\x32-.stateforge.sfp.manifest.v1.ConditionOperatorR\x08operator\x12,\n\x05value\x18\x03 \x01(\x0b\x32\x16.google.protobuf.ValueR\x05value\"\x91\x01\n\nRepetition\x12G\n\ncollection\x18\x01 \x01(\x0b\x32\'.stateforge.sfp.manifest.v1.DataBindingR\ncollection\x12\x1d\n\nitem_scope\x18\x02 \x01(\tR\titemScope\x12\x1b\n\tmax_items\x18\x03 \x01(\rR\x08maxItems\"\xf2\x01\n\x13RendererRequirement\x12\x31\n\x14\x65xtension_identifier\x18\x01 \x01(\tR\x13\x65xtensionIdentifier\x12+\n\x11\x65xtension_version\x18\x02 \x01(\tR\x10\x65xtensionVersion\x12\x30\n\x14renderer_api_version\x18\x03 \x01(\tR\x12rendererApiVersion\x12\'\n\x0f\x61rtifact_digest\x18\x04 \x01(\tR\x0e\x61rtifactDigest\x12 \n\x0bpermissions\x18\x05 \x03(\tR\x0bpermissions\"\x95\x01\n\x11PresentationAsset\x12\x1d\n\nmedia_type\x18\x01 \x01(\tR\tmediaType\x12\x18\n\x07\x63ontent\x18\x02 \x01(\x0cR\x07\x63ontent\x12\x14\n\x05width\x18\x03 \x01(\rR\x05width\x12\x16\n\x06height\x18\x04 \x01(\rR\x06height\x12\x19\n\x08\x61lt_text\x18\x05 \x01(\tR\x07\x61ltText*\xbb\x01\n\x11\x43onditionOperator\x12\"\n\x1e\x43ONDITION_OPERATOR_UNSPECIFIED\x10\x00\x12\x1d\n\x19\x43ONDITION_OPERATOR_EXISTS\x10\x01\x12!\n\x1d\x43ONDITION_OPERATOR_NOT_EXISTS\x10\x02\x12\x1d\n\x19\x43ONDITION_OPERATOR_EQUALS\x10\x03\x12!\n\x1d\x43ONDITION_OPERATOR_NOT_EQUALS\x10\x04\x32\x81\x01\n\x0fManifestService\x12n\n\x0bGetManifest\x12..stateforge.sfp.manifest.v1.GetManifestRequest\x1a/.stateforge.sfp.manifest.v1.GetManifestResponseb\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) @@ -38,26 +38,74 @@ _globals['_PROVIDERMANIFEST_RUNTIMEREQUIREMENTSENTRY']._serialized_options = b'8\001' _globals['_PROVIDERMANIFEST_TRIGGERSENTRY']._loaded_options = None _globals['_PROVIDERMANIFEST_TRIGGERSENTRY']._serialized_options = b'8\001' + _globals['_PROVIDERPRESENTATION_OPERATIONSENTRY']._loaded_options = None + _globals['_PROVIDERPRESENTATION_OPERATIONSENTRY']._serialized_options = b'8\001' + _globals['_PROVIDERPRESENTATION_TRIGGERSENTRY']._loaded_options = None + _globals['_PROVIDERPRESENTATION_TRIGGERSENTRY']._serialized_options = b'8\001' + _globals['_PROVIDERPRESENTATION_ASSETSENTRY']._loaded_options = None + _globals['_PROVIDERPRESENTATION_ASSETSENTRY']._serialized_options = b'8\001' + _globals['_PROVIDERPRESENTATION_RENDERERREQUIREMENTSENTRY']._loaded_options = None + _globals['_PROVIDERPRESENTATION_RENDERERREQUIREMENTSENTRY']._serialized_options = b'8\001' + _globals['_PRESENTATIONTARGET_SURFACESENTRY']._loaded_options = None + _globals['_PRESENTATIONTARGET_SURFACESENTRY']._serialized_options = b'8\001' + _globals['_COMPONENTNODE_BINDINGSENTRY']._loaded_options = None + _globals['_COMPONENTNODE_BINDINGSENTRY']._serialized_options = b'8\001' + _globals['_COMPONENTNODE_ASSETBINDINGSENTRY']._loaded_options = None + _globals['_COMPONENTNODE_ASSETBINDINGSENTRY']._serialized_options = b'8\001' + _globals['_CONDITIONOPERATOR']._serialized_start=5261 + _globals['_CONDITIONOPERATOR']._serialized_end=5448 _globals['_GETMANIFESTREQUEST']._serialized_start=113 _globals['_GETMANIFESTREQUEST']._serialized_end=391 _globals['_GETMANIFESTRESPONSE']._serialized_start=394 - _globals['_GETMANIFESTRESPONSE']._serialized_end=720 - _globals['_PROVIDERMANIFEST']._serialized_start=723 - _globals['_PROVIDERMANIFEST']._serialized_end=1679 - _globals['_PROVIDERMANIFEST_OPERATIONSENTRY']._serialized_start=1339 - _globals['_PROVIDERMANIFEST_OPERATIONSENTRY']._serialized_end=1450 - _globals['_PROVIDERMANIFEST_RUNTIMEREQUIREMENTSENTRY']._serialized_start=1452 - _globals['_PROVIDERMANIFEST_RUNTIMEREQUIREMENTSENTRY']._serialized_end=1570 - _globals['_PROVIDERMANIFEST_TRIGGERSENTRY']._serialized_start=1572 - _globals['_PROVIDERMANIFEST_TRIGGERSENTRY']._serialized_end=1679 - _globals['_OPERATIONDECLARATION']._serialized_start=1682 - _globals['_OPERATIONDECLARATION']._serialized_end=1858 - _globals['_RUNTIMEREQUIREMENT']._serialized_start=1860 - _globals['_RUNTIMEREQUIREMENT']._serialized_end=1961 - _globals['_PLATFORMCOMPATIBILITY']._serialized_start=1963 - _globals['_PLATFORMCOMPATIBILITY']._serialized_end=2065 - _globals['_TRIGGERDECLARATION']._serialized_start=2067 - _globals['_TRIGGERDECLARATION']._serialized_end=2151 - _globals['_MANIFESTSERVICE']._serialized_start=2154 - _globals['_MANIFESTSERVICE']._serialized_end=2283 + _globals['_GETMANIFESTRESPONSE']._serialized_end=890 + _globals['_PROVIDERMANIFEST']._serialized_start=893 + _globals['_PROVIDERMANIFEST']._serialized_end=1849 + _globals['_PROVIDERMANIFEST_OPERATIONSENTRY']._serialized_start=1509 + _globals['_PROVIDERMANIFEST_OPERATIONSENTRY']._serialized_end=1620 + _globals['_PROVIDERMANIFEST_RUNTIMEREQUIREMENTSENTRY']._serialized_start=1622 + _globals['_PROVIDERMANIFEST_RUNTIMEREQUIREMENTSENTRY']._serialized_end=1740 + _globals['_PROVIDERMANIFEST_TRIGGERSENTRY']._serialized_start=1742 + _globals['_PROVIDERMANIFEST_TRIGGERSENTRY']._serialized_end=1849 + _globals['_OPERATIONDECLARATION']._serialized_start=1852 + _globals['_OPERATIONDECLARATION']._serialized_end=2028 + _globals['_RUNTIMEREQUIREMENT']._serialized_start=2030 + _globals['_RUNTIMEREQUIREMENT']._serialized_end=2131 + _globals['_PLATFORMCOMPATIBILITY']._serialized_start=2133 + _globals['_PLATFORMCOMPATIBILITY']._serialized_end=2235 + _globals['_TRIGGERDECLARATION']._serialized_start=2237 + _globals['_TRIGGERDECLARATION']._serialized_end=2321 + _globals['_PROVIDERPRESENTATION']._serialized_start=2324 + _globals['_PROVIDERPRESENTATION']._serialized_end=3339 + _globals['_PROVIDERPRESENTATION_OPERATIONSENTRY']._serialized_start=2893 + _globals['_PROVIDERPRESENTATION_OPERATIONSENTRY']._serialized_end=3002 + _globals['_PROVIDERPRESENTATION_TRIGGERSENTRY']._serialized_start=3004 + _globals['_PROVIDERPRESENTATION_TRIGGERSENTRY']._serialized_end=3111 + _globals['_PROVIDERPRESENTATION_ASSETSENTRY']._serialized_start=3113 + _globals['_PROVIDERPRESENTATION_ASSETSENTRY']._serialized_end=3217 + _globals['_PROVIDERPRESENTATION_RENDERERREQUIREMENTSENTRY']._serialized_start=3219 + _globals['_PROVIDERPRESENTATION_RENDERERREQUIREMENTSENTRY']._serialized_end=3339 + _globals['_PRESENTATIONTARGET']._serialized_start=3342 + _globals['_PRESENTATIONTARGET']._serialized_end=3562 + _globals['_PRESENTATIONTARGET_SURFACESENTRY']._serialized_start=3454 + _globals['_PRESENTATIONTARGET_SURFACESENTRY']._serialized_end=3562 + _globals['_PRESENTATIONSURFACE']._serialized_start=3564 + _globals['_PRESENTATIONSURFACE']._serialized_end=3648 + _globals['_COMPONENTNODE']._serialized_start=3651 + _globals['_COMPONENTNODE']._serialized_end=4403 + _globals['_COMPONENTNODE_BINDINGSENTRY']._serialized_start=4237 + _globals['_COMPONENTNODE_BINDINGSENTRY']._serialized_end=4337 + _globals['_COMPONENTNODE_ASSETBINDINGSENTRY']._serialized_start=4339 + _globals['_COMPONENTNODE_ASSETBINDINGSENTRY']._serialized_end=4403 + _globals['_DATABINDING']._serialized_start=4405 + _globals['_DATABINDING']._serialized_end=4511 + _globals['_CONDITION']._serialized_start=4514 + _globals['_CONDITION']._serialized_end=4713 + _globals['_REPETITION']._serialized_start=4716 + _globals['_REPETITION']._serialized_end=4861 + _globals['_RENDERERREQUIREMENT']._serialized_start=4864 + _globals['_RENDERERREQUIREMENT']._serialized_end=5106 + _globals['_PRESENTATIONASSET']._serialized_start=5109 + _globals['_PRESENTATIONASSET']._serialized_end=5258 + _globals['_MANIFESTSERVICE']._serialized_start=5451 + _globals['_MANIFESTSERVICE']._serialized_end=5580 # @@protoc_insertion_point(module_scope) diff --git a/src/stateforge_protocol/sfp/manifest/v1/manifest_pb2.pyi b/src/stateforge_protocol/sfp/manifest/v1/manifest_pb2.pyi index 217b8ee..ee2d24a 100644 --- a/src/stateforge_protocol/sfp/manifest/v1/manifest_pb2.pyi +++ b/src/stateforge_protocol/sfp/manifest/v1/manifest_pb2.pyi @@ -8,6 +8,7 @@ from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import struct_pb2 as _struct_pb2 from google.protobuf.internal import containers as _containers +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper import builtins as _builtins import sys import typing as _typing @@ -19,6 +20,30 @@ else: DESCRIPTOR: _descriptor.FileDescriptor +class _ConditionOperator: + ValueType = _typing.NewType("ValueType", _builtins.int) + V: _TypeAlias = ValueType # noqa: Y015 + +class _ConditionOperatorEnumTypeWrapper(_enum_type_wrapper._EnumTypeWrapper[_ConditionOperator.ValueType], _builtins.type): + DESCRIPTOR: _descriptor.EnumDescriptor + CONDITION_OPERATOR_UNSPECIFIED: _ConditionOperator.ValueType # 0 + CONDITION_OPERATOR_EXISTS: _ConditionOperator.ValueType # 1 + CONDITION_OPERATOR_NOT_EXISTS: _ConditionOperator.ValueType # 2 + CONDITION_OPERATOR_EQUALS: _ConditionOperator.ValueType # 3 + CONDITION_OPERATOR_NOT_EQUALS: _ConditionOperator.ValueType # 4 + +class ConditionOperator(_ConditionOperator, metaclass=_ConditionOperatorEnumTypeWrapper): + """ConditionOperator controls whether a node is rendered. Equality compares + JSON values exactly after resolving the binding. + """ + +CONDITION_OPERATOR_UNSPECIFIED: ConditionOperator.ValueType # 0 +CONDITION_OPERATOR_EXISTS: ConditionOperator.ValueType # 1 +CONDITION_OPERATOR_NOT_EXISTS: ConditionOperator.ValueType # 2 +CONDITION_OPERATOR_EQUALS: ConditionOperator.ValueType # 3 +CONDITION_OPERATOR_NOT_EQUALS: ConditionOperator.ValueType # 4 +Global___ConditionOperator: _TypeAlias = ConditionOperator # noqa: Y015 + @_typing.final class GetManifestRequest(_message.Message): """GetManifestRequest binds the read to the session confirmed by Handshake. @@ -77,6 +102,8 @@ class GetManifestResponse(_message.Message): MANIFEST_REVISION_FIELD_NUMBER: _builtins.int MANIFEST_FIELD_NUMBER: _builtins.int SESSION_ID_FIELD_NUMBER: _builtins.int + PRESENTATION_FIELD_NUMBER: _builtins.int + PRESENTATION_REVISION_FIELD_NUMBER: _builtins.int provider_instance_id: _builtins.str """Must equal the request's expected identity and the negotiated session.""" endpoint_generation: _builtins.int @@ -94,10 +121,23 @@ class GetManifestResponse(_message.Message): The Agent must match it to both the request and its current session before accepting or reusing a cached declaration. Not part of manifest_revision. """ + presentation_revision: _builtins.str + """Present exactly when presentation is present. "sha256:" plus 64 lowercase + hex digits over the canonical presentation preimage defined by this + package. Session ID and endpoint generation are excluded. + """ @_builtins.property def manifest(self) -> Global___ProviderManifest: """Required. At most 1 MiB of canonical JSON for the revision preimage.""" + @_builtins.property + def presentation(self) -> Global___ProviderPresentation: + """Optional declarative presentation snapshot. Operational JSON Schemas + remain sufficient to render every declared capability when this field is + absent, unsupported or rejected. Presentation never changes execution + semantics and is not part of manifest_revision. + """ + def __init__( self, *, @@ -107,12 +147,16 @@ class GetManifestResponse(_message.Message): manifest_revision: _builtins.str = ..., manifest: Global___ProviderManifest | None = ..., session_id: _builtins.str = ..., + presentation: Global___ProviderPresentation | None = ..., + presentation_revision: _builtins.str | None = ..., ) -> None: ... - _HasFieldArgType: _TypeAlias = _typing.Literal["manifest", b"manifest"] # noqa: Y015 + _HasFieldArgType: _TypeAlias = _typing.Literal["_presentation_revision", b"_presentation_revision", "manifest", b"manifest", "presentation", b"presentation", "presentation_revision", b"presentation_revision"] # noqa: Y015 def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... - _ClearFieldArgType: _TypeAlias = _typing.Literal["endpoint_generation", b"endpoint_generation", "manifest", b"manifest", "manifest_revision", b"manifest_revision", "manifest_schema_version", b"manifest_schema_version", "provider_instance_id", b"provider_instance_id", "session_id", b"session_id"] # noqa: Y015 + _ClearFieldArgType: _TypeAlias = _typing.Literal["_presentation_revision", b"_presentation_revision", "endpoint_generation", b"endpoint_generation", "manifest", b"manifest", "manifest_revision", b"manifest_revision", "manifest_schema_version", b"manifest_schema_version", "presentation", b"presentation", "presentation_revision", b"presentation_revision", "provider_instance_id", b"provider_instance_id", "session_id", b"session_id"] # noqa: Y015 def ClearField(self, field_name: _ClearFieldArgType) -> None: ... - def WhichOneof(self, oneof_group: _Never) -> None: ... + _WhichOneofReturnType__presentation_revision: _TypeAlias = _typing.Literal["presentation_revision"] # noqa: Y015 + _WhichOneofArgType__presentation_revision: _TypeAlias = _typing.Literal["_presentation_revision", b"_presentation_revision"] # noqa: Y015 + def WhichOneof(self, oneof_group: _WhichOneofArgType__presentation_revision) -> _WhichOneofReturnType__presentation_revision | None: ... Global___GetManifestResponse: _TypeAlias = GetManifestResponse # noqa: Y015 @@ -373,3 +417,472 @@ class TriggerDeclaration(_message.Message): def WhichOneof(self, oneof_group: _Never) -> None: ... Global___TriggerDeclaration: _TypeAlias = TriggerDeclaration # noqa: Y015 + +@_typing.final +class ProviderPresentation(_message.Message): + """ProviderPresentation is an optional, independently revised visual overlay + on an accepted ProviderManifest. Maps use the exact operation and trigger + identifiers declared by that manifest. Presentation cannot add, remove or + redefine capabilities or their JSON Schemas. + """ + + DESCRIPTOR: _descriptor.Descriptor + + @_typing.final + class OperationsEntry(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + KEY_FIELD_NUMBER: _builtins.int + VALUE_FIELD_NUMBER: _builtins.int + key: _builtins.str + @_builtins.property + def value(self) -> Global___PresentationTarget: ... + def __init__( + self, + *, + key: _builtins.str = ..., + value: Global___PresentationTarget | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["value", b"value"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key", "value", b"value"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + + @_typing.final + class TriggersEntry(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + KEY_FIELD_NUMBER: _builtins.int + VALUE_FIELD_NUMBER: _builtins.int + key: _builtins.str + @_builtins.property + def value(self) -> Global___PresentationTarget: ... + def __init__( + self, + *, + key: _builtins.str = ..., + value: Global___PresentationTarget | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["value", b"value"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key", "value", b"value"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + + @_typing.final + class AssetsEntry(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + KEY_FIELD_NUMBER: _builtins.int + VALUE_FIELD_NUMBER: _builtins.int + key: _builtins.str + @_builtins.property + def value(self) -> Global___PresentationAsset: ... + def __init__( + self, + *, + key: _builtins.str = ..., + value: Global___PresentationAsset | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["value", b"value"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key", "value", b"value"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + + @_typing.final + class RendererRequirementsEntry(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + KEY_FIELD_NUMBER: _builtins.int + VALUE_FIELD_NUMBER: _builtins.int + key: _builtins.str + @_builtins.property + def value(self) -> Global___RendererRequirement: ... + def __init__( + self, + *, + key: _builtins.str = ..., + value: Global___RendererRequirement | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["value", b"value"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key", "value", b"value"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + + PRESENTATION_SCHEMA_VERSION_FIELD_NUMBER: _builtins.int + PROVIDER_FIELD_NUMBER: _builtins.int + OPERATIONS_FIELD_NUMBER: _builtins.int + TRIGGERS_FIELD_NUMBER: _builtins.int + ASSETS_FIELD_NUMBER: _builtins.int + RENDERER_REQUIREMENTS_FIELD_NUMBER: _builtins.int + presentation_schema_version: _builtins.int + """Presentation document version. Version 1 is defined by this package.""" + @_builtins.property + def provider(self) -> Global___PresentationTarget: + """Optional Provider-level surfaces.""" + + @_builtins.property + def operations(self) -> _containers.MessageMap[_builtins.str, Global___PresentationTarget]: + """Optional surfaces keyed by declared operation identifier.""" + + @_builtins.property + def triggers(self) -> _containers.MessageMap[_builtins.str, Global___PresentationTarget]: + """Optional surfaces keyed by declared trigger identifier.""" + + @_builtins.property + def assets(self) -> _containers.MessageMap[_builtins.str, Global___PresentationAsset]: + """Embedded content-addressed visuals keyed by their sha256 digest.""" + + @_builtins.property + def renderer_requirements(self) -> _containers.MessageMap[_builtins.str, Global___RendererRequirement]: + """Renderer metadata keyed by the custom component namespace it serves. + Every stateforge.* namespace is reserved and cannot require an extension. + """ + + def __init__( + self, + *, + presentation_schema_version: _builtins.int = ..., + provider: Global___PresentationTarget | None = ..., + operations: _abc.Mapping[_builtins.str, Global___PresentationTarget] | None = ..., + triggers: _abc.Mapping[_builtins.str, Global___PresentationTarget] | None = ..., + assets: _abc.Mapping[_builtins.str, Global___PresentationAsset] | None = ..., + renderer_requirements: _abc.Mapping[_builtins.str, Global___RendererRequirement] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["provider", b"provider"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["assets", b"assets", "operations", b"operations", "presentation_schema_version", b"presentation_schema_version", "provider", b"provider", "renderer_requirements", b"renderer_requirements", "triggers", b"triggers"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___ProviderPresentation: _TypeAlias = ProviderPresentation # noqa: Y015 + +@_typing.final +class PresentationTarget(_message.Message): + """PresentationTarget owns the surfaces declared for one Provider, operation or + trigger. Keys are versioned surface identifiers defined by this contract. + """ + + DESCRIPTOR: _descriptor.Descriptor + + @_typing.final + class SurfacesEntry(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + KEY_FIELD_NUMBER: _builtins.int + VALUE_FIELD_NUMBER: _builtins.int + key: _builtins.str + @_builtins.property + def value(self) -> Global___PresentationSurface: ... + def __init__( + self, + *, + key: _builtins.str = ..., + value: Global___PresentationSurface | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["value", b"value"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key", "value", b"value"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + + SURFACES_FIELD_NUMBER: _builtins.int + @_builtins.property + def surfaces(self) -> _containers.MessageMap[_builtins.str, Global___PresentationSurface]: ... + def __init__( + self, + *, + surfaces: _abc.Mapping[_builtins.str, Global___PresentationSurface] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["surfaces", b"surfaces"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___PresentationTarget: _TypeAlias = PresentationTarget # noqa: Y015 + +@_typing.final +class PresentationSurface(_message.Message): + """PresentationSurface is one bounded declarative component tree.""" + + DESCRIPTOR: _descriptor.Descriptor + + ROOT_FIELD_NUMBER: _builtins.int + @_builtins.property + def root(self) -> Global___ComponentNode: ... + def __init__( + self, + *, + root: Global___ComponentNode | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["root", b"root"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["root", b"root"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___PresentationSurface: _TypeAlias = PresentationSurface # noqa: Y015 + +@_typing.final +class ComponentNode(_message.Message): + """ComponentNode selects a renderer by identifier and supplies only declarative + data. Properties are interpreted by the Control Plane renderer registry, not + by SFP. Custom components require renderer metadata and a core-only fallback. + """ + + DESCRIPTOR: _descriptor.Descriptor + + @_typing.final + class BindingsEntry(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + KEY_FIELD_NUMBER: _builtins.int + VALUE_FIELD_NUMBER: _builtins.int + key: _builtins.str + @_builtins.property + def value(self) -> Global___DataBinding: ... + def __init__( + self, + *, + key: _builtins.str = ..., + value: Global___DataBinding | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["value", b"value"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key", "value", b"value"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + + @_typing.final + class AssetBindingsEntry(_message.Message): + DESCRIPTOR: _descriptor.Descriptor + + KEY_FIELD_NUMBER: _builtins.int + VALUE_FIELD_NUMBER: _builtins.int + key: _builtins.str + value: _builtins.str + def __init__( + self, + *, + key: _builtins.str = ..., + value: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["key", b"key", "value", b"value"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + + COMPONENT_IDENTIFIER_FIELD_NUMBER: _builtins.int + PROPERTIES_FIELD_NUMBER: _builtins.int + BINDINGS_FIELD_NUMBER: _builtins.int + CHILDREN_FIELD_NUMBER: _builtins.int + FALLBACK_FIELD_NUMBER: _builtins.int + CONDITION_FIELD_NUMBER: _builtins.int + REPEAT_FIELD_NUMBER: _builtins.int + ASSET_BINDINGS_FIELD_NUMBER: _builtins.int + component_identifier: _builtins.str + @_builtins.property + def properties(self) -> _struct_pb2.Struct: ... + @_builtins.property + def bindings(self) -> _containers.MessageMap[_builtins.str, Global___DataBinding]: ... + @_builtins.property + def children(self) -> _containers.RepeatedCompositeFieldContainer[Global___ComponentNode]: ... + @_builtins.property + def fallback(self) -> Global___ComponentNode: ... + @_builtins.property + def condition(self) -> Global___Condition: ... + @_builtins.property + def repeat(self) -> Global___Repetition: ... + @_builtins.property + def asset_bindings(self) -> _containers.ScalarMap[_builtins.str, _builtins.str]: + """Renderer-defined slot name to embedded asset digest.""" + + def __init__( + self, + *, + component_identifier: _builtins.str = ..., + properties: _struct_pb2.Struct | None = ..., + bindings: _abc.Mapping[_builtins.str, Global___DataBinding] | None = ..., + children: _abc.Iterable[Global___ComponentNode] | None = ..., + fallback: Global___ComponentNode | None = ..., + condition: Global___Condition | None = ..., + repeat: Global___Repetition | None = ..., + asset_bindings: _abc.Mapping[_builtins.str, _builtins.str] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["condition", b"condition", "fallback", b"fallback", "properties", b"properties", "repeat", b"repeat"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["asset_bindings", b"asset_bindings", "bindings", b"bindings", "children", b"children", "component_identifier", b"component_identifier", "condition", b"condition", "fallback", b"fallback", "properties", b"properties", "repeat", b"repeat"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___ComponentNode: _TypeAlias = ComponentNode # noqa: Y015 + +@_typing.final +class DataBinding(_message.Message): + """DataBinding points at immutable data supplied by the Control Plane for the + current surface. Empty pointer selects the complete source document. Scope is + empty except for bindings to a named repetition item. + """ + + DESCRIPTOR: _descriptor.Descriptor + + SOURCE_IDENTIFIER_FIELD_NUMBER: _builtins.int + POINTER_FIELD_NUMBER: _builtins.int + SCOPE_FIELD_NUMBER: _builtins.int + source_identifier: _builtins.str + pointer: _builtins.str + scope: _builtins.str + def __init__( + self, + *, + source_identifier: _builtins.str = ..., + pointer: _builtins.str = ..., + scope: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["pointer", b"pointer", "scope", b"scope", "source_identifier", b"source_identifier"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___DataBinding: _TypeAlias = DataBinding # noqa: Y015 + +@_typing.final +class Condition(_message.Message): + """Condition is optional. EXISTS and NOT_EXISTS omit value; equality operators + require value, including an explicitly supplied JSON null. + """ + + DESCRIPTOR: _descriptor.Descriptor + + BINDING_FIELD_NUMBER: _builtins.int + OPERATOR_FIELD_NUMBER: _builtins.int + VALUE_FIELD_NUMBER: _builtins.int + operator: Global___ConditionOperator.ValueType + @_builtins.property + def binding(self) -> Global___DataBinding: ... + @_builtins.property + def value(self) -> _struct_pb2.Value: ... + def __init__( + self, + *, + binding: Global___DataBinding | None = ..., + operator: Global___ConditionOperator.ValueType = ..., + value: _struct_pb2.Value | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["binding", b"binding", "value", b"value"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["binding", b"binding", "operator", b"operator", "value", b"value"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___Condition: _TypeAlias = Condition # noqa: Y015 + +@_typing.final +class Repetition(_message.Message): + """Repetition renders a node once per item in one bound collection. max_items is + a required positive safety ceiling; item_scope names the item for descendant + bindings. + """ + + DESCRIPTOR: _descriptor.Descriptor + + COLLECTION_FIELD_NUMBER: _builtins.int + ITEM_SCOPE_FIELD_NUMBER: _builtins.int + MAX_ITEMS_FIELD_NUMBER: _builtins.int + item_scope: _builtins.str + max_items: _builtins.int + @_builtins.property + def collection(self) -> Global___DataBinding: ... + def __init__( + self, + *, + collection: Global___DataBinding | None = ..., + item_scope: _builtins.str = ..., + max_items: _builtins.int = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _typing.Literal["collection", b"collection"] # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["collection", b"collection", "item_scope", b"item_scope", "max_items", b"max_items"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___Repetition: _TypeAlias = Repetition # noqa: Y015 + +@_typing.final +class RendererRequirement(_message.Message): + """RendererRequirement identifies a separately distributed renderer extension. + SFP transports metadata only: no executable bytes, URL or install command is + carried by this message. Permissions are versioned identifiers understood by + the Control Plane extension host. + """ + + DESCRIPTOR: _descriptor.Descriptor + + EXTENSION_IDENTIFIER_FIELD_NUMBER: _builtins.int + EXTENSION_VERSION_FIELD_NUMBER: _builtins.int + RENDERER_API_VERSION_FIELD_NUMBER: _builtins.int + ARTIFACT_DIGEST_FIELD_NUMBER: _builtins.int + PERMISSIONS_FIELD_NUMBER: _builtins.int + extension_identifier: _builtins.str + extension_version: _builtins.str + renderer_api_version: _builtins.str + artifact_digest: _builtins.str + @_builtins.property + def permissions(self) -> _containers.RepeatedScalarFieldContainer[_builtins.str]: ... + def __init__( + self, + *, + extension_identifier: _builtins.str = ..., + extension_version: _builtins.str = ..., + renderer_api_version: _builtins.str = ..., + artifact_digest: _builtins.str = ..., + permissions: _abc.Iterable[_builtins.str] | None = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["artifact_digest", b"artifact_digest", "extension_identifier", b"extension_identifier", "extension_version", b"extension_version", "permissions", b"permissions", "renderer_api_version", b"renderer_api_version"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___RendererRequirement: _TypeAlias = RendererRequirement # noqa: Y015 + +@_typing.final +class PresentationAsset(_message.Message): + """PresentationAsset is embedded, content-addressed media. The map key is the + sha256 digest of content. Remote URLs and filesystem paths have no wire field. + """ + + DESCRIPTOR: _descriptor.Descriptor + + MEDIA_TYPE_FIELD_NUMBER: _builtins.int + CONTENT_FIELD_NUMBER: _builtins.int + WIDTH_FIELD_NUMBER: _builtins.int + HEIGHT_FIELD_NUMBER: _builtins.int + ALT_TEXT_FIELD_NUMBER: _builtins.int + media_type: _builtins.str + content: _builtins.bytes + width: _builtins.int + height: _builtins.int + alt_text: _builtins.str + def __init__( + self, + *, + media_type: _builtins.str = ..., + content: _builtins.bytes = ..., + width: _builtins.int = ..., + height: _builtins.int = ..., + alt_text: _builtins.str = ..., + ) -> None: ... + _HasFieldArgType: _TypeAlias = _Never # noqa: Y015 + def HasField(self, field_name: _HasFieldArgType) -> _builtins.bool: ... + _ClearFieldArgType: _TypeAlias = _typing.Literal["alt_text", b"alt_text", "content", b"content", "height", b"height", "media_type", b"media_type", "width", b"width"] # noqa: Y015 + def ClearField(self, field_name: _ClearFieldArgType) -> None: ... + def WhichOneof(self, oneof_group: _Never) -> None: ... + +Global___PresentationAsset: _TypeAlias = PresentationAsset # noqa: Y015 diff --git a/src/stateforge_protocol/sfp/manifest/v1/validation.py b/src/stateforge_protocol/sfp/manifest/v1/validation.py index 7eddba4..c340178 100644 --- a/src/stateforge_protocol/sfp/manifest/v1/validation.py +++ b/src/stateforge_protocol/sfp/manifest/v1/validation.py @@ -4,11 +4,13 @@ import hashlib from dataclasses import dataclass +from enum import StrEnum from typing import TYPE_CHECKING, Any, Final, cast from uuid import UUID from stateforge_protocol.sfp import _validation from stateforge_protocol.sfp.manifest.v1 import ( + _presentation, _schema_inspection, contract, manifest_pb2, @@ -23,13 +25,21 @@ "ManifestRevisionKey", "ManifestValidationError", "ManifestValidationLimits", + "PresentationRevisionKey", + "PresentationValidationStatus", + "ValidatedManifestExchange", "bounded_json", "canonical_bytes", + "canonical_presentation_bytes", "compute_manifest_revision", + "compute_presentation_revision", "contract_validator", "validate_manifest_document", + "validate_manifest_exchange", "validate_manifest_key", "validate_manifest_response", + "validate_presentation_document", + "validate_presentation_key", "validate_schema", "validate_structure", ] @@ -86,6 +96,36 @@ class ManifestRevisionKey: revision: str +@dataclass(frozen=True, slots=True) +class PresentationRevisionKey: + """Identify one valid presentation bound to an operational manifest.""" + + provider_instance_id: UUID + manifest_revision: str + schema_version: int + revision: str + + +class PresentationValidationStatus(StrEnum): + """Describe how an optional presentation snapshot was handled.""" + + ABSENT = "absent" + ACCEPTED = "accepted" + UNSUPPORTED = "unsupported" + INVALID = "invalid" + + +@dataclass(frozen=True, slots=True) +class ValidatedManifestExchange: + """Retain independently validated operational and presentation data.""" + + manifest_key: ManifestRevisionKey + manifest_document: bytes + presentation_status: PresentationValidationStatus + presentation_key: PresentationRevisionKey | None = None + presentation_document: bytes | None = None + + def bounded_json( value: object, path: str, @@ -113,6 +153,16 @@ def canonical_bytes(value: dict[str, Any]) -> bytes: ) +def canonical_presentation_bytes(value: dict[str, Any]) -> bytes: + """Return bounded RFC 8785 bytes for a presentation document.""" + return _VALIDATION.canonicalize_json( + value, + maximum_bytes=contract.MAX_PRESENTATION_REVISION_PREIMAGE_BYTES, + limit_message="presentation: canonical preimage limit exceeded", + invalid_message="presentation: non-interoperable JSON value", + ) + + def contract_validator(definition: str) -> Draft202012Validator: """Load a validation projection from the installed Protocol package.""" return _SCHEMA.validator(definition) @@ -183,22 +233,100 @@ def compute_manifest_revision( return "sha256:" + hashlib.sha256(preimage).hexdigest() -def validate_manifest_response( - response: manifest_pb2.GetManifestResponse, +def compute_presentation_revision( + presentation: dict[str, Any], + manifest_revision: str, + provider_instance_id: str, +) -> str: + """Return the revision for presentation bound to one manifest.""" + validate_structure( + provider_instance_id, "instanceId", "providerInstanceId" + ) + if not _SCHEMA.is_valid(manifest_revision, "revision"): + raise ManifestValidationError( + "presentation: manifest revision is invalid" + ) + preimage = canonical_presentation_bytes( + { + "manifestRevision": manifest_revision, + "presentation": presentation, + "providerInstanceId": provider_instance_id, + } + ) + return "sha256:" + hashlib.sha256(preimage).hexdigest() + + +def validate_presentation_document( + presentation: manifest_pb2.ProviderPresentation, + manifest: dict[str, Any], *, limits: ManifestValidationLimits = DEFAULT_VALIDATION_LIMITS, ) -> bytes: - """Validate a response and return its canonical manifest bytes.""" + """Validate one complete presentation overlay and its references.""" + presentation = _VALIDATION.require_instance( + presentation, + manifest_pb2.ProviderPresentation, + "presentation: expected ProviderPresentation", + ) + document = cast( + dict[str, Any], + _VALIDATION.project_message(presentation, "presentation"), + ) + _VALIDATION.require_bounded_json( + document, + "presentation", + maximum_depth=contract.MAX_EMBEDDED_JSON_DEPTH + 4, + maximum_nodes=limits.max_json_nodes, + maximum_bytes=contract.MAX_PRESENTATION_REVISION_PREIMAGE_BYTES, + ) + validate_structure(document, "providerPresentation", "presentation") + _presentation.validate_presentation_semantics( + document, + manifest, + presentation, + error_type=ManifestValidationError, + ) + return canonical_presentation_bytes(document) + + +def validate_manifest_exchange( + response: manifest_pb2.GetManifestResponse, + *, + limits: ManifestValidationLimits = DEFAULT_VALIDATION_LIMITS, +) -> ValidatedManifestExchange: + """Validate a manifest and independently accept its presentation.""" + response = _VALIDATION.require_instance( + response, + manifest_pb2.GetManifestResponse, + "response: expected GetManifestResponse", + ) + _VALIDATION.require_serialized_size( + response, + maximum_bytes=contract.MAX_RESPONSE_BYTES, + path="response", + ) projected = _VALIDATION.project_message(response, "response") - bounded_json( + _VALIDATION.require_bounded_json( projected, "response", - depth_limit=contract.MAX_EMBEDDED_JSON_DEPTH + 4, - limits=limits, + maximum_depth=contract.MAX_EMBEDDED_JSON_DEPTH + 6, + maximum_nodes=limits.max_json_nodes, + maximum_bytes=contract.MAX_RESPONSE_BYTES * 2, ) - validate_structure(projected, "getManifestResponse", "response") + operational = { + key: projected[key] + for key in ( + "providerInstanceId", + "endpointGeneration", + "manifestSchemaVersion", + "manifestRevision", + "manifest", + "sessionId", + ) + } + validate_structure(operational, "getManifestResponse", "response") manifest = cast(dict[str, Any], projected["manifest"]) - document = validate_manifest_document(manifest, limits=limits) + manifest_document = validate_manifest_document(manifest, limits=limits) revision = compute_manifest_revision( manifest, response.manifest_schema_version, @@ -206,7 +334,89 @@ def validate_manifest_response( ) if revision != response.manifest_revision: raise ManifestValidationError("response: manifest revision mismatch") - return document + manifest_key = validate_manifest_key( + response.provider_instance_id, + response.manifest_schema_version, + response.manifest_revision, + ) + + if not response.HasField("presentation"): + status = ( + PresentationValidationStatus.ABSENT + if not response.HasField("presentation_revision") + else PresentationValidationStatus.INVALID + ) + return ValidatedManifestExchange( + manifest_key=manifest_key, + manifest_document=manifest_document, + presentation_status=status, + ) + if not _SCHEMA.is_valid(response.presentation_revision, "revision"): + return ValidatedManifestExchange( + manifest_key=manifest_key, + manifest_document=manifest_document, + presentation_status=PresentationValidationStatus.INVALID, + ) + presentation_schema_version = ( + response.presentation.presentation_schema_version + ) + if presentation_schema_version == 0: + return ValidatedManifestExchange( + manifest_key=manifest_key, + manifest_document=manifest_document, + presentation_status=PresentationValidationStatus.INVALID, + ) + if presentation_schema_version != contract.PRESENTATION_SCHEMA_VERSION: + return ValidatedManifestExchange( + manifest_key=manifest_key, + manifest_document=manifest_document, + presentation_status=PresentationValidationStatus.UNSUPPORTED, + ) + + presentation = cast(dict[str, Any], projected["presentation"]) + try: + presentation_document = validate_presentation_document( + response.presentation, + manifest, + limits=limits, + ) + expected_revision = compute_presentation_revision( + presentation, + response.manifest_revision, + response.provider_instance_id, + ) + if expected_revision != response.presentation_revision: + raise ManifestValidationError("presentation: revision mismatch") + presentation_key = validate_presentation_key( + response.provider_instance_id, + response.manifest_revision, + presentation_schema_version, + response.presentation_revision, + ) + except ManifestValidationError: + return ValidatedManifestExchange( + manifest_key=manifest_key, + manifest_document=manifest_document, + presentation_status=PresentationValidationStatus.INVALID, + ) + return ValidatedManifestExchange( + manifest_key=manifest_key, + manifest_document=manifest_document, + presentation_status=PresentationValidationStatus.ACCEPTED, + presentation_key=presentation_key, + presentation_document=presentation_document, + ) + + +def validate_manifest_response( + response: manifest_pb2.GetManifestResponse, + *, + limits: ManifestValidationLimits = DEFAULT_VALIDATION_LIMITS, +) -> bytes: + """Validate a response and return its canonical operational manifest.""" + return validate_manifest_exchange( + response, limits=limits + ).manifest_document def validate_manifest_key( @@ -229,6 +439,36 @@ def validate_manifest_key( ) +def validate_presentation_key( + provider_instance_id: str, + manifest_revision: str, + presentation_schema_version: int, + presentation_revision: str, +) -> PresentationRevisionKey: + """Validate the scalar key for an accepted presentation snapshot.""" + if not _SCHEMA.is_valid(provider_instance_id, "instanceId"): + raise ManifestValidationError( + "presentation: provider identity must be a canonical UUIDv4" + ) + if not _SCHEMA.is_valid(manifest_revision, "revision"): + raise ManifestValidationError( + "presentation: manifest revision is invalid" + ) + _VALIDATION.require_equal( + presentation_schema_version, + contract.PRESENTATION_SCHEMA_VERSION, + "presentation: schema version is unsupported", + ) + if not _SCHEMA.is_valid(presentation_revision, "revision"): + raise ManifestValidationError("presentation: revision is invalid") + return PresentationRevisionKey( + provider_instance_id=UUID(provider_instance_id), + manifest_revision=manifest_revision, + schema_version=presentation_schema_version, + revision=presentation_revision, + ) + + def _validate_embedded_schemas( manifest: dict[str, Any], *, diff --git a/tests/fixtures/manifest/presentation-response.json b/tests/fixtures/manifest/presentation-response.json new file mode 100644 index 0000000..37f40c1 --- /dev/null +++ b/tests/fixtures/manifest/presentation-response.json @@ -0,0 +1,240 @@ +{ + "providerInstanceId": "7f7db7d8-68b4-4f71-9769-065b5c4f941c", + "endpointGeneration": "4", + "manifestSchemaVersion": 1, + "manifest": { + "providerIdentity": "stateforge.git", + "implementationVersion": "1.0.0", + "displayName": "Git Provider", + "operations": { + "stateforge.git/reference.resolve@1": { + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "repository": { + "type": "string" + }, + "depth": { + "type": "integer", + "minimum": 1, + "maximum": 10 + }, + "token": { + "type": "string", + "writeOnly": true + } + }, + "required": [ + "repository" + ], + "additionalProperties": false + }, + "resultSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "commit": { + "type": "string" + }, + "changed": { + "type": "boolean" + } + }, + "required": [ + "commit" + ], + "additionalProperties": false + }, + "implements": [] + } + }, + "runtimeRequirements": { + "executable.git": { + "description": "Git executable available to the Provider", + "versionConstraint": ">=2.40" + } + }, + "platforms": [ + { + "operatingSystem": "linux", + "architecture": "x86_64" + } + ], + "configurationSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "repository": { + "type": "string" + }, + "token": { + "type": "string", + "writeOnly": true + } + }, + "required": [ + "repository" + ], + "additionalProperties": false + }, + "triggers": { + "stateforge.git/reference.changed@1": { + "payloadSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "reference": { + "type": "string" + }, + "previous": { + "type": "string" + } + }, + "required": [ + "reference" + ], + "additionalProperties": false + } + } + } + }, + "manifestRevision": "sha256:c836c97c8f170ea22b7c9002aa6075d84746dab7bbe3c822f628fd1176fd3c56", + "sessionId": "manifest-session-A", + "presentation": { + "presentationSchemaVersion": 1, + "provider": { + "surfaces": { + "stateforge.ui/surface.provider.overview@1": { + "root": { + "componentIdentifier": "stateforge.ui/layout.stack@1", + "properties": { + "gap": "large" + }, + "bindings": {}, + "children": [ + { + "componentIdentifier": "stateforge.ui/media.image@1", + "properties": { + "fit": "contain" + }, + "bindings": {}, + "children": [], + "assetBindings": { + "source": "sha256:8c5dec37f2aba701bd79272fc7fe4d34292623e531df7fd23b95cb3c96034741" + } + }, + { + "componentIdentifier": "stateforge.ui/content.text@1", + "properties": { + "title": "Git Provider", + "body": "Inspect and resolve Git references." + }, + "bindings": {}, + "children": [], + "assetBindings": {} + } + ], + "assetBindings": {} + } + } + } + }, + "operations": { + "stateforge.git/reference.resolve@1": { + "surfaces": { + "stateforge.ui/surface.operation.request@1": { + "root": { + "componentIdentifier": "stateforge.ui/input.form@1", + "properties": { + "submitLabel": "Resolve reference" + }, + "bindings": { + "schema": { + "sourceIdentifier": "stateforge.binding/operation.request.schema@1", + "pointer": "", + "scope": "" + }, + "value": { + "sourceIdentifier": "stateforge.binding/operation.request.public_value@1", + "pointer": "", + "scope": "" + } + }, + "children": [], + "assetBindings": {} + } + }, + "stateforge.ui/surface.operation.result@1": { + "root": { + "componentIdentifier": "example.git/data.commit_graph@1", + "properties": {}, + "bindings": { + "result": { + "sourceIdentifier": "stateforge.binding/operation.result.value@1", + "pointer": "", + "scope": "" + } + }, + "children": [], + "assetBindings": {}, + "fallback": { + "componentIdentifier": "stateforge.ui/data.tree@1", + "properties": {}, + "bindings": { + "value": { + "sourceIdentifier": "stateforge.binding/operation.result.value@1", + "pointer": "", + "scope": "" + } + }, + "children": [], + "assetBindings": {} + } + } + } + } + } + }, + "triggers": { + "stateforge.git/reference.changed@1": { + "surfaces": { + "stateforge.ui/surface.trigger.event@1": { + "root": { + "componentIdentifier": "stateforge.ui/data.key_value@1", + "properties": {}, + "bindings": { + "value": { + "sourceIdentifier": "stateforge.binding/trigger.payload.value@1", + "pointer": "", + "scope": "" + } + }, + "children": [], + "assetBindings": {} + } + } + } + } + }, + "assets": { + "sha256:8c5dec37f2aba701bd79272fc7fe4d34292623e531df7fd23b95cb3c96034741": { + "mediaType": "image/svg+xml", + "content": "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxNiAxNiI+PHBhdGggZD0iTTIgMmgxMnYxMkgyeiIvPjwvc3ZnPg==", + "width": 16, + "height": 16, + "altText": "Git Provider mark" + } + }, + "rendererRequirements": { + "example.git": { + "extensionIdentifier": "example.git/renderer@1", + "extensionVersion": "1.0.0", + "rendererApiVersion": "1.0.0", + "artifactDigest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "permissions": [] + } + } + }, + "presentationRevision": "sha256:df215c63eb41659f8d38649cf84bd9f9e7696aa9d08b88219f219361d1bc8d2d" +} diff --git a/tests/test_documentation_system.py b/tests/test_documentation_system.py index 6635de6..44d620b 100644 --- a/tests/test_documentation_system.py +++ b/tests/test_documentation_system.py @@ -47,6 +47,66 @@ def test_protocol_uses_the_shared_documentation_presentation() -> None: assert configuration.extra["annotate"]["json"] == [".s2"] +def test_provider_presentation_guide_maps_components_to_surfaces() -> None: + page = ( + ROOT / "docs/v0.1.0/procedures/provider-presentation.md" + ).read_text(encoding="utf-8") + configuration = load_config( + config_file=str(ROOT / "mkdocs.yml"), + strict=True, + ) + version_navigation = configuration.nav[0]["Protocol documentation"][1][ + "v0.1.0" + ] + procedure_navigation = next( + item["SFP procedures"] + for item in version_navigation + if isinstance(item, dict) and "SFP procedures" in item + ) + + assert { + "Provider manifest exchange": [ + { + "Contract and exchange": ( + "v0.1.0/procedures/provider-manifest.md" + ) + }, + { + "Provider presentation": ( + "v0.1.0/procedures/provider-presentation.md" + ) + }, + ] + } in procedure_navigation + for contract_type in ( + "`PresentationTarget`", + "`PresentationSurface`", + "`ComponentNode`", + "`DataBinding`", + "`RendererRequirement`", + "`PresentationAsset`", + ): + assert contract_type in page + for surface in ( + "surface.provider.overview@1", + "surface.operation.request@1", + "surface.operation.run@1", + "surface.operation.result@1", + "surface.trigger.policy@1", + "surface.trigger.event@1", + "surface.evidence@1", + ): + assert surface in page + assert "schema-derived interface" in page.lower() + assert "active Control Plane skin" in page + assert "operation.request.public_value@1" in page + assert "has no presentation binding identifier" in page + assert "input.secret" in page + assert "Portable core structure" in page + assert "No second SFP presentation RPC" in page + assert "SF-AOP" in page + + def test_documentation_home_orients_readers_to_the_protocol() -> None: home = (ROOT / "docs/index.md").read_text(encoding="utf-8") diff --git a/tests/test_manifest_contract.py b/tests/test_manifest_contract.py index 7b8ff65..af1341c 100644 --- a/tests/test_manifest_contract.py +++ b/tests/test_manifest_contract.py @@ -15,6 +15,18 @@ from tests.documentation import annotated_json_example from stateforge_protocol.sfp.manifest.v1 import contract, manifest_pb2 +from stateforge_protocol.sfp.operation_admission.v1 import ( + operation_admission_pb2, +) +from stateforge_protocol.sfp.operation_admission.v1 import ( + validation as admission_validation, +) +from stateforge_protocol.sfp.trigger_publication.v1 import ( + trigger_publication_pb2, +) +from stateforge_protocol.sfp.trigger_publication.v1 import ( + validation as trigger_validation, +) _FIXTURES = Path(__file__).parent / "fixtures" / "manifest" _SCHEMA = json.loads( @@ -56,12 +68,27 @@ def test_versioned_contract_exposes_normative_limits() -> None: "MAX_REQUEST_BYTES": 8 * 1024, "MAX_RESPONSE_BYTES": 2 * 1024 * 1024, "MAX_CANONICAL_REVISION_PREIMAGE_BYTES": 1 * 1024 * 1024, + "MAX_PRESENTATION_REVISION_PREIMAGE_BYTES": 2 * 1024 * 1024, "MAX_EMBEDDED_JSON_DEPTH": 64, "MAX_OPERATIONS": 1_024, "MAX_TRIGGERS": 1_024, "MAX_RUNTIME_REQUIREMENTS": 1_024, "MAX_PLATFORMS": 256, "MAX_PROFILE_CLAIMS_PER_OPERATION": 64, + "PRESENTATION_SCHEMA_VERSION": 1, + "MAX_PRESENTATION_SURFACES_PER_TARGET": 8, + "MAX_PRESENTATION_COMPONENTS": 4_096, + "MAX_PRESENTATION_COMPONENT_DEPTH": 16, + "MAX_COMPONENT_CHILDREN": 256, + "MAX_COMPONENT_BINDINGS": 64, + "MAX_COMPONENT_ASSET_BINDINGS": 32, + "MAX_RENDERER_REQUIREMENTS": 64, + "MAX_RENDERER_PERMISSIONS": 32, + "MAX_REPETITION_ITEMS": 1_024, + "MAX_PRESENTATION_ASSETS": 64, + "MAX_PRESENTATION_ASSET_BYTES": 256 * 1024, + "MAX_PRESENTATION_ASSET_TOTAL_BYTES": 1 * 1024 * 1024, + "MAX_PRESENTATION_ASSET_DIMENSION": 8_192, } assert {name: getattr(contract, name) for name in expected} == expected @@ -92,6 +119,55 @@ def test_versioned_contract_limits_match_packaged_schema() -> None: definitions["sessionId"]["maxLength"] == contract.MAX_SESSION_ID_CODE_POINTS ) + presentation = definitions["providerPresentation"]["properties"] + assert ( + presentation["presentationSchemaVersion"]["const"] + == contract.PRESENTATION_SCHEMA_VERSION + ) + assert ( + presentation["operations"]["maxProperties"] + == contract.MAX_PRESENTATION_OPERATIONS + ) + assert ( + presentation["triggers"]["maxProperties"] + == contract.MAX_PRESENTATION_TRIGGERS + ) + assert ( + presentation["assets"]["maxProperties"] + == contract.MAX_PRESENTATION_ASSETS + ) + assert ( + definitions["presentationTarget"]["properties"]["surfaces"][ + "maxProperties" + ] + == contract.MAX_PRESENTATION_SURFACES_PER_TARGET + ) + component = definitions["componentNode"]["properties"] + assert component["children"]["maxItems"] == contract.MAX_COMPONENT_CHILDREN + assert ( + component["bindings"]["maxProperties"] + == contract.MAX_COMPONENT_BINDINGS + ) + assert ( + component["assetBindings"]["maxProperties"] + == contract.MAX_COMPONENT_ASSET_BINDINGS + ) + assert ( + presentation["rendererRequirements"]["maxProperties"] + == contract.MAX_RENDERER_REQUIREMENTS + ) + assert ( + definitions["rendererRequirement"]["properties"]["permissions"][ + "maxItems" + ] + == contract.MAX_RENDERER_PERMISSIONS + ) + assert ( + set( + definitions["presentationAsset"]["properties"]["mediaType"]["enum"] + ) + == contract.ALLOWED_PRESENTATION_MEDIA_TYPES + ) def test_manifest_walkthrough_covers_every_documented_scenario() -> None: @@ -168,7 +244,7 @@ def test_documented_manifest_protojson_matches_conformance_fixtures() -> None: Draft202012Validator(_SCHEMA).validate(response) -def test_response_round_trip_preserves_canonical_representation( +def test_response_round_trip_matches_canonical_representation( response, validator ) -> None: validator.validate(response) @@ -194,6 +270,184 @@ def test_response_round_trip_preserves_canonical_representation( ) +def test_provider_presentation_fixture_validates_and_round_trips() -> None: + document = json.loads( + (_FIXTURES / "presentation-response.json").read_text() + ) + Draft202012Validator(_SCHEMA).validate(document) + Draft202012Validator( + { + "$ref": "#/$defs/providerPresentation", + "$defs": _SCHEMA["$defs"], + } + ).validate(document["presentation"]) + + message = json_format.ParseDict( + document, + manifest_pb2.GetManifestResponse(), + ) + projected = json_format.MessageToDict( + message, + always_print_fields_with_no_presence=True, + ) + + assert projected == document + + +def test_presentation_is_outside_the_operational_manifest() -> None: + manifest_fields = manifest_pb2.ProviderManifest.DESCRIPTOR.fields_by_name + operation_fields = ( + manifest_pb2.OperationDeclaration.DESCRIPTOR.fields_by_name + ) + trigger_fields = manifest_pb2.TriggerDeclaration.DESCRIPTOR.fields_by_name + + assert "presentation" not in manifest_fields + assert "view" not in operation_fields + assert "view" not in trigger_fields + assert { + field.name: field.number + for field in manifest_pb2.GetManifestResponse.DESCRIPTOR.fields + } == { + "provider_instance_id": 1, + "endpoint_generation": 2, + "manifest_schema_version": 3, + "manifest_revision": 4, + "manifest": 5, + "session_id": 6, + "presentation": 7, + "presentation_revision": 8, + } + + +def test_presentation_contract_cannot_hide_or_redefine_fields() -> None: + component = manifest_pb2.ComponentNode.DESCRIPTOR.fields_by_name + renderer = manifest_pb2.RendererRequirement.DESCRIPTOR.fields_by_name + forbidden = { + "hidden", + "required", + "schema", + "default", + "html", + "css", + "javascript", + "url", + "path", + "executable", + "install_command", + } + + assert set(component) == { + "component_identifier", + "properties", + "bindings", + "children", + "fallback", + "condition", + "repeat", + "asset_bindings", + } + assert not forbidden & set(component) + assert not forbidden & set(renderer) + + +def test_presentation_is_not_part_of_operation_or_trigger_messages() -> None: + descriptors = ( + operation_admission_pb2.OperationInvocation.DESCRIPTOR, + operation_admission_pb2.StartOperationRequest.DESCRIPTOR, + trigger_publication_pb2.TriggerPublication.DESCRIPTOR, + trigger_publication_pb2.StreamTriggersResponse.DESCRIPTOR, + ) + + for descriptor in descriptors: + assert not { + "presentation", + "presentation_revision", + "view", + "asset", + } & set(descriptor.fields_by_name) + + +def test_presentation_changes_do_not_change_business_fingerprints() -> None: + operation = json_format.ParseDict( + json.loads( + ( + _FIXTURES.parent / "operation_admission" / "request.json" + ).read_text() + ), + operation_admission_pb2.StartOperationRequest(), + ).invocation + publication = json_format.ParseDict( + json.loads( + ( + _FIXTURES.parent / "trigger_publication" / "publication.json" + ).read_text() + ), + trigger_publication_pb2.StreamTriggersResponse(), + ).publication + operation_fingerprint = admission_validation.compute_request_fingerprint( + operation + ) + trigger_fingerprint = ( + trigger_validation.compute_publication_content_fingerprint(publication) + ) + + manifest_response = json_format.ParseDict( + json.loads((_FIXTURES / "presentation-response.json").read_text()), + manifest_pb2.GetManifestResponse(), + ) + manifest_response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root.properties.update({"gap": "changed"}) + + assert ( + admission_validation.compute_request_fingerprint(operation) + == operation_fingerprint + ) + assert ( + trigger_validation.compute_publication_content_fingerprint(publication) + == trigger_fingerprint + ) + + +@pytest.mark.parametrize( + ("target", "field", "value"), + [ + ("component", "hidden", True), + ("component", "javascript", "alert(1)"), + ("renderer", "url", "https://example.invalid/renderer"), + ("renderer", "executable", "payload"), + ("asset", "url", "https://example.invalid/icon.svg"), + ("asset", "path", "../../etc/passwd"), + ], +) +def test_presentation_protojson_rejects_executable_or_semantic_fields( + target: str, + field: str, + value: object, +) -> None: + document = json.loads( + (_FIXTURES / "presentation-response.json").read_text() + )["presentation"] + if target == "component": + operation = next(iter(document["operations"].values())) + selected = operation["surfaces"][contract.OPERATION_RESULT_SURFACE][ + "root" + ] + elif target == "renderer": + selected = next(iter(document["rendererRequirements"].values())) + else: + selected = next(iter(document["assets"].values())) + selected[field] = value + + with pytest.raises(ValidationError): + Draft202012Validator( + { + "$ref": "#/$defs/providerPresentation", + "$defs": _SCHEMA["$defs"], + } + ).validate(document) + + def test_request_round_trip_and_offer_order() -> None: request = manifest_pb2.GetManifestRequest( expected_provider_instance_id="7f7db7d8-68b4-4f71-9769-065b5c4f941c", diff --git a/tests/test_manifest_session_contract.py b/tests/test_manifest_session_contract.py index ae4bb22..484b139 100644 --- a/tests/test_manifest_session_contract.py +++ b/tests/test_manifest_session_contract.py @@ -58,7 +58,7 @@ def _round_trip(document, definition): ) -def test_envelope_additions_preserve_existing_field_numbers(): +def test_manifest_envelope_field_layout_is_exact(): for message, expected in [ ( manifest_pb2.GetManifestRequest, @@ -78,6 +78,8 @@ def test_envelope_additions_preserve_existing_field_numbers(): "manifest_revision": 4, "manifest": 5, "session_id": 6, + "presentation": 7, + "presentation_revision": 8, }, ), ]: @@ -149,9 +151,7 @@ def test_invalid_session_shapes_are_rejected(definition, field, value): ("getManifestResponse", "sessionId"), ], ) -def test_missing_or_defaulted_session_is_not_a_legacy_bypass( - definition, field -): +def test_missing_or_defaulted_session_is_invalid(definition, field): document = _fixture(definition) del document[field] with pytest.raises(ValidationError, match="required property"): @@ -216,7 +216,7 @@ def test_agent_rejects_wrong_or_superseded_response_session(case): assert matches == case["accept"] -def test_session_changes_preserve_exact_canonical_preimage_and_golden(): +def test_session_changes_do_not_change_canonical_manifest_revision(): response = _fixture("getManifestResponse") for session_id in ("manifest-session-A", "manifest-session-B"): response["sessionId"] = session_id diff --git a/tests/test_manifest_validation.py b/tests/test_manifest_validation.py index b3af666..ee1fadb 100644 --- a/tests/test_manifest_validation.py +++ b/tests/test_manifest_validation.py @@ -1,22 +1,32 @@ """Executable semantic-validation evidence for Provider Manifest v1.""" import copy +import hashlib import json +import struct +import zlib from pathlib import Path import pytest -from google.protobuf.json_format import ParseDict +from google.protobuf import struct_pb2 +from google.protobuf.json_format import MessageToDict, ParseDict from stateforge_protocol.sfp.manifest.v1 import contract, manifest_pb2 from stateforge_protocol.sfp.manifest.v1.validation import ( ManifestValidationError, ManifestValidationLimits, + PresentationValidationStatus, bounded_json, canonical_bytes, + canonical_presentation_bytes, compute_manifest_revision, + compute_presentation_revision, contract_validator, + validate_manifest_exchange, validate_manifest_key, validate_manifest_response, + validate_presentation_document, + validate_presentation_key, validate_schema, ) @@ -31,6 +41,140 @@ def _response() -> manifest_pb2.GetManifestResponse: return ParseDict(document, manifest_pb2.GetManifestResponse()) +def _presentation_response() -> manifest_pb2.GetManifestResponse: + document = json.loads( + (_FIXTURES / "presentation-response.json").read_text() + ) + return ParseDict(document, manifest_pb2.GetManifestResponse()) + + +def _project(message) -> dict[str, object]: + return MessageToDict( + message, + always_print_fields_with_no_presence=True, + ) + + +def _refresh_presentation_revision( + response: manifest_pb2.GetManifestResponse, +) -> None: + response.presentation_revision = compute_presentation_revision( + _project(response.presentation), + response.manifest_revision, + response.provider_instance_id, + ) + + +def _refresh_manifest_revision( + response: manifest_pb2.GetManifestResponse, +) -> None: + response.manifest_revision = compute_manifest_revision( + _project(response.manifest), + response.manifest_schema_version, + response.provider_instance_id, + ) + + +def _validate_presentation( + response: manifest_pb2.GetManifestResponse, +) -> bytes: + return validate_presentation_document( + response.presentation, + _project(response.manifest), + ) + + +def _png_chunk(kind: bytes, content: bytes) -> bytes: + checksum = zlib.crc32(kind) + checksum = zlib.crc32(content, checksum) & 0xFFFFFFFF + return ( + struct.pack(">I", len(content)) + + kind + + content + + struct.pack(">I", checksum) + ) + + +def _png_with_image_data( + image_data: bytes, + *, + width: int = 1, + height: int = 1, + interlace_method: int = 0, + split_at: int | None = None, +) -> bytes: + header = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0) + header = header[:-1] + bytes([interlace_method]) + if split_at is None: + data_chunks = (_png_chunk(b"IDAT", image_data),) + else: + data_chunks = ( + _png_chunk(b"IDAT", image_data[:split_at]), + _png_chunk(b"IDAT", image_data[split_at:]), + ) + return ( + b"\x89PNG\r\n\x1a\n" + + _png_chunk(b"IHDR", header) + + b"".join(data_chunks) + + _png_chunk(b"IEND", b"") + ) + + +def _png(width: int = 1, height: int = 1) -> bytes: + pixels = b"".join( + b"\x00" + (b"\x00\x00\x00\x00" * width) for _ in range(height) + ) + return _png_with_image_data( + zlib.compress(pixels), + width=width, + height=height, + ) + + +def _replace_provider_icon( + response: manifest_pb2.GetManifestResponse, + *, + content: bytes, + media_type: str, + width: int, + height: int, +) -> str: + image = _provider_image(response) + old_digest = image.asset_bindings["source"] + del response.presentation.assets[old_digest] + digest = "sha256:" + hashlib.sha256(content).hexdigest() + response.presentation.assets[digest].CopyFrom( + manifest_pb2.PresentationAsset( + media_type=media_type, + content=content, + width=width, + height=height, + alt_text="Provider icon", + ) + ) + image.asset_bindings["source"] = digest + return digest + + +def _provider_image( + response: manifest_pb2.GetManifestResponse, +) -> manifest_pb2.ComponentNode: + return response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root.children[0] + + +def _operation_root( + response: manifest_pb2.GetManifestResponse, + surface: str, +) -> manifest_pb2.ComponentNode: + return ( + response.presentation.operations["stateforge.git/reference.resolve@1"] + .surfaces[surface] + .root + ) + + def _schema(**overrides): return { "$schema": "https://json-schema.org/draft/2020-12/schema", @@ -57,6 +201,909 @@ def test_validates_and_canonicalizes_the_cross_language_vector() -> None: ) +def test_accepts_complete_provider_presentation_snapshot() -> None: + response = _presentation_response() + + exchange = validate_manifest_exchange(response) + + expected = json.loads( + (_FIXTURES / "presentation-response.json").read_text() + ) + assert ( + exchange.presentation_status is PresentationValidationStatus.ACCEPTED + ) + assert json.loads(exchange.manifest_document) == expected["manifest"] + assert ( + json.loads(exchange.presentation_document or b"") + == expected["presentation"] + ) + assert exchange.presentation_key is not None + assert exchange.presentation_key.revision == response.presentation_revision + assert ( + exchange.presentation_key.manifest_revision + == response.manifest_revision + ) + + +def test_absent_presentation_uses_schema_derived_rendering() -> None: + exchange = validate_manifest_exchange(_response()) + + assert exchange.presentation_status is PresentationValidationStatus.ABSENT + assert exchange.presentation_key is None + assert exchange.presentation_document is None + + +def test_empty_presentation_overlay_is_valid() -> None: + response = _presentation_response() + response.presentation.ClearField("provider") + response.presentation.ClearField("operations") + response.presentation.ClearField("triggers") + response.presentation.ClearField("assets") + response.presentation.ClearField("renderer_requirements") + _refresh_presentation_revision(response) + + exchange = validate_manifest_exchange(response) + + assert ( + exchange.presentation_status is PresentationValidationStatus.ACCEPTED + ) + assert json.loads(exchange.presentation_document or b"") == { + "assets": {}, + "operations": {}, + "presentationSchemaVersion": 1, + "rendererRequirements": {}, + "triggers": {}, + } + + +def test_invalid_presentation_falls_back_without_rejecting_manifest() -> None: + response = _presentation_response() + _operation_root(response, contract.OPERATION_REQUEST_SURFACE).bindings[ + "schema" + ].source_identifier = contract.PROVIDER_RUNTIME_BINDING + _refresh_presentation_revision(response) + + exchange = validate_manifest_exchange(response) + + assert exchange.presentation_status is PresentationValidationStatus.INVALID + assert exchange.presentation_document is None + assert exchange.presentation_key is None + assert exchange.manifest_document == validate_manifest_response(response) + + +@pytest.mark.parametrize( + ("schema_version", "status"), + [ + (0, PresentationValidationStatus.INVALID), + (2, PresentationValidationStatus.UNSUPPORTED), + ], +) +def test_unknown_or_invalid_presentation_versions_fall_back( + schema_version: int, + status: PresentationValidationStatus, +) -> None: + response = _presentation_response() + response.presentation.presentation_schema_version = schema_version + + exchange = validate_manifest_exchange(response) + + assert exchange.presentation_status is status + assert exchange.presentation_document is None + + +def test_presentation_and_revision_presence_must_agree() -> None: + absent = _response() + absent.presentation_revision = "sha256:" + ("a" * 64) + explicitly_empty = _response() + explicitly_empty.presentation_revision = "" + present = _presentation_response() + present.ClearField("presentation_revision") + + assert ( + validate_manifest_exchange(absent).presentation_status + is PresentationValidationStatus.INVALID + ) + assert ( + validate_manifest_exchange(explicitly_empty).presentation_status + is PresentationValidationStatus.INVALID + ) + assert ( + validate_manifest_exchange(present).presentation_status + is PresentationValidationStatus.INVALID + ) + + +def test_presentation_revision_mismatch_falls_back() -> None: + response = _presentation_response() + response.presentation_revision = "sha256:" + ("0" * 64) + + exchange = validate_manifest_exchange(response) + + assert exchange.presentation_status is PresentationValidationStatus.INVALID + + +def test_presentation_revision_is_isolated_and_bound_to_manifest() -> None: + response = _presentation_response() + original_manifest_revision = response.manifest_revision + original_presentation_revision = response.presentation_revision + + response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root.properties.update({"gap": "compact"}) + _refresh_presentation_revision(response) + + assert response.manifest_revision == original_manifest_revision + assert response.presentation_revision != original_presentation_revision + assert ( + validate_manifest_exchange(response).presentation_status + is PresentationValidationStatus.ACCEPTED + ) + + presentation_revision = response.presentation_revision + response.manifest.display_name = "Renamed Git Provider" + _refresh_manifest_revision(response) + _refresh_presentation_revision(response) + + assert response.manifest_revision != original_manifest_revision + assert response.presentation_revision != presentation_revision + assert ( + validate_manifest_exchange(response).presentation_status + is PresentationValidationStatus.ACCEPTED + ) + + +def test_presentation_key_validates_the_complete_revision_identity() -> None: + response = _presentation_response() + + key = validate_presentation_key( + response.provider_instance_id, + response.manifest_revision, + response.presentation.presentation_schema_version, + response.presentation_revision, + ) + + assert str(key.provider_instance_id) == response.provider_instance_id + assert key.manifest_revision == response.manifest_revision + assert key.schema_version == contract.PRESENTATION_SCHEMA_VERSION + assert key.revision == response.presentation_revision + + +@pytest.mark.parametrize( + ("field", "value", "message"), + [ + ("provider", "not-a-uuid", "provider identity"), + ("manifest", "not-a-revision", "manifest revision"), + ("schema", 2, "schema version"), + ("presentation", "not-a-revision", "revision is invalid"), + ], +) +def test_presentation_key_rejects_invalid_identity_parts( + field: str, + value: str | int, + message: str, +) -> None: + response = _presentation_response() + arguments: dict[str, str | int] = { + "provider": response.provider_instance_id, + "manifest": response.manifest_revision, + "schema": response.presentation.presentation_schema_version, + "presentation": response.presentation_revision, + } + arguments[field] = value + + with pytest.raises(ManifestValidationError, match=message): + validate_presentation_key( + str(arguments["provider"]), + str(arguments["manifest"]), + int(arguments["schema"]), + str(arguments["presentation"]), + ) + + +def test_presentation_revision_requires_a_manifest_revision() -> None: + response = _presentation_response() + + with pytest.raises(ManifestValidationError, match="manifest revision"): + compute_presentation_revision( + _project(response.presentation), + "not-a-revision", + response.provider_instance_id, + ) + + +def test_public_presentation_validator_projects_its_own_message() -> None: + response = _presentation_response() + manifest = _project(response.manifest) + + document = validate_presentation_document( + response.presentation, + manifest, + ) + + assert document == canonical_presentation_bytes( + _project(response.presentation) + ) + + +@pytest.mark.parametrize("collection", ["operations", "triggers"]) +def test_targets_cannot_name_undeclared_capabilities(collection: str) -> None: + response = _presentation_response() + targets = getattr(response.presentation, collection) + declared_identifier = next(iter(targets)) + targets["example.invalid/not_declared@1"].CopyFrom( + targets[declared_identifier] + ) + + with pytest.raises( + ManifestValidationError, + match=f"{collection[:-1]} target does not name a declared", + ): + _validate_presentation(response) + + +def test_surface_must_belong_to_its_target_kind() -> None: + response = _presentation_response() + target = response.presentation.provider + target.surfaces[contract.OPERATION_REQUEST_SURFACE].CopyFrom( + target.surfaces[contract.PROVIDER_OVERVIEW_SURFACE] + ) + + with pytest.raises(ManifestValidationError, match="provider targets"): + _validate_presentation(response) + + +def test_surface_binding_source_must_be_available() -> None: + response = _presentation_response() + _operation_root(response, contract.OPERATION_REQUEST_SURFACE).bindings[ + "schema" + ].source_identifier = contract.OPERATION_RESULT_VALUE_BINDING + + with pytest.raises(ManifestValidationError, match="unavailable"): + _validate_presentation(response) + + +def test_raw_operation_request_values_are_not_presentation_sources() -> None: + response = _presentation_response() + result = _operation_root( + response, contract.OPERATION_RESULT_SURFACE + ).fallback + result.bindings[ + "secret" + ].source_identifier = "stateforge.binding/operation.request.value@1" + result.bindings["secret"].pointer = "/token" + + with pytest.raises(ManifestValidationError, match="unavailable"): + _validate_presentation(response) + + +def test_public_request_projection_is_available_across_lifecycle() -> None: + expected = contract.OPERATION_REQUEST_PUBLIC_VALUE_BINDING + + for surface in ( + contract.OPERATION_REQUEST_SURFACE, + contract.OPERATION_RUN_SURFACE, + contract.OPERATION_RESULT_SURFACE, + ): + assert expected in contract.SURFACE_BINDING_SOURCES[surface] + + assert all( + "stateforge.binding/operation.request.value@1" not in sources + for sources in contract.SURFACE_BINDING_SOURCES.values() + ) + + +def test_core_component_catalog_is_explicit() -> None: + response = _presentation_response() + response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root.component_identifier = "stateforge.ui/layout.unknown@1" + + with pytest.raises(ManifestValidationError, match="unknown core"): + _validate_presentation(response) + + +def test_core_action_is_rejected_outside_its_operation_surface() -> None: + response = _presentation_response() + root = response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root + root.component_identifier = "stateforge.ui/action.operation_submit@1" + + with pytest.raises(ManifestValidationError, match="unavailable"): + _validate_presentation(response) + + +def test_core_leaf_component_rejects_children() -> None: + response = _presentation_response() + image = _provider_image(response) + child = image.children.add( + component_identifier="stateforge.ui/content.text@1" + ) + child.properties.CopyFrom(struct_pb2.Struct()) + + with pytest.raises(ManifestValidationError, match="child contract"): + _validate_presentation(response) + + +def test_core_component_requires_its_binding_slots() -> None: + response = _presentation_response() + event = next(iter(response.presentation.triggers.values())) + event.surfaces[contract.TRIGGER_EVENT_SURFACE].root.ClearField("bindings") + + with pytest.raises(ManifestValidationError, match="required binding"): + _validate_presentation(response) + + +def test_core_component_rejects_unknown_binding_slots() -> None: + response = _presentation_response() + image = _provider_image(response) + image.bindings[ + "value" + ].source_identifier = contract.PROVIDER_MANIFEST_BINDING + + with pytest.raises(ManifestValidationError, match="binding slot"): + _validate_presentation(response) + + +def test_core_input_schema_slot_rejects_value_sources() -> None: + response = _presentation_response() + request = _operation_root(response, contract.OPERATION_REQUEST_SURFACE) + request.bindings[ + "schema" + ].source_identifier = contract.OPERATION_REQUEST_PUBLIC_VALUE_BINDING + + with pytest.raises(ManifestValidationError, match="component slot"): + _validate_presentation(response) + + +def test_core_media_component_requires_its_asset_slot() -> None: + response = _presentation_response() + _provider_image(response).ClearField("asset_bindings") + + with pytest.raises(ManifestValidationError, match="required asset"): + _validate_presentation(response) + + +def test_core_component_cannot_declare_a_fallback() -> None: + response = _presentation_response() + root = response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root + root.fallback.component_identifier = "stateforge.ui/content.text@1" + root.fallback.properties.CopyFrom(struct_pb2.Struct()) + + with pytest.raises(ManifestValidationError, match="cannot declare"): + _validate_presentation(response) + + +def test_secret_input_is_part_of_the_portable_core_catalog() -> None: + secret = contract.CORE_COMPONENT_CONTRACTS["stateforge.ui/input.secret@1"] + + assert secret.required_bindings == frozenset({"schema"}) + assert "value" not in secret.optional_bindings + + +@pytest.mark.parametrize( + ("identifier", "required_bindings"), + [ + ("stateforge.ui/data.table@1", {"rows"}), + ("stateforge.ui/data.diff@1", {"before", "after"}), + ("stateforge.ui/data.log@1", {"entries"}), + ("stateforge.ui/status.timeline@1", {"events"}), + ("stateforge.ui/data.chart@1", {"series"}), + ("stateforge.ui/data.topology@1", {"nodes", "edges"}), + ("stateforge.ui/data.artifacts@1", {"items"}), + ], +) +def test_core_data_components_have_semantic_binding_slots( + identifier: str, + required_bindings: set[str], +) -> None: + component = contract.CORE_COMPONENT_CONTRACTS[identifier] + + assert component.required_bindings == frozenset(required_bindings) + + +def test_custom_component_requires_renderer_metadata() -> None: + response = _presentation_response() + del response.presentation.renderer_requirements["example.git"] + + with pytest.raises(ManifestValidationError, match="renderer requirement"): + _validate_presentation(response) + + +def test_custom_component_requires_core_fallback() -> None: + response = _presentation_response() + _operation_root(response, contract.OPERATION_RESULT_SURFACE).ClearField( + "fallback" + ) + + with pytest.raises(ManifestValidationError, match="core fallback"): + _validate_presentation(response) + + +def test_custom_component_fallback_cannot_require_an_extension() -> None: + response = _presentation_response() + _operation_root( + response, contract.OPERATION_RESULT_SURFACE + ).fallback.component_identifier = "example.git/data.commit_graph@1" + + with pytest.raises(ManifestValidationError, match="core components"): + _validate_presentation(response) + + +def test_renderer_requirements_cannot_be_unreferenced() -> None: + response = _presentation_response() + response.presentation.renderer_requirements["example.widget"].CopyFrom( + response.presentation.renderer_requirements["example.git"] + ) + requirement = response.presentation.renderer_requirements["example.widget"] + requirement.extension_identifier = "example.widget/renderer@1" + + with pytest.raises(ManifestValidationError, match="exactly match"): + _validate_presentation(response) + + +def test_renderer_extension_must_share_component_namespace() -> None: + response = _presentation_response() + response.presentation.renderer_requirements[ + "example.git" + ].extension_identifier = "example.widget/renderer@1" + + with pytest.raises(ManifestValidationError, match="namespace"): + _validate_presentation(response) + + +@pytest.mark.parametrize( + "identifier", + [ + "stateforge.git/data.commit_graph@1", + "stateforge.ui.custom/data.commit_graph@1", + ], +) +def test_custom_components_cannot_claim_stateforge_namespaces( + identifier: str, +) -> None: + response = _presentation_response() + _operation_root( + response, contract.OPERATION_RESULT_SURFACE + ).component_identifier = identifier + + with pytest.raises(ManifestValidationError, match="StateForge-owned"): + _validate_presentation(response) + + +def test_renderer_requirements_cannot_claim_stateforge_namespaces() -> None: + response = _presentation_response() + reserved = response.presentation.renderer_requirements["stateforge.git"] + reserved.CopyFrom( + response.presentation.renderer_requirements["example.git"] + ) + reserved.extension_identifier = "stateforge.git/renderer@1" + del response.presentation.renderer_requirements["example.git"] + + with pytest.raises(ManifestValidationError, match="StateForge-owned"): + _validate_presentation(response) + + +def test_repetition_scope_is_available_to_component_bindings() -> None: + response = _presentation_response() + root = response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root + repeated = root.children.add( + component_identifier="stateforge.ui/data.table@1" + ) + repeated.properties.update({"title": "Runtime items"}) + repeated.repeat.collection.CopyFrom( + manifest_pb2.DataBinding( + source_identifier=contract.PROVIDER_RUNTIME_BINDING, + pointer="/items", + ) + ) + repeated.repeat.item_scope = "row" + repeated.repeat.max_items = 100 + repeated.bindings["rows"].CopyFrom( + manifest_pb2.DataBinding( + source_identifier=contract.REPETITION_ITEM_BINDING, + pointer="/name", + scope="row", + ) + ) + + _validate_presentation(response) + + +def test_repetition_item_binding_requires_an_active_scope() -> None: + response = _presentation_response() + root = response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root + root.bindings["item"].CopyFrom( + manifest_pb2.DataBinding( + source_identifier=contract.REPETITION_ITEM_BINDING, + scope="missing", + ) + ) + + with pytest.raises(ManifestValidationError, match="active scope"): + _validate_presentation(response) + + +def test_non_repetition_binding_cannot_claim_a_scope() -> None: + response = _presentation_response() + _operation_root(response, contract.OPERATION_REQUEST_SURFACE).bindings[ + "schema" + ].scope = "row" + + with pytest.raises(ManifestValidationError, match="may name a scope"): + _validate_presentation(response) + + +@pytest.mark.parametrize( + ("operator", "with_value", "message"), + [ + ( + manifest_pb2.CONDITION_OPERATOR_EXISTS, + True, + "cannot declare a value", + ), + ( + manifest_pb2.CONDITION_OPERATOR_EQUALS, + False, + "requires a value", + ), + ], +) +def test_condition_value_presence_matches_operator( + operator: int, + with_value: bool, + message: str, +) -> None: + response = _presentation_response() + root = response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root + root.condition.binding.CopyFrom( + manifest_pb2.DataBinding( + source_identifier=contract.PROVIDER_RUNTIME_BINDING, + pointer="/available", + ) + ) + root.condition.operator = operator + if with_value: + root.condition.value.bool_value = True + + with pytest.raises(ManifestValidationError, match=message): + _validate_presentation(response) + + +def test_component_properties_have_an_independent_byte_limit() -> None: + response = _presentation_response() + response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root.properties.update( + {"content": "x" * contract.MAX_COMPONENT_PROPERTIES_BYTES} + ) + + with pytest.raises(ManifestValidationError, match="properties limit"): + _validate_presentation(response) + + +def test_component_tree_depth_is_bounded() -> None: + response = _presentation_response() + node = response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root + for depth in range(contract.MAX_PRESENTATION_COMPONENT_DEPTH): + node = node.children.add( + component_identifier="stateforge.ui/layout.section@1" + ) + node.properties.update({"depth": depth}) + + with pytest.raises(ManifestValidationError, match="depth limit"): + _validate_presentation(response) + + +def test_bounded_static_png_asset_is_accepted() -> None: + response = _presentation_response() + _replace_provider_icon( + response, + content=_png(2, 3), + media_type="image/png", + width=2, + height=3, + ) + _refresh_presentation_revision(response) + + exchange = validate_manifest_exchange(response) + + assert ( + exchange.presentation_status is PresentationValidationStatus.ACCEPTED + ) + + +def test_asset_reference_must_resolve() -> None: + response = _presentation_response() + del response.presentation.assets[ + _provider_image(response).asset_bindings["source"] + ] + + with pytest.raises(ManifestValidationError, match="reference is missing"): + _validate_presentation(response) + + +def test_unreferenced_assets_are_rejected() -> None: + response = _presentation_response() + content = _png() + digest = "sha256:" + hashlib.sha256(content).hexdigest() + response.presentation.assets[digest].CopyFrom( + manifest_pb2.PresentationAsset( + media_type="image/png", + content=content, + width=1, + height=1, + alt_text="Unreferenced image", + ) + ) + + with pytest.raises(ManifestValidationError, match="unreferenced asset"): + _validate_presentation(response) + + +def test_asset_digest_must_match_exact_bytes() -> None: + response = _presentation_response() + digest = _provider_image(response).asset_bindings["source"] + response.presentation.assets[digest].content += b"changed" + + with pytest.raises(ManifestValidationError, match="digest mismatch"): + _validate_presentation(response) + + +def test_asset_size_limit_is_enforced() -> None: + response = _presentation_response() + _replace_provider_icon( + response, + content=b"x" * (contract.MAX_PRESENTATION_ASSET_BYTES + 1), + media_type="image/png", + width=1, + height=1, + ) + + with pytest.raises(ManifestValidationError, match="byte limit"): + _validate_presentation(response) + + +def test_aggregate_asset_size_limit_is_enforced() -> None: + response = _presentation_response() + response.presentation.ClearField("assets") + references: list[str] = [] + for index in range(5): + content = bytes([index]) + ( + b"x" * (contract.MAX_PRESENTATION_ASSET_BYTES - 1) + ) + digest = "sha256:" + hashlib.sha256(content).hexdigest() + response.presentation.assets[digest].CopyFrom( + manifest_pb2.PresentationAsset( + media_type="image/svg+xml", + content=content, + width=1, + height=1, + alt_text="Visual", + ) + ) + references.append(digest) + root = response.presentation.provider.surfaces[ + contract.PROVIDER_OVERVIEW_SURFACE + ].root + root.ClearField("children") + for index, digest in enumerate(references): + image = root.children.add( + component_identifier="stateforge.ui/media.image@1" + ) + image.properties.update({"index": index}) + image.asset_bindings["source"] = digest + + with pytest.raises(ManifestValidationError, match="aggregate asset"): + _validate_presentation(response) + + +def test_raster_media_type_and_dimensions_must_match_content() -> None: + response = _presentation_response() + _replace_provider_icon( + response, + content=_png(), + media_type="image/png", + width=2, + height=1, + ) + + with pytest.raises(ManifestValidationError, match="dimensions"): + _validate_presentation(response) + + response = _presentation_response() + _replace_provider_icon( + response, + content=b"not a PNG", + media_type="image/png", + width=1, + height=1, + ) + with pytest.raises(ManifestValidationError, match="invalid PNG"): + _validate_presentation(response) + + +def test_png_crc_and_chunk_allowlist_are_enforced() -> None: + response = _presentation_response() + invalid_crc = bytearray(_png()) + invalid_crc[-1] ^= 0xFF + _replace_provider_icon( + response, + content=bytes(invalid_crc), + media_type="image/png", + width=1, + height=1, + ) + with pytest.raises(ManifestValidationError, match="invalid PNG"): + _validate_presentation(response) + + +@pytest.mark.parametrize( + "image_data", + [ + b"not a zlib stream", + zlib.compress(b"\x00\x00\x00\x00\x00")[:-1], + zlib.compress(b"\x00\x00\x00\x00\x00") + b"trailing", + zlib.compress(b"\x00\x00\x00\x00\x00\x00"), + zlib.compress(b"\x05\x00\x00\x00\x00"), + ], +) +def test_png_image_data_must_decode_to_exact_scanlines( + image_data: bytes, +) -> None: + response = _presentation_response() + _replace_provider_icon( + response, + content=_png_with_image_data(image_data), + media_type="image/png", + width=1, + height=1, + ) + + with pytest.raises(ManifestValidationError, match="invalid PNG"): + _validate_presentation(response) + + +def test_png_consecutive_idat_chunks_form_one_valid_stream() -> None: + response = _presentation_response() + image_data = zlib.compress(b"\x00\x00\x00\x00\x00") + _replace_provider_icon( + response, + content=_png_with_image_data( + image_data, + split_at=len(image_data) // 2, + ), + media_type="image/png", + width=1, + height=1, + ) + + _validate_presentation(response) + + +def test_png_adam7_scanline_layout_is_accepted() -> None: + response = _presentation_response() + _replace_provider_icon( + response, + content=_png_with_image_data( + zlib.compress(b"\x00\x00\x00\x00\x00"), + interlace_method=1, + ), + media_type="image/png", + width=1, + height=1, + ) + + _validate_presentation(response) + + +def test_png_decoded_size_is_bounded_before_decompression() -> None: + response = _presentation_response() + _replace_provider_icon( + response, + content=_png_with_image_data( + zlib.compress(b""), + width=contract.MAX_PRESENTATION_ASSET_DIMENSION, + height=contract.MAX_PRESENTATION_ASSET_DIMENSION, + ), + media_type="image/png", + width=contract.MAX_PRESENTATION_ASSET_DIMENSION, + height=contract.MAX_PRESENTATION_ASSET_DIMENSION, + ) + + with pytest.raises(ManifestValidationError, match="invalid PNG"): + _validate_presentation(response) + + +@pytest.mark.parametrize( + "content", + [ + _png(0, 1), + _png()[:33] + _png()[8:33] + _png()[33:], + _png()[:33] + _png_chunk(b"IEND", b""), + _png()[:-12], + ], +) +def test_png_structure_is_enforced(content: bytes) -> None: + response = _presentation_response() + _replace_provider_icon( + response, + content=content, + media_type="image/png", + width=1, + height=1, + ) + + with pytest.raises(ManifestValidationError, match="invalid PNG"): + _validate_presentation(response) + + response = _presentation_response() + png = _png() + unsafe_chunk = b"\x00\x00\x00\x00tEXt" + struct.pack( + ">I", zlib.crc32(b"tEXt") & 0xFFFFFFFF + ) + content = png[:-12] + unsafe_chunk + png[-12:] + _replace_provider_icon( + response, + content=content, + media_type="image/png", + width=1, + height=1, + ) + with pytest.raises(ManifestValidationError, match="invalid PNG"): + _validate_presentation(response) + + +@pytest.mark.parametrize( + "content", + [ + b"", + b'', + b'', + b'', + b']>', + b'', + b'', + ], +) +def test_svg_executable_or_external_content_is_rejected_without_echo( + content: bytes, +) -> None: + response = _presentation_response() + _replace_provider_icon( + response, + content=content, + media_type="image/svg+xml", + width=1, + height=1, + ) + + with pytest.raises(ManifestValidationError) as error: + _validate_presentation(response) + + assert content.decode() not in str(error.value) + + +def test_media_allowlist_is_enforced() -> None: + response = _presentation_response() + digest = _provider_image(response).asset_bindings["source"] + response.presentation.assets[digest].media_type = "text/html" + + with pytest.raises(ManifestValidationError, match="enum constraint"): + _validate_presentation(response) + + def test_public_contract_validator_uses_the_packaged_schema() -> None: validator = contract_validator("schemaDocument")