# OIP-Book **Repository Path**: cheneychen650D/OIP-Book ## Basic Information - **Project Name**: OIP-Book - **Description**: OIP-Book是奥集能开放架构的 中心化认证服务端,承载 OIP 协议核心实现——所有权利的签发、转移、验证、撤销、合规检查均在 OIP-Book中完成。OIP-Book全局唯一部署,所有 GoInOne节点共享同一个 OIP-Book完成认证、权限查询和 OIP 协议操作。 - **Primary Language**: Rust - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 7 - **Created**: 2026-11-12 - **Last Updated**: 2026-11-25 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # OIP-Book · Rights State Machine Layer Service > **Document version**: v1.1 | **Updated**: 2026-09-26 | **Status**: Released > **Related**: [OIP-Book-Design.md](../OIP/docs/OIP-Book-Design.md) · [OIP-Protocol.md](../OIP/docs/OIP-Protocol.md) · [OIP.md](../OIP/docs/OIP.md) `OIP-Book` is the **centralized authentication service** of the Open Interconnect Protocol (OIP) and hosts the OIP protocol core — the L3 Rights State Machine Layer. Issuance, transfer, verification, revocation and compliance checks of all entitlements are performed in `OIP-Book`; `OIP-Book` is deployed exactly once and shared by all `OIP-GoInOne` nodes for authentication, permission queries and OIP protocol operations. > Rust implementation (edition 2024; axum + tokio + serde + ed25519-dalek + mongodb + redis + async-nats + tokio-postgres), aligned with [OIP-Book-Design.md](../OIP/docs/OIP-Book-Design.md) in the OIP specification repository. ## Core Capabilities | Capability | Description | | --- | --- | | Verifiable Entitlement Token (VET) lifecycle state machine | Seven states Issued/Active/Transferred/Consumed/Expired/Revoked/Dead with checked transitions | | Policy Decision Point (PDP) staged pipeline | lifecycle → signature → operation-set → nonce → delegation → constraints → object → device → decision; every rejection returns the same `OIP_4031` (boolean blindness) | | Four transfer laws | Override / Workflow / Exchange / Collaboration, incl. workflow approval and lock-commit | | Delegation Chain | Delegation policy checks (shrink, depth) and cascade revocation | | Merkle Audit Tree | append / root / proof / verify, sorted-pair hashing for determinism | | Compliance engine | Sanctions list + GDPR cross-border data-subject checks (DPIA) | | Global Circuit Breaker | Triggered when `force_level` ≥ `breaker.force_threshold` (default 250); HSM-signed regulator commands | | Decentralized Identifier (DID) management | Registration and status management (Active / Suspended / Deactivated) | | Ed25519 signing | VET issuance and delegation-chain verification (canonical payload) | | Storage abstraction | **PostgreSQL (`store.mode=postgres`)** / MongoDB (`store.mode=mongo`) / in-memory (`store.mode=memory`, tests); the sharing plane additionally supports **MySQL (`OIP_BOOK_ORG_STORE=mysql`)** | | Persistence coverage | With `postgres`: VET / org collaboration / Exchange locks / audit + Merkle roots / workflow / sync cursors / third-party bindings / outbox all persisted (account/password credentials are in-process storage for now; their PostgreSQL backend is a follow-up) | | Event bus | In-memory / NATS JetStream dual backends (`events.mode`) | | Outbox | Atomic dual-write of authoritative source and events + asynchronous relay; over-retry entries become dead letters and are never deleted | | Rate limiting | Token bucket (`src/ratelimit.rs`: Issue 100/s, Verify 1000/s, Revoke 10/s, Override 1/s), applied to the auth, VET issue/verify/revoke, Override transfer and data-share endpoints | | **Org collaboration** | Target/Team/Relation/Identity/Authority, normalized to DID entities / VET mappings per `OIP-Book-Design.md` §5B.2 | | **Workflow Admin** | Workflow administration (§5A.8): definition/instance/task/gateway management plane | | **System Auth** | Login-state endpoints (§5A.7): Login/Refresh/Logout/Challenge issuance plane | | **Account/password credentials (authority plane)** | Account registration / account-password login / password change / external-assertion exchange / OTP private-key custody (§5A.9 `QueryOtpPrivateKey`); credentials map 1:1 to DIDs, passwords stored as argon2 PHC | | **Node-to-node sync** | SyncSnapshot (§5B.7): DID/VET/audit/Merkle root/breaker full fallback + cursor-based incremental | | **Third-party account binding** | `vet/bind`, `vet/unbind`, `vet/bindings/:target_did` (§5A.10) | ## Quick Start ```bash # 1. Prepare config (see config.example.yaml) cp config.example.yaml config.yaml # Edit config.yaml: fill in store / events / hsm_key, etc. # 2. Build / Test / Lint cargo build --release --locked cargo fmt --all --check cargo clippy --all-targets -- -D warnings cargo test --all-targets # unit tests + tests/auth_issuance_contract.rs contract integration tests # 3. Run (override the config path with OIP_BOOK_CONFIG) OIP_BOOK_CONFIG=config.yaml cargo run ``` ## Environment Variables | Variable | Purpose | Default behaviour | | --- | --- | --- | | `OIP_BOOK_CONFIG` | Override the config file path | Uses `config.yaml` | | `OIP_BOOK_INTERNAL_TOKEN` | Enable the inbound internal token gate (≥16 chars) | Disabled when unset or empty | | `OIP_POSTGRES_URL` | PostgreSQL URL for `#[ignore]` integration cases | Cases print `skip` and return | | `OIP_REDIS_URL` | Redis URL for `#[ignore]` integration cases | Cases print `skip` and return | | `OIP_BOOK_DATABASE_URL` | PostgreSQL URL when `store.mode=postgres` (injected at deploy time; credentials never enter VCS) | Falls back to `store.database_url` | | `OIP_BOOK_ORG_STORE` | Override the **sharing plane** (org collaboration / workflow / private data) store mode (`memory`/`mongo`/`postgres`/`mysql`) | Falls back to `store.mode` | | `OIP_BOOK_MONGO_URI` | MongoDB URL when `OIP_BOOK_ORG_STORE=mongo` | Falls back to `store.mongo_uri` | | `OIP_BOOK_MYSQL_URL` | MySQL URL for the sharing plane (`OIP_BOOK_ORG_STORE=mysql`) | Falls back to `store.mysql_url` | | `OIP_BOOK_PRE_STOP_SECS` | Graceful-shutdown **drain window** in seconds (wait between marking not-ready and draining in-flight requests after `SIGTERM`/`SIGINT`) | `5` (`0` disables the wait) | ## Configuration Keys and Defaults `src/config.rs` parses strictly with `#[serde(deny_unknown_fields)]`; unknown keys are rejected. Defaults come from `src/config.rs`; the template is `config.example.yaml`. | Key | Default | Description | | --- | --- | --- | | `listen` | none (required) | HTTP listen address; the template uses `"0.0.0.0:8081"` | | `log_level` | `"info"` | tracing filter level | | `store.mode` | `"postgres"` | `memory` / `mongo` / `postgres`; selects where the **OIP-owned plane** (VET / audit / locks / outbox / DID / credentials / sync cursors / bindings) lives; unknown values fail explicitly in `AppState::from_config` (including `mysql` — MySQL only carries the sharing plane, and the error points the caller at `OIP_BOOK_ORG_STORE=mysql`). The default is the production-preferred `postgres`: a missing value **fails at startup** (no `store.database_url`) instead of silently degrading to `memory` | | `store.mongo_uri` | `""` | Required when `store.mode=mongo`, otherwise startup fails | | `store.redis_uri` | `""` | Required when `store.mode=mongo` (atomic nonce consumption), otherwise startup fails | | `store.database_url` | `""` | Required when `store.mode=postgres`, otherwise startup fails | | `store.mysql_url` | `""` | MySQL URL for the sharing plane (`mysql://user:pass@host:3306/relation`); required when `OIP_BOOK_ORG_STORE=mysql`, otherwise startup fails | | `events.mode` | `"memory"` | `memory` / `nats`; unknown values fail explicitly | | `events.nats_uri` | `""` | Required when `events.mode=nats`, otherwise startup fails | | `breaker.force_threshold` | `250` | `force_level` threshold that trips the global circuit breaker | | `hsm_key` | `null` | Base64-encoded Ed25519 private key used to verify regulator signatures (override / emergency breaker) | | `hsm_user_key` | `null` | Base64-encoded Ed25519 seed for the **user token domain** (access / refresh). One-domain-one-key: required in production and MUST differ from `hsm_key`; falls back to `hsm_key` in demo mode only. Env: `OIP_BOOK_HSM_USER_KEY` | | `hsm_user_key_previous` | `null` | Previous user-token key kept for verification only during the rotation window (= refresh TTL, 7 days). Env: `OIP_BOOK_HSM_USER_KEY_PREVIOUS` | | `demo_mode` | `false` | When `true`, startup is allowed without `hsm_key` (demo only); when `false`, startup is refused if `hsm_key` / `internal_token` is missing, or `hsm_user_key` is missing or equals `hsm_key` | ## Continuous Integration `.github/workflows/ci.yml` runs on push (`master`/`main`) and `pull_request` on `ubuntu-latest` with Rust `1.98.1` (including `rustfmt` and `clippy`), backed by service containers `postgres:16` (database `oip_test`) and `redis:7`: ```bash cargo fmt --all --check cargo clippy --all-targets -- -D warnings cargo test --all-targets cargo test --lib -- --ignored # PostgreSQL / Redis integration cases (service containers inject OIP_POSTGRES_URL, OIP_REDIS_URL) cargo build --release --locked ``` `.github/workflows/contract-check.yml` performs protocol-surface drift verification and is **fail-closed**: if `../OIP/tools/gen_protocol.py` is missing it first tries `git clone --depth 1 https://gitee.com/orginone/OIP.git ../OIP`; if the script is still unavailable after cloning, the job exits with an error (it does not skip). When available it runs `python3 ../OIP/tools/gen_protocol.py --check`, and any drift fails the job. `src/protocol_gen.rs` and `src/topics_gen.rs` are generated by that script. ## Persistence Modes `store.mode` decides how the **authoritative source data (facts and state)** of `OIP-Book` is persisted: > **Two planes**: this key governs only the **OIP-owned plane** (VET / audit + Merkle roots / Exchange locks / outbox / DID / credentials / sync cursors / third-party bindings). The **sharing plane** (org collaboration / workflow / private data) is selected by `OIP_BOOK_ORG_STORE`, falling back to this key — the three share the legacy relationship kernel's `tb_*` tables and MUST stay on one backend. That kernel runs on **MySQL 8** in production, so the "take over the legacy database" shape is `store.mode=postgres` + `OIP_BOOK_ORG_STORE=mysql`. | Mode | Storage | Use case | Notes | | --- | --- | --- | --- | | `memory` | In-process | Unit tests / local demo | Lost on restart | | `postgres` | PostgreSQL (relational DB) | Production | VET, org collaboration, Exchange locks, audit + Merkle roots, workflow, sync cursors, third-party bindings and outbox all persisted (see table below) | | `mongo` | MongoDB | Production fallback / legacy compatibility | VET in `oip_book.vets`, org collaboration in `org_*` collections; nonce consumed atomically via Redis | | `mysql` (via `OIP_BOOK_ORG_STORE` only) | MySQL 8 (legacy relationship-kernel DB) | Taking over the legacy kernel / legacy compatibility | The sharing plane lands in the legacy `tb_*` tables in place; the OIP-owned plane still follows `store.mode` | With `store.mode=postgres`, `store.database_url` specifies the connection string (e.g. `postgres://user:pass@host:5432/oip`); persistence coverage: | Data | Tables | | --- | --- | | VET lifecycle (CAS optimistic locking via the `version` column) | `oip_vet` | | Org collaboration (Target/Team/Relation/Identity/Authority) | `tb_target` / `tb_team` / `tb_relation` / `tb_authority` / `tb_identity` / `tb_team_identity` / `tb_id_proof` / `oip_identity_authority` | | Exchange two-phase locks | `oip_lock` | | Transfer workflow instances (approval chain; CAS via the `version` column) | `oip_transfer_workflow` | | Audit log + Merkle root history | `oip_audit` / `oip_merkle_root` | | Third-party account bindings | `oip_third_party_binding` | | Outbox | `oip_outbox` | | Workflow definitions | `oip_wf_define` | | Workflow instances / tasks / gateways / node records | `tb_work_instance` / `tb_work_task` / `tb_work_node_gateway` / `tb_work_record` | | Private data (legacy table added; no consumer yet) | `tb_private` | | DID registry | `oip_did` | | Node sync cursors | `oip_sync_cursor` | ### Sharing tables with the legacy relationship kernel The org-collaboration and workflow tables reuse the table and column names of the legacy relationship kernel (`oiocns-goinone/source/schema`), so a legacy database can be taken over in place. The column-level rules are: legacy columns are preserved verbatim; same-name same-meaning columns (`name` / `code` / `remark` / `title` / `create_time` / `update_time`) are shared; every other OIP column carries an `oip_` prefix; and `id BIGINT` (legacy internal id) coexists with `oip_did` / `oip_oid` (OIP identifiers). **The OIP DID and the legacy data-chain identifier `chainId` belong to the same identifier space**, so `oip_did` is backfilled from that value and no separate `id ↔ DID` mapping table exists. Alignment with the Ent model: the legacy soft-delete column `is_deleted` (NOT NULL DEFAULT false) on every `tb_*` table, and the workflow-task enum column defaults (`approve_type` / `task_type` set to the Ent value domain `审批` / `事项`), are added at table-creation time — OIP neither reads nor writes these legacy columns, but their presence keeps OIP-written rows visible to legacy filters and valid under the enum constraints, and makes a fresh database match the Ent schema. Column refinement: tables that previously kept a whole record in a `data` / `doc` JSONB column are now columnar; **list- and tree-valued fields always land in relational tables, never in PG array columns** — cross-subject relations land in `tb_team_identity` / `tb_id_proof` / `oip_identity_authority`, team membership lands in `tb_relation` member rows, the authority hierarchy is restored from the self-referencing `tb_authority.parent_id`, and workflow instance approvers are aggregated from `tb_work_task` assignees; JSONB is retained only for variable-length nested structures whose shape varies with their values (workflow definition `content`, instance and gateway `oip_content`, VET `parameters`, audit/outbox `payload`). The mapping inventory, migration steps and known boundaries are in [../OIP/docs/OIP-Book-Design.md](../OIP/docs/OIP-Book-Design.md) §6.3. The OIP-owned tables `oip_vet` / `oip_wf_define` additionally carry a **forward migration**: on startup, if the historical single `data` (JSONB) column that stored the whole record is detected, the schema is extended, backfilled field-by-field from `data`, constrained to match a fresh install, and the legacy column is dropped — so an old database is taken over without manual steps. ### MySQL sharing plane (`OIP_BOOK_ORG_STORE=mysql`) The legacy relationship kernel runs on **MySQL 8** in production (Ent-generated schema, `oiocns-goinone/kernel/store/migrate/schema.go`); PostgreSQL is merely an optional driver. The MySQL variant lands the sharing plane **in place** in that database with the same column-level rules as the PostgreSQL side (legacy columns preserved verbatim, same-name same-meaning columns shared, other OIP columns prefixed `oip_`, `id` coexisting with `oip_did` / `oip_oid`). Dialect mapping (`src/mysql.rs` holds the shared facilities): | Concern | PostgreSQL | MySQL | | --- | --- | --- | | Idempotent write | `ON CONFLICT ... DO UPDATE` | `ON DUPLICATE KEY UPDATE ... = VALUES(...)` | | Creation mutex | `pg_advisory_xact_lock` (transaction-scoped) | `GET_LOCK` / `RELEASE_LOCK` (session-scoped) | | `id` allocation | `CREATE SEQUENCE` + column default | `oip_id_seq` table + atomic `LAST_INSERT_ID` increment (**not** `AUTO_INCREMENT`, which would rewrite a legacy column definition) | | Boolean / time / nested payloads | `BOOLEAN` / `TIMESTAMPTZ` / `JSONB` | `TINYINT(1)` / `DATETIME(6)` (UTC by convention) / `JSON` | | List aggregation | `array_agg(...)` | `GROUP_CONCAT(... ORDER BY ... SEPARATOR ',')` | The takeover actions mirror the PostgreSQL side: add `oip_*` columns, add `is_deleted TINYINT(1) NOT NULL DEFAULT 0`, fill in defaults for legacy columns that are **NOT NULL without a DB default** (`tb_target.type_name` / `tb_work_instance.content_type` / `tb_work_task.title|approve_type|task_type`), and create the OIP key indexes (MySQL has no `ADD COLUMN IF NOT EXISTS` / `CREATE INDEX IF NOT EXISTS`, so `information_schema` is consulted first). `tb_work_*` and `tb_private` are created by `src/workflow/mysql.rs` and `src/private.rs` respectively, on the same backend as org collaboration. The legacy schema baseline is `tests/fixtures/legacy_goinone_ent_schema.mysql.sql` (transcribed column-by-column from the Ent-generated file above: 12 tables, 177 columns); `tests/legacy_schema_takeover_contract.rs` asserts that this fixture does **not drift** from the Ent output and runs the takeover against the real structure. The cases are gated by `OIP_MYSQL_URL` (skip when unset) and are **not** `#[ignore]`d. `events.mode` independently controls the **event bus**: `memory` / `nats` (NATS JetStream). With `store.mode=postgres`, audit, locks, workflow, sync cursors, third-party bindings and the outbox share `store.database_url`; `OIP_BOOK_ORG_STORE` overrides the **sharing plane** (org collaboration / workflow / private data) store mode on its own, and `mysql` selects taking over the legacy relationship-kernel database. Each store's DDL batch is serialized behind a transaction-scoped advisory lock (`src/storage.rs::ddl_batch`): `CREATE ... IF NOT EXISTS` is only idempotent under sequential execution, since concurrent execution collides on system-catalog unique constraints. Creation mutex for simultaneously starting replicas is therefore settled at the DDL layer rather than relying on the startup backoff retry. ### Legacy data import and key backfill Legacy rows and OIP rows share the same tables, but their **key columns belong to two identifier spaces**; until backfilled, legacy rows are invisible to OIP. `src/migrate.rs` performs the backfill: | Step | Interface | Notes | | --- | --- | --- | | Schema | each store's `connect` | Idempotent; adds columns, defaults and the soft-delete column to pre-existing legacy tables | | Stage key map | `stage_keys` | The migration adapter writes "legacy internal id → OIP identifier" into `oip_legacy_key_map` (for subjects the value is the DID, taken from the legacy data-chain identifier `chainId`) | | Backfill | `backfill_legacy_keys` | Idempotently fills `oip_*` key columns and derives relational rows (team members / team identities / identity proofs / authority set / private properties); a second run is a no-op | The backfill only trusts what is **deterministically derivable**: soft-deleted rows are skipped, membership comes only from effective states, `oip_type_name` is accepted only when already an OIP literal, assignees and legacy status codes are never guessed, and duplicate association rows are de-duplicated by smallest `id`. Rules and known boundaries: [../OIP/docs/OIP-Book-Design.md](../OIP/docs/OIP-Book-Design.md) §6.3.4 / §6.3.5. The production combination is `store.mode=postgres` (relational authoritative source; transactions plus row versions delivering "linearizable, correctness first") + `events.mode=nats`; `mongo` carries legacy compatibility; a `memory` combination emits an ERROR-level warning at startup and loses state on restart. ### Multi-replica (cluster) deployment With `store.mode=postgres`, `OIP-Book` runs as multiple replicas (N instances behind one `Service`); replicas exchange state that must be globally consistent through the **shared database**. `memory` / `mongo` do not provide the semantics below and suit single-instance deployment only. | State | Shared location | Semantics across replicas | | --- | --- | --- | | Atomic nonce consumption | `oip_nonce` (primary key `(ns_key, nonce)`) | Replay protection **holds across replicas**: a nonce consumed by A is rejected as a replay by B | | Global circuit breaker | `oip_breaker` (single row `id='global'`) | Once any replica activates the break, **all replicas** reject writes via `guard()` (fail-closed: writes are also rejected when the shared store is unreachable) | | Rate limiting | `oip_ratelimit` (fixed-window counter) | The service-level quota is consumed cluster-wide (an in-process counter would be multiplied N-fold); an atomic upsert keeps the per-window count consistent across replicas | | Data-share records | `oip_share` | A `share_id` issued by replica A can be loaded by replica B (a "write-then-read" fact) | | Outbox claiming | `oip_outbox` (`FOR UPDATE SKIP LOCKED`) | A given batch of pending rows is claimed by one replica only, preventing duplicate publishing and multi-fold `attempts` increments; delivery stays at-least-once and consumers de-duplicate by `event.id` | **Maintenance leader election**: VET expiry scanning and Exchange lock-timeout rollback start on every replica, but only the **leader holding a session-level `pg_try_advisory_lock`** actually runs them (others skip the round). The lock is released when the leader's connection closes, and another replica takes over on the next round — no additional election component is required. **Graceful shutdown (rolling updates)**: after `SIGINT` / `SIGTERM` the instance **drains** — `/readyz` immediately returns `503 draining` so the orchestrator/LB removes it; after `OIP_BOOK_PRE_STOP_SECS` (default 5s) axum graceful shutdown drains in-flight requests. Readiness gating MUST therefore target `/readyz`, and `terminationGracePeriodSeconds` MUST exceed the drain window. **Readiness probe**: `/readyz` returns `503` when draining, when the breaker is open, or when every pooled PG connection is broken; `/healthz` reflects process liveness only. ## API Endpoints `build()` in `src/router.rs` is the single assembly point for all endpoints. | Method | Path | Description | | --- | --- | --- | | POST | `/oip/v1/auth/login` | Login-state issuance: DID Proof and account/password are two **mutually exclusive** forms (`{did, proof}` or `{account, password}`) | | POST | `/oip/v1/auth/register` | Account registration: create subject (`type_name=person`) + register credential, **no session issued**; duplicate account returns `OIP_4094` | | POST | `/oip/v1/auth/password` | Change password: verify `old_password` then store a new hash; a wrong old password returns `OIP_4001` | | POST | `/oip/v1/auth/password/disable` | **User-initiated** opt-out from account/password login (requires the current password); toggles a flag only, keeps the hash, reversible at any time | | POST | `/oip/v1/auth/password/enable` | Re-enable account/password login (requires the current password; the credential was never deleted) | | POST | `/oip/v1/auth/assertion/exchange` | External assertion → credential: look up an **existing binding** by the four-part binding key and sign only for the bound DID; never creates subjects, never writes bindings | | POST | `/oip/v1/auth/refresh` | Refresh-token rotation | | POST | `/oip/v1/auth/logout` | Revoke session | | POST | `/oip/v1/auth/challenge` | Generate login challenge | | GET | `/oip/v1/otp/private-key` | Query OTP private key (§5A.9 `QueryOtpPrivateKey`): `?subject_id=` returns the TOTP shared secret as raw base32; unregistered returns `OIP_4041` | | POST | `/oip/v1/vet/issue` | Issue VET (Ed25519 signed); optional **object binding** `object{type,id}` and **parameter bounds** `constraints.parameters`, which MUST come with `object_signature` / `constraints_signature` respectively (each separately endorsed by the issuer) | | POST | `/oip/v1/vet/verify` | PDP staged verification (Stage 4 re-verifies the constraints endorsement, Stage 4.5 re-verifies the object endorsement, then checks `resource_id == object.id`) | | POST | `/oip/v1/vet/revoke` | Revoke VET (cascade revocation) | | GET | `/oip/v1/vet/:vet_id` | Query VET details | | GET | `/oip/v1/vet/:vet_id/delegation-chain` | Query delegation chain | | GET | `/oip/v1/vet/by-object` | List the transferable VETs the caller may claim **on a given object** (read-only; only `holder == caller`, minimal projection; rejected when `caller_did` is absent) | | POST | `/oip/v1/vet/bind` / `/oip/v1/vet/unbind` | Bind / unbind a third-party account (§5A.10) | | GET | `/oip/v1/vet/bindings/:target_did` | List a subject's bindings | | GET | `/oip/v1/transfer/prepare` | Settlement preparation (read-only): returns the raw `signing_payload` plus the two bounds/object `*_signing_payload` strings for the source to sign before `commit` | | POST | `/oip/v1/transfer/override` | Override forced transfer (HSM regulator signature); a **control transfer** ⇒ other transferable VETs on the same object are revoked in the same transaction | | POST | `/oip/v1/transfer/workflow` | Workflow transfer creation (with approval flow) | | POST | `/oip/v1/transfer/workflow/approve` | Approve workflow (completing the chain transfers ⇒ same cascade) | | GET | `/oip/v1/transfer/workflow/pending` | List workflows awaiting my signature (read-only; already-signed ones are excluded) | | GET | `/oip/v1/transfer/workflow/{workflow_id}` | Fetch one workflow's status (read-only; chain parties only — non-parties get the same code as non-existent) | | POST | `/oip/v1/transfer/lock` | Exchange lock (timeout rollback) | | POST | `/oip/v1/transfer/commit` | Exchange commit (issue-new + revoke-old ⇒ same cascade) | | POST | `/oip/v1/transfer/collaborate` | Collaboration transfer (**does not transfer ownership**, no cascade) | | POST | `/oip/v1/regulator/emergency-break` | Regulator emergency break | | POST | `/oip/v1/regulator/release-break` | Release break | | GET | `/oip/v1/regulator/break-status` | Break status query | | GET | `/oip/v1/audit/trace` | Audit trace | | GET | `/oip/v1/audit/merkle-proof` | Merkle inclusion proof | | POST | `/oip/v1/audit/verify-integrity` | Audit integrity verification | | GET | `/oip/v1/audit/events` | Audit event stream | | POST | `/oip/v1/target` | Create target (Target is DID) | | POST | `/oip/v1/target/query` | Query target by ID | | GET | `/oip/v1/target/search` | Fuzzy search targets | | DELETE | `/oip/v1/target/:id` | Delete target | | PUT | `/oip/v1/target/:id` | Update target | | POST | `/oip/v1/identity` | Create identity (VET) | | POST | `/oip/v1/identity/give` | Grant identity (VET) | | POST | `/oip/v1/identity/remove` | Remove identity (VET) | | POST | `/oip/v1/authority` | Create authority (VET) | | GET | `/oip/v1/authority/tree` | Authority tree | | POST | `/oip/v1/relations/create` | Establish relation (VET) | | POST | `/oip/v1/relations/validate` | Validate relation evidence | | POST | `/oip/v1/team` | Create team | | POST | `/oip/v1/team/join` | Join team | | POST | `/oip/v1/team/leave` | Leave team | | POST | `/oip/v1/work/define` | Create work definition | | GET | `/oip/v1/work/define/:id` | Query work definition | | POST | `/oip/v1/work/define/:id/switch` | Switch definition version | | POST | `/oip/v1/work/instance` | Create work instance | | POST | `/oip/v1/work/task/approval` | Approve task | | POST | `/oip/v1/work/gateway` | Create work gateway | | GET | `/oip/v1/work/gateways` | Query work gateways | | POST | `/oip/v1/sync/snapshot` | Generate sync snapshot (§5B.7) | | POST | `/oip/v1/sync/cursor/:node_id` | Query a downstream node's sync cursor | | POST | `/oip/v1/sync/cursor/:node_id/advance` | Report a consumed cursor | | POST | `/oip/v1/system/data-share` | Issue data-share record / data licence token (§5B.5) | | POST | `/oip/v1/system/load-share` | Load data-share record | | GET | `/healthz` | Liveness probe | | GET | `/readyz` | Readiness probe | ## Error Codes `OipErrorCode::as_str()` in `src/error.rs` defines the external error codes and `http_status()` defines the HTTP mapping. | Code | HTTP | Meaning | | --- | --- | --- | | `OIP_4001` | 400 | Invalid parameter | | `OIP_4002` | 400 | Schema validation failed | | `OIP_4003` | 400 | Delegation out of scope | | `OIP_4005` | 400 | Delegation depth exceeded | | `OIP_4006` | 400 | Invalid market listing | | `OIP_4011` | 401 | Proof / token validation failed (includes the inbound internal token gate) | | `OIP_4012` | 401 | VET expired | | `OIP_4013` | 401 | VET revoked | | `OIP_4031` | 403 | PDP rejection (boolean blindness; no stage reason) | | `OIP_4033` | 403 | Compliance denied | | `OIP_4034` | 403 | Missing list VET | | `OIP_4035` | 403 | Missing audit VET | | `OIP_4041` | 404 | Not found | | `OIP_4091` | 409 | VET locked | | `OIP_4092` | 409 | Workflow in progress | | `OIP_4093` | 409 | Override conflict | | `OIP_4094` | 409 | State conflict | | `OIP_4291` | 429 | Rate limited | | `OIP_5001` | 500 | Internal error (generic message) | | `OIP_5031` | 503 | Service unavailable (including while the breaker is open) | ## Directory Structure ```text OIP-Book/ ├── Cargo.toml # manifest (edition 2024, license MIT) ├── config.example.yaml # config template (config.yaml is gitignored) ├── docker-compose.yml # local dependency orchestration ├── deploy/ # cluster deployment examples + start script (start-cluster.sh; K8s manifests + Secret template; single-host multi-replica compose + nginx LB) ├── deny.toml # cargo-deny dependency policy ├── AGENTS.md # collaboration conventions ├── README.md / README.en.md ├── src/ │ ├── main.rs # binary entry (thin shell: load config → HTTP + maintenance tasks + outbox relay) │ ├── lib.rs # library entry (module declarations; exports Config / AppState) │ ├── breaker.rs # global circuit breaker state machine (Open/HalfOpen/Closed) │ ├── clock.rs # time abstraction (SystemClock / ManualClock) │ ├── compliance.rs # compliance engine (sanctions + GDPR) │ ├── config.rs # config loading & validation │ ├── credentials.rs # account/password credentials (trait + in-memory impl; argon2 PHC / TOTP base32) │ ├── crypto.rs # Ed25519 signing/verification / HSM signature / canonical payload │ ├── did.rs # DID registration & status management │ ├── effects.rs # side-effect and disposition registry for authoritative operations (reversible / compensable / irreversible) │ ├── error.rs # OIP error codes & unified error │ ├── events.rs # audit events (in-memory / NATS JetStream) + topic registry │ ├── handlers/ # HTTP handlers (audit / auth / binding / health / org / regulator / sync / system / transfer / vet / workflow) │ ├── lifecycle.rs # VET state machine & transfer rules │ ├── merkle.rs # Merkle audit tree │ ├── migrate.rs # legacy relationship kernel → OIP key backfill and data import (oip_legacy_key_map + idempotent backfill) │ ├── mysql.rs # MySQL sharing-plane facilities (connection / DDL session lock / id allocation / dialect accessors) │ ├── org/ # org collaboration intake (types / store / postgres / mysql) │ ├── outbox.rs # outbox (atomic dual-write + async relay; dead letters are never deleted) │ ├── pdp.rs # PDP staged pipeline + boolean blindness │ ├── private.rs # private property values (legacy tb_private carry-over; values redacted in Debug) │ ├── protocol_gen.rs # protocol-surface registry (generated by gen_protocol.py) │ ├── ratelimit.rs # token bucket rate limiting │ ├── response.rs # unified OperateResult response │ ├── router.rs # route assembly + internal service token gate + router integration tests │ ├── runtime.rs # runtime assembly (background expiry sweep, lock timeout rollback) │ ├── share.rs # data-share records and data licence tokens │ ├── state.rs # global state and storage/event backend selection │ ├── storage.rs # storage abstraction (PostgreSQL / MongoDB / in-memory) │ ├── sync.rs # node-to-node sync (SyncSnapshot generation + sync cursor storage) │ ├── topics_gen.rs # NATS topic registry (generated by gen_protocol.py) │ ├── transfer.rs # four transfer laws │ ├── types.rs # VET / DID / delegation policy / event types │ └── workflow/ # workflow administration (mod + store + mysql) └── tests/ ├── fixtures/ # legacy Ent schema baseline (MySQL dialect) ├── auth_issuance_contract.rs # authentication issuance contract integration tests ├── credential_revocation_contract.rs # credential revocation contract ├── identity_grant_contract.rs # identity grant contract ├── otp_binding_contract.rs # OTP binding contract ├── target_list_contract.rs # target list contract ├── work_todo_contract.rs # work todo contract └── legacy_schema_takeover_contract.rs # legacy-schema drift gate + takeover contract (gated by OIP_MYSQL_URL) ``` ## Testing | Layer | Location | Description | | --- | --- | --- | | Unit tests | `#[cfg(test)]` in each module | state machine transitions, PDP six stages, Merkle proofs, rate limiting, circuit breaker, storage abstraction | | Router integration tests | `#[cfg(test)]` in `src/router.rs` | real HTTP requests via `tower::ServiceExt::oneshot` | | Contract integration tests | `tests/auth_issuance_contract.rs` | authentication issuance surface contract (26 cases, incl. account registration / account-password login / password change / assertion exchange / OTP private key) | | External-dependency cases | `#[ignore]` + `OIP_POSTGRES_URL` / `OIP_REDIS_URL` | require a real PostgreSQL / Redis; print `skip` and return when unset | | Legacy-schema takeover contract | `tests/legacy_schema_takeover_contract.rs` | contains the fixture ↔ Ent-output drift gate and the takeover contract on the real Ent structure; gated by `OIP_MYSQL_URL` (skipped when unset, **not** `#[ignore]`d) | ## Security Baseline - PDP boolean blindness: every rejection path returns an identical `OIP_4031` body; stage reasons go only to the internal `detail` field - Override transfers and emergency breaks (`force_level` ≥ 50 / 250) require HSM-signed regulator commands; once the breaker trips, writes are globally refused - 500-class errors return generic messages; full exceptions go only to internal logs - Auth, VET issue/verify/revoke, Override transfer and data-share endpoints are rate-limited by token bucket (quotas in `src/ratelimit.rs`); nonces are consumed atomically as a `(key, nonce)` pair to prevent replay (Redis / in-memory) - Internal service token gate: with the environment variable `OIP_BOOK_INTERNAL_TOKEN` set (non-empty enables it), every endpoint except `/healthz` and `/readyz` requires `Authorization: Bearer `, compared in constant time and rejected with `OIP_4011` - Credentials are injected only via `config.yaml` (gitignored, never committed) and must not be hardcoded - Account/password credentials: passwords are stored only as argon2id PHC strings (`Argon2::default()`: m=19 MiB / t=2 / p=1); plaintext and hashes are redacted by hand-written `Debug`; `account` is unique and maps 1:1 to a DID - Account-enumeration defence: account-password login and password change return byte-identical external errors for "unknown account" and "wrong password" (login `OIP_4011`, password change `OIP_4001`), and the unknown-account branch still performs an equivalent argon2 verification to blunt the timing side channel - Assertion exchange (`auth/assertion/exchange`) only reads existing binding facts: assertions MUST NOT create subjects, MUST NOT write bindings, and no assertion field MUST be treated as a DID (signing always uses the `target_did` of the binding fact) - DID Proof login strictness is not relaxed: the subject must be registered and active, must have a registered Auth Key, and the Proof is mandatory and must verify; the `account_password` bridge field has been removed ## Docs - Design (OIP specification repository): [OIP-Book-Design.md](../OIP/docs/OIP-Book-Design.md) - Decentralization design (OIP specification repository): [OIP-Book-Decentralization-Design.md](../OIP/docs/OIP-Book-Decentralization-Design.md) - Protocol specification (OIP specification repository): [OIP-Protocol.md](../OIP/docs/OIP-Protocol.md) - Test strategy (OIP specification repository): [OIP-Test-Strategy.md](../OIP/docs/OIP-Test-Strategy.md) - Protocol-surface generator (OIP specification repository): [gen_protocol.py](../OIP/tools/gen_protocol.py) - Conventions: [AGENTS.md](AGENTS.md) - License: MIT