Skip to content

Latest commit

 

History

History
190 lines (150 loc) · 9.21 KB

IR_SPEC.md

File metadata and controls

190 lines (150 loc) · 9.21 KB

PolyAPI canonical IR specification v2 and auth v3

Status: draft. The media identifier is polyapi.ir/v2. This is the only input backend generators should consume after the source frontend is implemented. The password-session authentication contract uses the breaking polyapi.ir/v3 form described in AUTH_PROFILE.md; an IR v2 document cannot claim that profile.

Design

The IR is typed, ordered, language-neutral, and close to SSA. Values use %name identifiers and are defined before use. Instructions retain high-level operations such as record construction and integer summation so every backend receives the same overflow and validation semantics.

The canonical JSON form uses UTF-8, no insignificant duplicate keys, and the field order shown by the schema encoder. A content digest is calculated over RFC 8785 JSON canonicalization. Source paths and spans belong in an optional source map and are excluded from a semantic digest.

The complete example is examples/quote/quote.ir.json. Example source, generated artifacts, host wiring, and deployment files are isolated together in that directory.

Top-level document

Field Meaning
format Exactly polyapi.ir/v2.
service Stable service name and positive API version.
labels Declared taint or sensitivity labels.
proofs Declared contextual guarantees.
types Record definitions and constraints.
sanitizers Typed security transformations.
sinks Effect capabilities and per-argument policy.
stores Persistent providers, typed envelopes, write sinks, replay labels, and stable failures.
endpoints Transport contracts and ordered instructions.

Unknown fields and unknown operation names are errors. Consumers must not apply "best effort" behavior to a newer IR.

Authentication v3

An auth v3 document retains the common service/label/proof fields, requires the generic v2 type/sanitizer/sink/store/endpoint arrays to be empty, and contains one auth object. That object freezes the exact password-session profile, Postgres tables, policy bounds, routes, intrinsic registry, source/sink contract, compatible target set, and ordered operation graph.

The password policy includes an exact hash_bytes field. Profile 0.1 requires 32; omitting or changing it is an IR downgrade error. Every emitter and the Postgres PHC constraint derive their hash length from that canonical field, preventing target-specific defaults from silently diverging.

The target set is exactly Go, Python, Rust, Java, and Postgres. The operation graph is compiler-owned and binds each route's strict transport decode, normalization/KDF/session/database steps, failure codes, and terminal response sink. Reordering or removing a step, changing a terminal sink, or dropping a target is invalid canonical IR. The checked example is examples/auth/auth.ir.json, and its strict schema is schema/polyapi-ir-v3.schema.json.

Instructions

Instructions execute in array order and have a unique id within an endpoint. Results are immutable and unique within the endpoint.

Operation Required data Semantics
param result, name, type Introduces a transport parameter.
source value, labels Adds security labels to an existing value.
sanitize result, input, sanitizer Applies a declared sanitizer contract.
let result, type, expr Evaluates a pure typed expression.
build result, type, fields Constructs a record with every required field.
sink sink, arguments Checks policy and performs/authorizes an effect.
persist result, store, input, value Authorizes the store sink, inserts/replays an immutable idempotent value, and returns the stored value.
return value Terminates with the endpoint response value.

Version 2 expressions are ref, const_i64, const_string, const_bool, project, add_i64, sub_i64, mul_i64, div_i64, and sum_i64. Binary integer expressions evaluate left then right using wrapping signed 64-bit arithmetic. sum_i64 binds its item only inside its nested expression.

Security state

The verifier tracks a state for each value:

State(value) = { labels: set<label>, proofs: set<proof>, provenance: source spans }

Transfer rules are deliberately conservative:

  • source unions its labels into the referenced value.
  • ref copies state.
  • project copies labels but drops proofs unless a future proof definition says it is projection-stable.
  • arithmetic, summation, and record construction union input labels and drop proofs.
  • sanitize copies input labels, removes only its declared removes, drops prior proofs, and establishes exactly its declared proves.
  • sink rejects an argument containing a forbidden label or missing a required proof.
  • persist first applies its store's database.persist sink policy to input and value. Its result unions their labels, adds replay_labels, and drops all proofs because the returned row may predate the current execution.

The compiler must report the sink, parameter, label/proof, value, and source provenance when rejecting a flow.

Sources

Sources are explicit instructions rather than naming conventions. HTTP bodies, headers, query values, database reads, environment variables, files, queues, and secrets can therefore be modeled without baking a framework into the IR.

Sanitizers

Sanitizer declarations contain input/output types, an intrinsic identifier, labels removed, proofs established, and a stable failure code. A backend has an implementation registry keyed by intrinsic. Compilation fails if any selected backend lacks a semantically equivalent intrinsic.

IR v2 permits only the compiler-owned schema.validate intrinsic. It requires identical input/output types, preserves every label, forbids removes, and establishes one or more declared schema proofs. Sanitizer declarations select that behavior; they do not define it. Unknown intrinsics, type-changing schema validators, empty proof sets, and any v2 label removal are errors.

Sinks

Sinks name an effect capability such as http.response, process.exec, database.query, filesystem.write, or network.request. Policy belongs to individual parameters because a command executable, argument, environment, and stdin have different requirements.

A sink instruction must provide exactly the declared parameters. The verifier runs before backend emission, and the backend must map the capability to a known implementation. No backend can silently downgrade a missing proof to a warning.

Every v2 endpoint has exactly one http.response authorization immediately before return. That sink has exactly one body parameter of the endpoint response type, and return must reference that same SSA value. Authorizing a safe value and returning a different secret-bearing value is therefore invalid IR.

Stores

A v2 store has id, provider, table, key_field, input_type, value_type, sink, replay_labels, conflict_error, and unavailable_error. Version 2 recognizes only postgres. The key is a required string field of the input record, and the referenced sink must have capability database.persist with exact parameters input and value matching the store.

The canonical IR does not name GORM, SQLAlchemy, SeaORM, or Hibernate. Those are target profiles implementing the same store operation. Postgres envelope, idempotency, migration, and cross-language rules are specified in POSTGRES_PROFILE.md.

Validation phases

The compiler performs these passes in order:

  1. Decode with unknown-field rejection.
  2. Validate format, identifiers, uniqueness, and declarations.
  3. Resolve type references, intrinsics, capabilities, stores, labels, and proofs.
  4. Validate value definition/use order and expression types.
  5. Run source/sanitizer/sink flow verification.
  6. Confirm every selected backend supports every used intrinsic and capability.
  7. Emit target ASTs and print source deterministically.
  8. Run differential conformance tests against the canonical behavior corpus.

Backend compatibility

The Tree-sitter frontend lowers .poly directly into this IR. New semantic features are specified in .poly and polyapi.ir/v2 first; backend-specific shortcuts are not added to the source language. The current Go and Python string emitters use a narrow internal adapter while target AST printers are built, but backend selection and security verification already occur on canonical IR.

Generic IR v2 deliberately contains no selected-target list and no Go, Python, Rust, or Java framework names. Target selection is a compiler invocation concern. The stable backend target identities and compatibility contract are defined in BACKEND_PROFILE.md. Before emission, each selected target must prove support for all IR types, operations, sanitizer intrinsics, sink capabilities, store providers, transport features, and integer semantics used by the document. Auth IR v3 is stricter: its fixed compatibility set records every target required by the profile so a partial auth implementation cannot be mistaken for a conforming build.