Make CultNet the provider contract owner

This commit is contained in:
Meta Vens 2026-07-19 21:28:21 +01:00
commit deed50808a
43 changed files with 13 additions and 9363 deletions

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "vendor/cultnet-rs"]
path = vendor/cultnet-rs
url = https://github.com/GameCult/cultnet-rs.git

View file

@ -1,6 +1,13 @@
use cultcache_rs::DatabaseEntry;
pub use cultnet_rs::{
GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA, GameCultServiceTrustAnchorRecord,
IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA,
IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE, IDUNN_PROVIDER_ACTIVE_REASON,
IDUNN_PROVIDER_DEGRADED_REASON, IDUNN_PROVIDER_FAILED_REASON, IDUNN_PROVIDER_WARMING_REASON,
IdunnAuthenticatedProviderHealthProjectionRecord, authenticated_provider_health_reason_code,
};
use cultnet_rs::{
GameCultProviderHealthIdentity, IdunnServiceIdentity, derive_service_identity_id,
GameCultProviderHealthIdentity, derive_service_identity_id,
};
use serde_json::Value;
@ -47,15 +54,6 @@ pub const IDUNN_AUTHENTICATED_DAEMON_HEALTH_ADMISSION_SCHEMA: &str =
"idunn.authenticated_daemon_health_admission.v1";
pub const IDUNN_UNSIGNED_DAEMON_HEALTH_DIAGNOSTIC_SCHEMA: &str =
"idunn.unsigned_daemon_health_diagnostic.v1";
pub const GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA: &str = "gamecult.service_trust_anchor.v1";
pub const IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA: &str =
"idunn.authenticated_provider_health_projection.v1";
pub const IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE: &str =
"idunn.authenticated-provider-health-projection.v1";
pub const IDUNN_PROVIDER_ACTIVE_REASON: &str = "authenticated_provider_active";
pub const IDUNN_PROVIDER_WARMING_REASON: &str = "authenticated_provider_warming";
pub const IDUNN_PROVIDER_DEGRADED_REASON: &str = "authenticated_provider_degraded";
pub const IDUNN_PROVIDER_FAILED_REASON: &str = "authenticated_provider_failed";
pub const MUNINN_TELEMETRY_SURFACE_SCHEMA: &str = "muninn.telemetry_surface.v1";
pub const MUNINN_CAPTURE_STREAM_SCHEMA: &str = "muninn.capture_stream.v1";
pub const MUNINN_CAPTURE_STREAM_COMMAND_SCHEMA: &str = "muninn.capture_stream_command.v1";
@ -615,208 +613,6 @@ impl IdunnUnsignedDaemonHealthDiagnosticRecord {
}
}
/// Root-distributed public key binding for one service-owned signed contract.
/// Consumers pin this document; a self-declared key inside a signed projection
/// is never authority.
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "gamecult.service_trust_anchor",
schema = "gamecult.service_trust_anchor.v1"
)]
pub struct GameCultServiceTrustAnchorRecord {
#[cultcache(key = 0)]
pub schema_version: String,
#[cultcache(key = 1)]
pub trust_anchor_id: String,
#[cultcache(key = 2)]
pub service_id: String,
#[cultcache(key = 3)]
pub runtime_id: String,
#[cultcache(key = 4)]
pub signer_identity_id: String,
#[cultcache(key = 5)]
pub signer_public_key: Vec<u8>,
#[cultcache(key = 6)]
pub signature_algorithm: String,
#[cultcache(key = 7)]
pub signing_purpose: String,
#[cultcache(key = 8)]
pub signed_schema: String,
#[cultcache(key = 9)]
pub binding_authority: String,
#[cultcache(key = 10)]
pub bound_at_unix_millis: u64,
#[cultcache(key = 11)]
pub expires_at_unix_millis: Option<u64>,
#[cultcache(key = 12)]
pub private_state_exposed: bool,
}
impl GameCultServiceTrustAnchorRecord {
pub fn validate(&self) -> Result<()> {
if self.schema_version != GAMECULT_SERVICE_TRUST_ANCHOR_SCHEMA {
bail!("service trust anchor schema is unsupported");
}
validate_identifier(&self.trust_anchor_id, "trust anchor id")?;
validate_identifier(&self.service_id, "service id")?;
validate_identifier(&self.runtime_id, "runtime id")?;
validate_identifier(&self.signer_identity_id, "signer identity id")?;
validate_identifier(&self.signing_purpose, "signing purpose")?;
validate_identifier(&self.signed_schema, "signed schema")?;
if self.signer_public_key.len() != 32
|| self.signature_algorithm != "ed25519"
|| self.binding_authority != "root"
|| self.bound_at_unix_millis == 0
|| self
.expires_at_unix_millis
.is_some_and(|expires_at| expires_at <= self.bound_at_unix_millis)
|| self.private_state_exposed
{
bail!("service trust anchor authority, key, lifetime, or privacy is invalid");
}
if self.signed_schema == IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA
&& (self.service_id != "idunn"
|| self.signing_purpose
!= IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SIGNING_PURPOSE
|| self.signer_identity_id
!= derive_service_identity_id::<IdunnServiceIdentity>(&self.signer_public_key)?)
{
bail!("Idunn provider-health trust anchor profile is invalid");
}
Ok(())
}
}
/// Idunn-owned, public, signed projection of one *current authenticated generic
/// provider health admission*. Absence, release drift, and dependency failures
/// produce no record; they are not provider states Idunn may manufacture.
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
#[cultcache(
type = "idunn.authenticated_provider_health_projection",
schema = "idunn.authenticated_provider_health_projection.v1"
)]
pub struct IdunnAuthenticatedProviderHealthProjectionRecord {
#[cultcache(key = 0)]
pub schema_version: String,
#[cultcache(key = 1)]
pub projection_id: String,
#[cultcache(key = 2)]
pub daemon_id: String,
#[cultcache(key = 3)]
pub health_contract: String,
#[cultcache(key = 4)]
pub provider_state: String,
#[cultcache(key = 5)]
pub reason_code: String,
#[cultcache(key = 6)]
pub provider_observed_at_unix_millis: u64,
#[cultcache(key = 7)]
pub admitted_at_unix_millis: u64,
#[cultcache(key = 8)]
pub evaluated_at_unix_millis: u64,
#[cultcache(key = 9)]
pub trust_binding_id: String,
#[cultcache(key = 10)]
pub trust_binding_sha256: String,
#[cultcache(key = 11)]
pub signed_health_sha256: String,
#[cultcache(key = 12)]
pub authenticated_admission_sha256: String,
#[cultcache(key = 13)]
pub provider_signer_identity_id: String,
#[cultcache(key = 14)]
pub provider_incarnation_id: String,
#[cultcache(key = 15)]
pub provider_sequence: u64,
#[cultcache(key = 16)]
pub release_id: Option<String>,
#[cultcache(key = 17)]
pub release_witness_sha256: Option<String>,
#[cultcache(key = 18)]
pub source_commit: Option<String>,
#[cultcache(key = 19)]
pub deployment_id: Option<String>,
#[cultcache(key = 20)]
pub idunn_runtime_id: String,
#[cultcache(key = 21)]
pub idunn_signer_identity_id: String,
#[cultcache(key = 22)]
pub projection_incarnation_id: String,
#[cultcache(key = 23)]
pub projection_sequence: u64,
#[cultcache(key = 24)]
pub signature_algorithm: String,
#[cultcache(key = 25)]
pub signature: Vec<u8>,
#[cultcache(key = 26)]
pub private_state_exposed: bool,
#[cultcache(key = 27)]
pub expires_at_unix_millis: u64,
}
/// Closed derivation used by Idunn when projecting an authenticated provider
/// state. `None` means there is no provider-health projection to publish.
pub fn authenticated_provider_health_reason_code(state: &str) -> Option<&'static str> {
match state {
"active" => Some(IDUNN_PROVIDER_ACTIVE_REASON),
"warming" => Some(IDUNN_PROVIDER_WARMING_REASON),
"degraded" => Some(IDUNN_PROVIDER_DEGRADED_REASON),
"failed" => Some(IDUNN_PROVIDER_FAILED_REASON),
_ => None,
}
}
impl IdunnAuthenticatedProviderHealthProjectionRecord {
pub fn validate(&self) -> Result<()> {
if self.schema_version != IDUNN_AUTHENTICATED_PROVIDER_HEALTH_PROJECTION_SCHEMA {
bail!("authenticated provider health projection schema is unsupported");
}
validate_identifier(&self.projection_id, "projection id")?;
validate_identifier(&self.daemon_id, "daemon id")?;
validate_identifier(&self.health_contract, "health contract")?;
validate_identifier(&self.trust_binding_id, "trust binding id")?;
validate_identifier(
&self.provider_signer_identity_id,
"provider signer identity id",
)?;
validate_identifier(&self.provider_incarnation_id, "provider incarnation id")?;
validate_identifier(&self.idunn_runtime_id, "Idunn runtime id")?;
validate_identifier(&self.idunn_signer_identity_id, "Idunn signer identity id")?;
validate_identifier(&self.projection_incarnation_id, "projection incarnation id")?;
let state_reason_is_valid = authenticated_provider_health_reason_code(&self.provider_state)
.is_some_and(|reason| reason == self.reason_code);
if !state_reason_is_valid
|| self.provider_observed_at_unix_millis == 0
|| self.admitted_at_unix_millis < self.provider_observed_at_unix_millis
|| self.evaluated_at_unix_millis < self.admitted_at_unix_millis
|| self.expires_at_unix_millis <= self.evaluated_at_unix_millis
|| self.provider_sequence == 0
|| self.projection_sequence == 0
|| !is_sha256(&self.trust_binding_sha256)
|| !is_sha256(&self.signed_health_sha256)
|| !is_sha256(&self.authenticated_admission_sha256)
|| self.signature_algorithm != "ed25519"
|| self.signature.len() != 64
|| self.private_state_exposed
{
bail!(
"authenticated provider health projection shape, lineage, reason, signature, or privacy is invalid"
);
}
validate_optional_release_binding(
&self.release_id,
&self.release_witness_sha256,
&self.source_commit,
)?;
validate_optional_identifier(&self.deployment_id, "deployment id")?;
let release_binding_present = self.release_id.is_some();
if self.deployment_id.is_some() != release_binding_present {
bail!("authenticated provider health projection release lineage is partial");
}
Ok(())
}
}
fn validate_identifier(value: &str, label: &str) -> Result<()> {
if value.trim().is_empty() || value.len() > 256 || value.chars().any(char::is_control) {
bail!("{label} is empty, oversized, or contains control characters");
@ -2211,7 +2007,7 @@ mod tests {
trust_anchor_id: "root/idunn/authenticated-provider-health-projection".into(),
service_id: "idunn".into(),
runtime_id: "idunn-yggdrasil".into(),
signer_identity_id: derive_service_identity_id::<IdunnServiceIdentity>(
signer_identity_id: derive_service_identity_id::<cultnet_rs::IdunnServiceIdentity>(
&signer_public_key,
)
.unwrap(),

1
vendor/cultnet-rs vendored Submodule

@ -0,0 +1 @@
Subproject commit 014f998b97c37a34055ce0af069ebaead32d11fb

View file

@ -1,2 +0,0 @@
/target
Cargo.lock

View file

@ -1,36 +0,0 @@
[package]
name = "cultnet-rs"
version = "0.1.0"
edition = "2024"
publish = false
license = "MIT"
description = "CultNet-style typed MessagePack messaging, direct-pipe framing, security helpers, and CultCache replication for Rust runtimes."
[lib]
name = "cultnet_rs"
path = "src/lib.rs"
[dependencies]
aes-gcm = "0.10"
anyhow = "1"
base64 = "0.22"
chrono = { version = "0.4", features = ["serde"] }
cultcache-rs = { path = "../cultcache-rs" }
ed25519-dalek = "2.2"
hmac = "0.12"
rand = "0.9"
rmp-serde = "1.3"
rmpv = { version = "1.3", features = ["with-serde"] }
serde = { version = "1", features = ["derive"] }
serde_bytes = "0.11"
serde_json = "1"
sha2 = "0.10"
socket2 = "0.5"
uuid = { version = "1", features = ["v4"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security_Cryptography"] }
[dev-dependencies]
pretty_assertions = "1.4"
tempfile = "3"

View file

@ -1,96 +0,0 @@
# CultNet RS
`cultnet-rs` is the Rust sibling of `cultnet-ts`: typed MessagePack messages,
4-byte length-prefixed direct-pipe framing, stop-and-wait RUDP message delivery,
CultLib-shaped security helpers, and CultCache replication without making
callers paw through raw envelopes like we lost a bet.
The contract is intentionally boring:
- `cultnet.schema.v0` sends schema-versioned MessagePack objects.
- `gamecult.networking.v0` maps the legacy C# union shape explicitly.
- schema discovery uses explicit catalog request/response messages; no inbound
auto-detect sludge.
- document put/delete/snapshot messages move typed CultCache entries.
- raw document put/snapshot messages preserve canonical MessagePack payload
bytes for bit-compatible neighbors.
- `cultnet.transport.rudp.v0` carries one CultNet message per acknowledged UDP
datagram with timeout/retry semantics.
- hello messages advertise `supportedMutationContracts`, so callers discover
which document types are read-only, which accept typed intents, which
authority owns the mutation, and which receipt documents prove the outcome.
- payloads are decoded through registered Rust types before entering the cache.
This crate is not an HTTP wrapper. It is the wire vocabulary Epiphany,
Ghostlight, VoidBot, and the rest of the swarm can share.
The public API surface is the schema plus its mutation contracts. A runtime does
not expose a pile of bespoke verbs and hope everyone remembers the ritual; it
advertises typed documents, typed intents, and typed receipts. Polite machines
knock on the contract before touching the furniture.
## Receipts
```powershell
cargo test
```
The initial tests prove:
- CultLib-compatible AES-GCM string encryption and HMAC session tokens
- 4-byte big-endian MessagePack framing
- schema-versioned message round trips
- legacy `gamecult.networking.v0` login mapping
- schema discovery catalog responses with canonical JSON schema hashes
- CultCache snapshot replication through registered typed documents
- raw snapshot replication that preserves the original payload bytes
- document mutation contract advertisement through hello frames and registries
- acknowledged localhost UDP delivery through `cultnet.transport.rudp.v0`
## RUDP Transport
`cultnet.transport.rudp.v0` is the Rust crate's first non-TCP daemon transport.
It is intentionally small: one CultNet message becomes one UDP data packet, the
receiver sends an acknowledgement packet, and the sender retries until the ack
arrives or the retry budget is spent.
This is a daemon health/control substrate, not a bulk stream transport. It does
not fragment oversized messages, multiplex streams, or promise congestion
control. Large snapshots should stay in CultCache/CultMesh storage and move by
document reference or a later chunking contract. The useful invariant is simple:
Rust runtimes can now move a typed CultNet message across UDP without reaching
for TCP as the hidden truth path.
## Schema Discovery
`cultnet-rs` now ships a built-in schema registry for the shared swarm contract
surface:
- core wire messages
- legacy `gamecult.networking.v0` auth/sample payloads
- schema catalog request/response messages
- the canonical `ghostlight.agent-state` document payload schema
Use `builtin_schema_registry()` when you want the standard catalog, or register
your own closed-world schema set with `CultNetSchemaRegistry`. Discovery stays
explicit on purpose: peers advertise only the contracts they were compiled to
understand, the same way CultCache only consumes the document types you
registered instead of pretending polymorphism is a public park.
## Local Fast Lane
`cultnet-rs` now mirrors the raw replication seam from `cultnet-ts`:
- `cultnet.document_put_raw.v0`
- `cultnet.snapshot_response_raw.v0`
Those messages carry the exact persisted MessagePack payload bytes from
CultCache along with the typed envelope metadata. Combined with
`CultCache::put_envelope::<T>()`, that lets a bit-compatible neighbor ingest the
document without re-encoding the payload first.
That still is not zero-copy in the religious sense. Frames allocate, bytes move,
and the receiving cache still decodes once to keep typed reads and validation
honest. The win is narrower and realer: identical payload bytes stop getting
decoded into generic sludge and then encoded right back into the same bytes for
no reason.

View file

@ -1,19 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-delete.schema.json",
"title": "CultNet Document Delete Message",
"type": "object",
"required": [
"schemaVersion",
"messageId",
"schemaId",
"recordKey"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.document_delete.v0" },
"messageId": { "type": "string", "minLength": 1 },
"schemaId": { "type": "string", "minLength": 1 },
"recordKey": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,40 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-mutation-contract.schema.json",
"title": "CultNet Document Mutation Contract",
"type": "object",
"required": [
"documentType",
"operations",
"authority"
],
"additionalProperties": false,
"properties": {
"documentType": { "type": "string", "minLength": 1 },
"payloadSchemaVersion": { "type": "string", "minLength": 1 },
"operations": {
"type": "array",
"minItems": 1,
"items": {
"type": "string",
"enum": ["snapshot", "documentPut", "documentDelete", "intentSubmit", "receiptWatch"]
}
},
"authority": {
"type": "string",
"enum": ["readOnly", "localUser", "coordinator", "runtime", "denied"]
},
"intentDocumentTypes": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"receiptDocumentTypes": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"notes": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
}
}
}

View file

@ -1,19 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-put-raw.schema.json",
"title": "CultNet Raw Document Put Message",
"type": "object",
"required": [
"schemaVersion",
"messageId",
"document"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.document_put_raw.v0" },
"messageId": { "type": "string", "minLength": 1 },
"document": {
"$ref": "./cultnet.raw-document-record.schema.json"
}
}
}

View file

@ -1,19 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-put.schema.json",
"title": "CultNet Document Put Message",
"type": "object",
"required": [
"schemaVersion",
"messageId",
"document"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.document_put.v0" },
"messageId": { "type": "string", "minLength": 1 },
"document": {
"$ref": "./cultnet.document-record.schema.json"
}
}
}

View file

@ -1,26 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.document-record.schema.json",
"title": "CultNet Document Record",
"type": "object",
"required": [
"schemaId",
"recordKey",
"storedAt",
"payload"
],
"additionalProperties": false,
"properties": {
"schemaId": { "type": "string", "minLength": 1 },
"recordKey": { "type": "string", "minLength": 1 },
"storedAt": { "type": "string", "minLength": 1 },
"payload": {},
"sourceRuntimeId": { "type": "string", "minLength": 1 },
"sourceAgentId": { "type": "string", "minLength": 1 },
"sourceRole": { "type": "string", "minLength": 1 },
"tags": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
}
}
}

View file

@ -1,15 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.error.schema.json",
"title": "CultNet Error Message",
"type": "object",
"required": [
"schemaVersion",
"error"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.error.v0" },
"error": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,41 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.hello.schema.json",
"title": "CultNet Hello Message",
"type": "object",
"required": [
"schemaVersion",
"runtimeId",
"runtimeKind"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.hello.v0" },
"runtimeId": { "type": "string", "minLength": 1 },
"runtimeKind": { "type": "string", "minLength": 1 },
"agentId": { "type": "string", "minLength": 1 },
"role": { "type": "string", "minLength": 1 },
"displayName": { "type": "string", "minLength": 1 },
"supportedDocumentTypes": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"supportedMutationContracts": {
"type": "array",
"items": {
"$ref": "./cultnet.document-mutation-contract.schema.json"
}
},
"supportedMessageVersions": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"transportProfiles": {
"type": "array",
"items": {
"$ref": "./cultnet.transport-profile.schema.json"
}
},
"supportsSchemaCatalog": { "type": "boolean" }
}
}

View file

@ -1,17 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.login-success.schema.json",
"title": "CultNet Login Success Message",
"type": "object",
"required": [
"schemaVersion",
"nonce",
"session"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.login_success.v0" },
"nonce": { "type": "string", "minLength": 1 },
"session": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,19 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.login.schema.json",
"title": "CultNet Login Message",
"type": "object",
"required": [
"schemaVersion",
"nonce",
"auth",
"password"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.login.v0" },
"nonce": { "type": "string", "minLength": 1 },
"auth": { "type": "string", "minLength": 1 },
"password": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,32 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.raw-document-record.schema.json",
"title": "CultNet Raw Document Record",
"type": "object",
"required": [
"schemaId",
"recordKey",
"storedAt",
"payloadEncoding",
"payload"
],
"additionalProperties": false,
"properties": {
"schemaId": { "type": "string", "minLength": 1 },
"recordKey": { "type": "string", "minLength": 1 },
"storedAt": { "type": "string", "minLength": 1 },
"payloadEncoding": { "const": "messagepack" },
"payload": {
"type": "string",
"contentEncoding": "base64",
"x-cult-runtime-type": "bytes"
},
"sourceRuntimeId": { "type": "string", "minLength": 1 },
"sourceAgentId": { "type": "string", "minLength": 1 },
"sourceRole": { "type": "string", "minLength": 1 },
"tags": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
}
}
}

View file

@ -1,21 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.register.schema.json",
"title": "CultNet Register Message",
"type": "object",
"required": [
"schemaVersion",
"nonce",
"email",
"password",
"name"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.register.v0" },
"nonce": { "type": "string", "minLength": 1 },
"email": { "type": "string", "minLength": 1 },
"password": { "type": "string", "minLength": 1 },
"name": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,15 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.sample-change-name.schema.json",
"title": "CultNet Sample Change Name Message",
"type": "object",
"required": [
"schemaVersion",
"name"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.sample.change_name.v0" },
"name": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,15 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.sample-chat.schema.json",
"title": "CultNet Sample Chat Message",
"type": "object",
"required": [
"schemaVersion",
"text"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.sample.chat.v0" },
"text": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,31 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-catalog-request.schema.json",
"title": "CultNet Schema Catalog Request Message",
"type": "object",
"required": [
"schemaVersion",
"messageId"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.schema_catalog_request.v0" },
"messageId": { "type": "string", "minLength": 1 },
"includeSchemaJson": { "type": "boolean" },
"schemaIds": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"kinds": {
"type": "array",
"items": {
"type": "string",
"enum": [
"wire_message",
"document_payload",
"shared_contract"
]
}
}
}
}

View file

@ -1,22 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-catalog-response.schema.json",
"title": "CultNet Schema Catalog Response Message",
"type": "object",
"required": [
"schemaVersion",
"messageId",
"schemas"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.schema_catalog_response.v0" },
"messageId": { "type": "string", "minLength": 1 },
"schemas": {
"type": "array",
"items": {
"$ref": "./cultnet.schema-descriptor.schema.json"
}
}
}
}

View file

@ -1,39 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.schema-descriptor.schema.json",
"title": "CultNet Schema Descriptor",
"type": "object",
"required": [
"schemaId",
"kind",
"wireContracts",
"contentHash"
],
"additionalProperties": false,
"properties": {
"schemaId": { "type": "string", "minLength": 1 },
"kind": {
"type": "string",
"enum": [
"wire_message",
"document_payload",
"shared_contract"
]
},
"schemaVersion": { "type": "string", "minLength": 1 },
"documentType": { "type": "string", "minLength": 1 },
"title": { "type": "string", "minLength": 1 },
"wireContracts": {
"type": "array",
"items": {
"type": "string",
"enum": [
"cultnet.schema.v0",
"gamecult.networking.v0"
]
}
},
"contentHash": { "type": "string", "minLength": 1 },
"schemaJson": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,23 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-request.schema.json",
"title": "CultNet Snapshot Request Message",
"type": "object",
"required": [
"schemaVersion",
"messageId"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.snapshot_request.v0" },
"messageId": { "type": "string", "minLength": 1 },
"schemaIds": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"recordKeys": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
}
}
}

View file

@ -1,22 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-response-raw.schema.json",
"title": "CultNet Raw Snapshot Response Message",
"type": "object",
"required": [
"schemaVersion",
"messageId",
"documents"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.snapshot_response_raw.v0" },
"messageId": { "type": "string", "minLength": 1 },
"documents": {
"type": "array",
"items": {
"$ref": "./cultnet.raw-document-record.schema.json"
}
}
}
}

View file

@ -1,22 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.snapshot-response.schema.json",
"title": "CultNet Snapshot Response Message",
"type": "object",
"required": [
"schemaVersion",
"messageId",
"documents"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.snapshot_response.v0" },
"messageId": { "type": "string", "minLength": 1 },
"documents": {
"type": "array",
"items": {
"$ref": "./cultnet.document-record.schema.json"
}
}
}
}

View file

@ -1,81 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.transport-profile.schema.json",
"title": "CultNet Transport Profile",
"type": "object",
"required": [
"schemaVersion",
"runtimeId",
"transports"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.transport_profile.v0" },
"runtimeId": { "type": "string", "minLength": 1 },
"transports": {
"type": "array",
"items": {
"type": "object",
"required": [
"transportId",
"protocol",
"channels"
],
"additionalProperties": false,
"properties": {
"transportId": { "type": "string", "minLength": 1 },
"protocol": {
"type": "string",
"enum": [
"tcp_framed",
"litenetlib",
"websocket",
"rudp"
]
},
"host": { "type": "string", "minLength": 1 },
"port": { "type": "integer", "minimum": 1, "maximum": 65535 },
"path": { "type": "string", "minLength": 1 },
"discoveryGroup": { "type": "string", "minLength": 1 },
"wireContracts": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"channels": {
"type": "array",
"items": {
"type": "object",
"required": [
"channelId",
"delivery",
"ordering"
],
"additionalProperties": false,
"properties": {
"channelId": { "type": "string", "minLength": 1 },
"delivery": {
"type": "string",
"enum": [
"reliable",
"unreliable"
]
},
"ordering": {
"type": "string",
"enum": [
"ordered",
"unordered",
"sequenced"
]
},
"maxPayloadBytes": { "type": "integer", "minimum": 1 },
"maxFragmentBytes": { "type": "integer", "minimum": 1 },
"maxPendingReliablePackets": { "type": "integer", "minimum": 1 }
}
}
}
}
}
}
}
}

View file

@ -1,17 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/cultnet-ts/contracts/cultnet.verify.schema.json",
"title": "CultNet Verify Message",
"type": "object",
"required": [
"schemaVersion",
"nonce",
"session"
],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.verify.v0" },
"nonce": { "type": "string", "minLength": 1 },
"session": { "type": "string", "minLength": 1 }
}
}

View file

@ -1,845 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/Ghostlight/schemas/agent-state.schema.json",
"title": "Ghostlight Agent State Schema",
"description": "First canonical contract for Ghostlight agent, perception, relationship, event, scene, and dialogue-context state.",
"type": "object",
"required": [
"schema_version",
"world",
"agents",
"relationships",
"events",
"scenes"
],
"additionalProperties": false,
"properties": {
"schema_version": {
"const": "ghostlight.agent_state.v0"
},
"world": {
"$ref": "#/$defs/world_state"
},
"agents": {
"type": "array",
"items": {
"$ref": "#/$defs/agent"
}
},
"relationships": {
"type": "array",
"items": {
"$ref": "#/$defs/relationship"
}
},
"events": {
"type": "array",
"items": {
"$ref": "#/$defs/event"
}
},
"scenes": {
"type": "array",
"items": {
"$ref": "#/$defs/scene"
}
}
},
"$defs": {
"world_state": {
"type": "object",
"required": [
"world_id",
"setting",
"time",
"canon_context"
],
"additionalProperties": false,
"properties": {
"world_id": {
"type": "string"
},
"setting": {
"type": "string"
},
"time": {
"type": "object",
"required": [
"label"
],
"additionalProperties": true,
"properties": {
"label": {
"type": "string"
}
}
},
"canon_context": {
"type": "array",
"items": {
"type": "string"
}
},
"ambient_pressures": {
"type": "array",
"items": {
"$ref": "#/$defs/pressure"
}
}
}
},
"agent": {
"type": "object",
"required": [
"agent_id",
"identity",
"canonical_state",
"goals",
"memories",
"perceived_state_overlays"
],
"additionalProperties": false,
"properties": {
"agent_id": {
"type": "string"
},
"identity": {
"$ref": "#/$defs/identity"
},
"canonical_state": {
"$ref": "#/$defs/canonical_state"
},
"goals": {
"type": "array",
"items": {
"$ref": "#/$defs/goal"
}
},
"memories": {
"$ref": "#/$defs/memory_bundle"
},
"perceived_state_overlays": {
"type": "array",
"items": {
"$ref": "#/$defs/perceived_state_overlay"
}
}
}
},
"identity": {
"type": "object",
"required": [
"name",
"roles",
"origin",
"public_description"
],
"additionalProperties": false,
"properties": {
"name": {
"type": "string"
},
"roles": {
"type": "array",
"items": {
"type": "string"
}
},
"origin": {
"type": "string"
},
"public_description": {
"type": "string"
},
"private_notes": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"canonical_state": {
"type": "object",
"required": [
"underlying_organization",
"stable_dispositions",
"behavioral_dimensions",
"presentation_strategy",
"voice_style",
"situational_state",
"values"
],
"additionalProperties": false,
"properties": {
"underlying_organization": {
"$ref": "#/$defs/variable_map"
},
"stable_dispositions": {
"$ref": "#/$defs/variable_map"
},
"behavioral_dimensions": {
"$ref": "#/$defs/variable_map"
},
"presentation_strategy": {
"$ref": "#/$defs/variable_map"
},
"situational_state": {
"$ref": "#/$defs/variable_map"
},
"values": {
"type": "array",
"items": {
"$ref": "#/$defs/value_commitment"
}
},
"voice_style": {
"$ref": "#/$defs/variable_map"
}
}
},
"variable_map": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/state_variable"
}
},
"state_variable": {
"type": "object",
"required": [
"mean",
"plasticity",
"current_activation"
],
"additionalProperties": false,
"properties": {
"mean": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"plasticity": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"current_activation": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"evidence": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"value_commitment": {
"type": "object",
"required": [
"value_id",
"label",
"priority",
"unforgivable_if_betrayed"
],
"additionalProperties": false,
"properties": {
"value_id": {
"type": "string"
},
"label": {
"type": "string"
},
"priority": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"unforgivable_if_betrayed": {
"type": "boolean"
}
}
},
"goal": {
"type": "object",
"required": [
"goal_id",
"description",
"scope",
"priority",
"emotional_stake",
"status"
],
"additionalProperties": false,
"properties": {
"goal_id": {
"type": "string"
},
"description": {
"type": "string"
},
"scope": {
"enum": [
"immediate",
"scene",
"case",
"arc",
"life"
]
},
"priority": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"emotional_stake": {
"type": "string"
},
"blockers": {
"type": "array",
"items": {
"type": "string"
}
},
"status": {
"enum": [
"active",
"blocked",
"dormant",
"resolved",
"abandoned"
]
}
}
},
"memory_bundle": {
"type": "object",
"required": [
"episodic",
"semantic",
"relationship_summaries"
],
"additionalProperties": false,
"properties": {
"episodic": {
"type": "array",
"items": {
"$ref": "#/$defs/memory"
}
},
"semantic": {
"type": "array",
"items": {
"$ref": "#/$defs/memory"
}
},
"relationship_summaries": {
"type": "array",
"items": {
"$ref": "#/$defs/memory"
}
}
}
},
"memory": {
"type": "object",
"required": [
"memory_id",
"summary",
"salience",
"confidence"
],
"additionalProperties": false,
"properties": {
"memory_id": {
"type": "string"
},
"summary": {
"type": "string"
},
"salience": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"linked_event_ids": {
"type": "array",
"items": {
"type": "string"
}
},
"linked_relationship_id": {
"type": "string"
}
}
},
"perceived_state_overlay": {
"type": "object",
"required": [
"observer_agent_id",
"target_agent_id",
"perceived_dimensions",
"beliefs",
"distortions"
],
"additionalProperties": false,
"properties": {
"observer_agent_id": {
"type": "string"
},
"target_agent_id": {
"type": "string"
},
"perceived_dimensions": {
"$ref": "#/$defs/inferred_variable_map"
},
"beliefs": {
"type": "array",
"items": {
"$ref": "#/$defs/belief"
}
},
"distortions": {
"type": "array",
"items": {
"enum": [
"hostile_attribution",
"false_reassurance",
"overread_warmth",
"underread_threat",
"false_mask_detection",
"missed_mask_detection",
"status_injury",
"threat_amplification",
"institutional_suspicion_transfer",
"care_underread",
"mask_overfocus"
]
}
}
}
},
"belief": {
"type": "object",
"required": [
"belief_id",
"claim",
"confidence"
],
"additionalProperties": false,
"properties": {
"belief_id": {
"type": "string"
},
"claim": {
"type": "string"
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"subject_id": {
"type": "string"
},
"claim_type": {
"enum": [
"fact",
"identity_inference",
"motive_inference",
"prediction",
"norm",
"value_read",
"relationship_read"
]
},
"evidence_event_ids": {
"type": "array",
"items": {
"type": "string"
}
},
"visibility": {
"enum": [
"private",
"shared",
"public",
"rumor"
]
},
"emotional_charge": {
"type": "number",
"minimum": 0,
"maximum": 1
}
}
},
"relationship": {
"type": "object",
"required": [
"relationship_id",
"source_id",
"target_id",
"stance",
"summary"
],
"additionalProperties": false,
"properties": {
"relationship_id": {
"type": "string"
},
"source_id": {
"type": "string"
},
"target_id": {
"type": "string"
},
"stance": {
"$ref": "#/$defs/variable_map"
},
"summary": {
"type": "string"
},
"unresolved_incident_ids": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"event": {
"type": "object",
"required": [
"event_id",
"kind",
"summary",
"participants",
"pressure_tags"
],
"additionalProperties": false,
"properties": {
"event_id": {
"type": "string"
},
"kind": {
"enum": [
"dialogue",
"action",
"memory",
"relationship_shift",
"scene_outcome",
"author_note"
]
},
"summary": {
"type": "string"
},
"participants": {
"type": "array",
"items": {
"type": "string"
}
},
"pressure_tags": {
"type": "array",
"items": {
"type": "string"
}
},
"observed_exchange": {
"type": "array",
"items": {
"$ref": "#/$defs/event_exchange_turn"
}
},
"private_interpretations": {
"type": "array",
"items": {
"$ref": "#/$defs/event_private_interpretation"
}
},
"event_effects": {
"type": "array",
"items": {
"$ref": "#/$defs/event_effect"
}
}
}
},
"scene": {
"type": "object",
"required": [
"scene_id",
"location",
"participants",
"public_stakes",
"hidden_stakes",
"dialogue_context_packs"
],
"additionalProperties": false,
"properties": {
"scene_id": {
"type": "string"
},
"location": {
"type": "string"
},
"participants": {
"type": "array",
"items": {
"type": "string"
}
},
"public_stakes": {
"type": "array",
"items": {
"type": "string"
}
},
"hidden_stakes": {
"type": "array",
"items": {
"type": "string"
}
},
"dialogue_context_packs": {
"type": "array",
"items": {
"$ref": "#/$defs/dialogue_context_pack"
}
}
}
},
"dialogue_context_pack": {
"type": "object",
"required": [
"speaker_agent_id",
"listener_ids",
"speaker_local_truth",
"speaker_beliefs",
"active_memories",
"active_goals",
"presentation_constraints"
],
"additionalProperties": false,
"properties": {
"speaker_agent_id": {
"type": "string"
},
"listener_ids": {
"type": "array",
"items": {
"type": "string"
}
},
"speaker_local_truth": {
"type": "array",
"items": {
"type": "string"
}
},
"speaker_beliefs": {
"type": "array",
"items": {
"type": "string"
}
},
"active_memories": {
"type": "array",
"items": {
"type": "string"
}
},
"active_goals": {
"type": "array",
"items": {
"type": "string"
}
},
"presentation_constraints": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"pressure": {
"type": "object",
"required": [
"pressure_id",
"label",
"intensity"
],
"additionalProperties": false,
"properties": {
"pressure_id": {
"type": "string"
},
"label": {
"type": "string"
},
"intensity": {
"type": "number",
"minimum": 0,
"maximum": 1
}
}
},
"inferred_variable_map": {
"type": "object",
"additionalProperties": {
"$ref": "#/$defs/inferred_state_variable"
}
},
"inferred_state_variable": {
"type": "object",
"required": [
"observed_activation",
"attributed_disposition",
"confidence"
],
"additionalProperties": false,
"properties": {
"observed_activation": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"attributed_disposition": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1
},
"evidence": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"event_exchange_turn": {
"type": "object",
"required": [
"speaker_id",
"utterance_summary",
"dialogue_function"
],
"additionalProperties": false,
"properties": {
"speaker_id": {
"type": "string"
},
"utterance_summary": {
"type": "string"
},
"dialogue_function": {
"type": "string"
},
"observable_cues": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"event_private_interpretation": {
"type": "object",
"required": [
"agent_id",
"interpretation",
"confidence"
],
"additionalProperties": false,
"properties": {
"agent_id": {
"type": "string"
},
"interpretation": {
"type": "string"
},
"attributed_motive": {
"type": "string"
},
"appraisal_tags": {
"type": "array",
"items": {
"type": "string"
}
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1
}
}
},
"event_effect": {
"type": "object",
"required": [
"agent_id",
"summary"
],
"additionalProperties": false,
"properties": {
"agent_id": {
"type": "string"
},
"summary": {
"type": "string"
},
"state_deltas": {
"type": "array",
"items": {
"$ref": "#/$defs/state_delta"
}
},
"new_belief_ids": {
"type": "array",
"items": {
"type": "string"
}
},
"memory_update_ids": {
"type": "array",
"items": {
"type": "string"
}
}
}
},
"state_delta": {
"type": "object",
"required": [
"path",
"delta"
],
"additionalProperties": false,
"properties": {
"path": {
"type": "string"
},
"delta": {
"type": "number",
"minimum": -1,
"maximum": 1
}
}
}
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,49 +0,0 @@
use anyhow::Result;
use anyhow::anyhow;
pub const FRAME_HEADER_BYTES: usize = 4;
pub fn encode_frame(payload: &[u8]) -> Result<Vec<u8>> {
let len: u32 = payload
.len()
.try_into()
.map_err(|_| anyhow!("CultNet frame payload is too large"))?;
let mut frame = Vec::with_capacity(FRAME_HEADER_BYTES + payload.len());
frame.extend_from_slice(&len.to_be_bytes());
frame.extend_from_slice(payload);
Ok(frame)
}
#[derive(Clone, Debug, Default)]
pub struct LengthPrefixedMessageFramer {
buffer: Vec<u8>,
}
impl LengthPrefixedMessageFramer {
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, chunk: impl AsRef<[u8]>) -> Vec<Vec<u8>> {
self.buffer.extend_from_slice(chunk.as_ref());
let mut frames = Vec::new();
loop {
if self.buffer.len() < FRAME_HEADER_BYTES {
break;
}
let payload_len = u32::from_be_bytes([
self.buffer[0],
self.buffer[1],
self.buffer[2],
self.buffer[3],
]) as usize;
let total_len = FRAME_HEADER_BYTES + payload_len;
if self.buffer.len() < total_len {
break;
}
frames.push(self.buffer[FRAME_HEADER_BYTES..total_len].to_vec());
self.buffer.drain(0..total_len);
}
frames
}
}

View file

@ -1,19 +0,0 @@
mod contracts;
mod framing;
mod replication;
mod rudp;
mod schema_discovery;
mod security;
mod service_identity;
mod snapshot_query;
mod transport;
pub use contracts::*;
pub use framing::*;
pub use replication::*;
pub use rudp::*;
pub use schema_discovery::*;
pub use security::*;
pub use service_identity::*;
pub use snapshot_query::*;
pub use transport::*;

View file

@ -1,442 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use cultcache_rs::CultCache;
use cultcache_rs::CultCacheEnvelope;
use cultcache_rs::DatabaseEntry;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use crate::CultNetDocumentMutationContract;
use crate::CultNetDocumentRecord;
use crate::CultNetMessage;
use crate::CultNetRawDocumentRecord;
use crate::CultNetRawPayloadEncoding;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CultNetDocumentPutOptions {
pub stored_at: Option<String>,
pub source_runtime_id: Option<String>,
pub source_agent_id: Option<String>,
pub source_role: Option<String>,
pub tags: Option<Vec<String>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetDocumentBinding {
pub schema_id: String,
pub document_type: String,
pub mutation_contract: Option<CultNetDocumentMutationContract>,
pub payload_schema_version: Option<String>,
}
impl CultNetDocumentBinding {
pub fn for_entry<T: DatabaseEntry>(payload_schema_version: impl Into<Option<String>>) -> Self {
Self {
document_type: T::TYPE.to_string(),
schema_id: T::TYPE.to_string(),
mutation_contract: None,
payload_schema_version: payload_schema_version.into(),
}
}
pub fn for_entry_with_schema_id<T: DatabaseEntry>(
schema_id: impl Into<String>,
payload_schema_version: impl Into<Option<String>>,
) -> Self {
Self {
document_type: T::TYPE.to_string(),
schema_id: schema_id.into(),
mutation_contract: None,
payload_schema_version: payload_schema_version.into(),
}
}
pub fn with_mutation_contract(mut self, contract: CultNetDocumentMutationContract) -> Self {
self.mutation_contract = Some(contract);
self
}
}
#[derive(Clone, Debug, Default)]
pub struct CultNetDocumentRegistry {
bindings_by_type: BTreeMap<String, CultNetDocumentBinding>,
bindings_by_schema_id: BTreeMap<String, CultNetDocumentBinding>,
}
impl CultNetDocumentRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, binding: CultNetDocumentBinding) -> &mut Self {
self.bindings_by_schema_id
.insert(binding.schema_id.clone(), binding.clone());
self.bindings_by_type
.insert(binding.document_type.clone(), binding);
self
}
pub fn binding(&self, document_type: &str) -> Option<&CultNetDocumentBinding> {
self.bindings_by_type.get(document_type)
}
pub fn binding_by_schema_id(&self, schema_id: &str) -> Option<&CultNetDocumentBinding> {
self.bindings_by_schema_id.get(schema_id)
}
pub fn mutation_contracts(&self) -> Vec<CultNetDocumentMutationContract> {
self.bindings_by_type
.values()
.filter_map(|binding| binding.mutation_contract.clone())
.collect()
}
pub fn create_document_put_message<T>(
&self,
message_id: impl Into<String>,
record_key: impl Into<String>,
value: &T,
options: CultNetDocumentPutOptions,
) -> Result<CultNetMessage>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let binding = self.require_binding(T::TYPE)?;
let payload = serde_json::to_value(round_trip_typed(value)?)?;
Ok(CultNetMessage::DocumentPut {
message_id: message_id.into(),
document: CultNetDocumentRecord {
schema_id: binding.schema_id.clone(),
record_key: record_key.into(),
stored_at: options.stored_at.unwrap_or_else(now_utc_second),
payload,
source_runtime_id: options.source_runtime_id,
source_agent_id: options.source_agent_id,
source_role: options.source_role,
tags: options.tags,
},
})
}
pub fn create_document_delete_message(
&self,
message_id: impl Into<String>,
schema_id: impl Into<String>,
record_key: impl Into<String>,
) -> CultNetMessage {
CultNetMessage::DocumentDelete {
message_id: message_id.into(),
schema_id: schema_id.into(),
record_key: record_key.into(),
}
}
pub fn create_raw_document_put_message_from_envelope(
&self,
message_id: impl Into<String>,
envelope: &CultCacheEnvelope,
) -> Result<CultNetMessage> {
Ok(CultNetMessage::DocumentPutRaw {
message_id: message_id.into(),
document: self.raw_document_record_from_envelope(envelope)?,
})
}
pub fn create_raw_document_put_message<T>(
&self,
message_id: impl Into<String>,
record_key: impl Into<String>,
value: &T,
options: CultNetDocumentPutOptions,
) -> Result<CultNetMessage>
where
T: DatabaseEntry + Serialize,
{
let binding = self.require_binding(T::TYPE)?;
Ok(CultNetMessage::DocumentPutRaw {
message_id: message_id.into(),
document: CultNetRawDocumentRecord {
schema_id: binding.schema_id.clone(),
record_key: record_key.into(),
stored_at: options.stored_at.unwrap_or_else(now_utc_second),
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
payload: rmp_serde::to_vec(value)?,
source_runtime_id: options.source_runtime_id,
source_agent_id: options.source_agent_id,
source_role: options.source_role,
tags: options.tags,
},
})
}
pub fn create_snapshot_response(
&self,
cache: &CultCache,
message_id: impl Into<String>,
schema_ids: Option<&[String]>,
record_keys: Option<&[String]>,
) -> Result<CultNetMessage> {
let requested_schema_ids = schema_ids.map(|items| items.iter().collect::<BTreeSet<_>>());
let requested_record_keys = record_keys.map(|items| items.iter().collect::<BTreeSet<_>>());
let mut documents = Vec::new();
for envelope in cache.snapshot() {
let binding = self.require_binding(&envelope.r#type)?;
if requested_schema_ids
.as_ref()
.is_some_and(|ids| !ids.contains(&binding.schema_id))
{
continue;
}
if requested_record_keys
.as_ref()
.is_some_and(|keys| !keys.contains(&envelope.key))
{
continue;
}
documents.push(self.document_record_from_envelope(&envelope)?);
}
Ok(CultNetMessage::SnapshotResponse {
message_id: message_id.into(),
documents,
})
}
pub fn create_raw_snapshot_response(
&self,
cache: &CultCache,
message_id: impl Into<String>,
schema_ids: Option<&[String]>,
record_keys: Option<&[String]>,
) -> Result<CultNetMessage> {
let requested_schema_ids = schema_ids.map(|items| items.iter().collect::<BTreeSet<_>>());
let requested_record_keys = record_keys.map(|items| items.iter().collect::<BTreeSet<_>>());
let mut documents = Vec::new();
for envelope in cache.snapshot() {
let binding = self.require_binding(&envelope.r#type)?;
if requested_schema_ids
.as_ref()
.is_some_and(|ids| !ids.contains(&binding.schema_id))
{
continue;
}
if requested_record_keys
.as_ref()
.is_some_and(|keys| !keys.contains(&envelope.key))
{
continue;
}
documents.push(self.raw_document_record_from_envelope(&envelope)?);
}
Ok(CultNetMessage::SnapshotResponseRaw {
message_id: message_id.into(),
documents,
})
}
pub fn apply_document_put_message<T>(
&self,
cache: &mut CultCache,
message: &CultNetMessage,
) -> Result<T>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let CultNetMessage::DocumentPut { document, .. } = message else {
return Err(anyhow!("expected cultnet.document_put.v0"));
};
let binding = self.require_binding(T::TYPE)?;
if document.schema_id != binding.schema_id {
return Err(anyhow!(
"schema id {:?} does not match registered Rust type {:?} schema {:?}",
document.schema_id,
T::TYPE,
binding.schema_id
));
}
let value: T = serde_json::from_value(document.payload.clone()).with_context(|| {
format!(
"failed to decode CultNet payload schema {:?} as {}",
binding.schema_id,
T::SCHEMA_NAME
)
})?;
cache.put(&document.record_key, &value)
}
pub fn apply_document_delete_message<T>(
&self,
cache: &mut CultCache,
message: &CultNetMessage,
) -> Result<bool>
where
T: DatabaseEntry,
{
let CultNetMessage::DocumentDelete {
schema_id,
record_key,
..
} = message
else {
return Err(anyhow!("expected cultnet.document_delete.v0"));
};
let binding = self.require_binding(T::TYPE)?;
if schema_id != &binding.schema_id {
return Err(anyhow!(
"schema id {:?} does not match registered Rust type {:?} schema {:?}",
schema_id,
T::TYPE,
binding.schema_id
));
}
cache.delete::<T>(record_key)
}
pub fn apply_raw_document_put_message<T>(
&self,
cache: &mut CultCache,
message: &CultNetMessage,
) -> Result<T>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let CultNetMessage::DocumentPutRaw { document, .. } = message else {
return Err(anyhow!("expected cultnet.document_put_raw.v0"));
};
let binding = self.require_binding(T::TYPE)?;
if document.schema_id != binding.schema_id {
return Err(anyhow!(
"schema id {:?} does not match registered Rust type {:?} schema {:?}",
document.schema_id,
T::TYPE,
binding.schema_id
));
}
cache.put_envelope::<T>(CultCacheEnvelope {
key: document.record_key.clone(),
r#type: binding.document_type.clone(),
payload: document.payload.clone(),
stored_at: document.stored_at.clone(),
schema_id: Some(binding.schema_id.clone()),
})
}
pub fn apply_snapshot_response<T>(
&self,
cache: &mut CultCache,
response: &CultNetMessage,
) -> Result<Vec<T>>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let CultNetMessage::SnapshotResponse { documents, .. } = response else {
return Err(anyhow!("expected cultnet.snapshot_response.v0"));
};
let mut applied = Vec::new();
let binding = self.require_binding(T::TYPE)?;
for document in documents {
if document.schema_id != binding.schema_id {
continue;
}
applied.push(self.apply_document_put_message::<T>(
cache,
&CultNetMessage::DocumentPut {
message_id: "snapshot-apply".to_string(),
document: document.clone(),
},
)?);
}
Ok(applied)
}
pub fn apply_raw_snapshot_response<T>(
&self,
cache: &mut CultCache,
response: &CultNetMessage,
) -> Result<Vec<T>>
where
T: DatabaseEntry + Serialize + DeserializeOwned,
{
let CultNetMessage::SnapshotResponseRaw { documents, .. } = response else {
return Err(anyhow!("expected cultnet.snapshot_response_raw.v0"));
};
let mut applied = Vec::new();
let binding = self.require_binding(T::TYPE)?;
for document in documents {
if document.schema_id != binding.schema_id {
continue;
}
applied.push(self.apply_raw_document_put_message::<T>(
cache,
&CultNetMessage::DocumentPutRaw {
message_id: "snapshot-apply-raw".to_string(),
document: document.clone(),
},
)?);
}
Ok(applied)
}
fn document_record_from_envelope(
&self,
envelope: &CultCacheEnvelope,
) -> Result<CultNetDocumentRecord<Value>> {
let binding = self.require_binding(&envelope.r#type)?;
let payload: Value = rmp_serde::from_slice(&envelope.payload).with_context(|| {
format!(
"failed to decode CultCache envelope {:?} at {:?} as generic CultNet payload",
envelope.r#type, envelope.key
)
})?;
Ok(CultNetDocumentRecord {
schema_id: binding.schema_id.clone(),
record_key: envelope.key.clone(),
stored_at: envelope.stored_at.clone(),
payload,
source_runtime_id: None,
source_agent_id: None,
source_role: None,
tags: None,
})
}
/// Project a stored CultCache envelope as a raw CultNet record without
/// decoding or re-encoding its payload bytes.
pub fn raw_document_record_from_envelope(
&self,
envelope: &CultCacheEnvelope,
) -> Result<CultNetRawDocumentRecord> {
let binding = self.require_binding(&envelope.r#type)?;
Ok(CultNetRawDocumentRecord {
schema_id: binding.schema_id.clone(),
record_key: envelope.key.clone(),
stored_at: envelope.stored_at.clone(),
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
payload: envelope.payload.clone(),
source_runtime_id: None,
source_agent_id: None,
source_role: None,
tags: None,
})
}
fn require_binding(&self, document_type: &str) -> Result<&CultNetDocumentBinding> {
self.binding(document_type).ok_or_else(|| {
anyhow!("No CultNet document binding is registered for {document_type:?}")
})
}
}
fn round_trip_typed<T>(value: &T) -> Result<T>
where
T: Serialize + DeserializeOwned,
{
Ok(rmp_serde::from_slice(&rmp_serde::to_vec(value)?)?)
}
fn now_utc_second() -> String {
chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

File diff suppressed because it is too large Load diff

View file

@ -1,396 +0,0 @@
use anyhow::Result;
use anyhow::anyhow;
use serde_json::Value;
use sha2::Digest;
use sha2::Sha256;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use crate::CultNetMessage;
use crate::CultNetSchemaDescriptor;
use crate::CultNetSchemaKind;
use crate::CultNetWireContract;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetSchemaRegistration {
pub schema_id: String,
pub kind: CultNetSchemaKind,
pub wire_contracts: Vec<CultNetWireContract>,
pub schema_version: Option<String>,
pub document_type: Option<String>,
pub title: Option<String>,
pub schema_json: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CultNetSchemaCatalogOptions {
pub include_schema_json: bool,
pub schema_ids: Option<Vec<String>>,
pub kinds: Option<Vec<CultNetSchemaKind>>,
}
#[derive(Clone, Debug, Default)]
pub struct CultNetSchemaRegistry {
entries: BTreeMap<String, CultNetSchemaDescriptor>,
}
impl CultNetSchemaRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, registration: CultNetSchemaRegistration) -> Result<()> {
if registration.schema_id.trim().is_empty() {
return Err(anyhow!("schema_id must be non-empty"));
}
if registration.wire_contracts.is_empty() {
return Err(anyhow!("wire_contracts must contain at least one entry"));
}
let content_hash = if let Some(schema_json) = registration.schema_json.as_deref() {
canonical_schema_hash(schema_json)?
} else {
return Err(anyhow!(
"schema_json is required so discovery can advertise canonical hashes"
));
};
self.entries.insert(
registration.schema_id.clone(),
CultNetSchemaDescriptor {
schema_id: registration.schema_id,
kind: registration.kind,
schema_version: registration.schema_version,
document_type: registration.document_type,
title: registration.title,
wire_contracts: registration.wire_contracts,
content_hash,
schema_json: registration.schema_json,
},
);
Ok(())
}
pub fn get(
&self,
schema_id: &str,
include_schema_json: bool,
) -> Option<CultNetSchemaDescriptor> {
self.entries
.get(schema_id)
.map(|entry| sanitize_descriptor(entry, include_schema_json))
}
pub fn list(&self, options: &CultNetSchemaCatalogOptions) -> Vec<CultNetSchemaDescriptor> {
let requested_ids = options
.schema_ids
.as_ref()
.map(|values| values.iter().cloned().collect::<BTreeSet<_>>());
let requested_kinds = options
.kinds
.as_ref()
.map(|values| values.iter().copied().collect::<BTreeSet<_>>());
self.entries
.values()
.filter(|entry| {
if let Some(requested_ids) = &requested_ids
&& !requested_ids.contains(&entry.schema_id)
{
return false;
}
if let Some(requested_kinds) = &requested_kinds
&& !requested_kinds.contains(&entry.kind)
{
return false;
}
true
})
.map(|entry| sanitize_descriptor(entry, options.include_schema_json))
.collect()
}
pub fn create_catalog_response(&self, request: &CultNetMessage) -> Result<CultNetMessage> {
let CultNetMessage::SchemaCatalogRequest {
message_id,
include_schema_json,
schema_ids,
kinds,
} = request
else {
return Err(anyhow!(
"expected cultnet.schema_catalog_request.v0 for schema discovery"
));
};
Ok(CultNetMessage::SchemaCatalogResponse {
message_id: message_id.clone(),
schemas: self.list(&CultNetSchemaCatalogOptions {
include_schema_json: include_schema_json.unwrap_or(false),
schema_ids: schema_ids.clone(),
kinds: kinds.clone(),
}),
})
}
}
fn sanitize_descriptor(
descriptor: &CultNetSchemaDescriptor,
include_schema_json: bool,
) -> CultNetSchemaDescriptor {
let mut clone = descriptor.clone();
if !include_schema_json {
clone.schema_json = None;
}
clone
}
fn canonical_schema_hash(schema_json: &str) -> Result<String> {
let value: Value = serde_json::from_str(schema_json)?;
let canonical = stable_stringify(&value);
Ok(format!("{:x}", Sha256::digest(canonical.as_bytes())))
}
fn stable_stringify(value: &Value) -> String {
match value {
Value::Null => "null".to_string(),
Value::Bool(value) => value.to_string(),
Value::Number(value) => value.to_string(),
Value::String(value) => serde_json::to_string(value).expect("string serialization"),
Value::Array(values) => format!(
"[{}]",
values
.iter()
.map(stable_stringify)
.collect::<Vec<_>>()
.join(",")
),
Value::Object(values) => {
let mut entries = values.iter().collect::<Vec<_>>();
entries.sort_by(|(left, _), (right, _)| left.cmp(right));
format!(
"{{{}}}",
entries
.into_iter()
.map(|(key, value)| {
format!(
"{}:{}",
serde_json::to_string(key).expect("key serialization"),
stable_stringify(value)
)
})
.collect::<Vec<_>>()
.join(",")
)
}
}
}
pub fn builtin_schema_registry() -> Result<CultNetSchemaRegistry> {
let mut registry = CultNetSchemaRegistry::new();
for registration in [
schema_registration(
include_str!("../contracts/cultnet.hello.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.hello.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.document-mutation-contract.schema.json"),
CultNetSchemaKind::SharedContract,
vec![CultNetWireContract::CultNetSchemaV0],
None,
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.transport-profile.schema.json"),
CultNetSchemaKind::SharedContract,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.transport_profile.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.login.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.login.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.register.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.register.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.verify.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.verify.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.login-success.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.login_success.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.error.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.error.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.sample-change-name.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.sample.change_name.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.sample-chat.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.sample.chat.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.document-put.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.document_put.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.document-delete.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.document_delete.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.raw-document-record.schema.json"),
CultNetSchemaKind::SharedContract,
vec![CultNetWireContract::CultNetSchemaV0],
None,
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.document-put-raw.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.document_put_raw.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.snapshot-request.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.snapshot_request.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.snapshot-response.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.snapshot_response.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.snapshot-response-raw.schema.json"),
CultNetSchemaKind::WireMessage,
vec![CultNetWireContract::CultNetSchemaV0],
Some("cultnet.snapshot_response_raw.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.schema-catalog-request.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.schema_catalog_request.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/cultnet.schema-catalog-response.schema.json"),
CultNetSchemaKind::WireMessage,
vec![
CultNetWireContract::CultNetSchemaV0,
CultNetWireContract::GameCultNetworkingV0,
],
Some("cultnet.schema_catalog_response.v0"),
None,
)?,
schema_registration(
include_str!("../contracts/ghostlight.agent-state.schema.json"),
CultNetSchemaKind::DocumentPayload,
vec![CultNetWireContract::CultNetSchemaV0],
Some("ghostlight.agent_state.v0"),
Some("ghostlight.agent-state"),
)?,
] {
registry.register(registration)?;
}
Ok(registry)
}
fn schema_registration(
schema_json: &str,
kind: CultNetSchemaKind,
wire_contracts: Vec<CultNetWireContract>,
schema_version: Option<&str>,
document_type: Option<&str>,
) -> Result<CultNetSchemaRegistration> {
let value: Value = serde_json::from_str(schema_json)?;
let schema_id = value
.get("$id")
.and_then(Value::as_str)
.ok_or_else(|| anyhow!("schema is missing $id"))?;
let title = value
.get("title")
.and_then(Value::as_str)
.map(str::to_string);
Ok(CultNetSchemaRegistration {
schema_id: schema_id.to_string(),
kind,
wire_contracts,
schema_version: schema_version.map(str::to_string),
document_type: document_type.map(str::to_string),
title,
schema_json: Some(schema_json.to_string()),
})
}

View file

@ -1,270 +0,0 @@
use aes_gcm::Aes256Gcm;
use aes_gcm::KeyInit;
use aes_gcm::Nonce;
use aes_gcm::aead::Aead;
use aes_gcm::aead::Payload;
use anyhow::Result;
use anyhow::anyhow;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use chrono::DateTime;
use chrono::TimeZone;
use chrono::Utc;
use hmac::Hmac;
use hmac::Mac;
use rand::RngCore;
use sha2::Digest;
use sha2::Sha256;
const NONCE_LENGTH: usize = 12;
type HmacSha256 = Hmac<Sha256>;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetClientSecurityOptions {
pub connection_key: String,
encryption_key: [u8; 32],
}
impl CultNetClientSecurityOptions {
pub fn new(connection_key: impl Into<String>) -> Result<Self> {
let connection_key = connection_key.into();
if connection_key.trim().is_empty() {
return Err(anyhow!("Connection key must be provided"));
}
let encryption_key = sha256(connection_key.as_bytes());
Ok(Self {
connection_key,
encryption_key,
})
}
pub fn development() -> Self {
Self::new("gamecult-dev-connection-key").expect("development key is valid")
}
pub fn encryption_key(&self) -> [u8; 32] {
self.encryption_key
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetServerSecurityOptions {
client: CultNetClientSecurityOptions,
pub session_signing_secret: String,
session_signing_key: [u8; 32],
pub is_development: bool,
}
impl CultNetServerSecurityOptions {
pub fn new(
connection_key: impl Into<String>,
session_signing_secret: impl Into<String>,
is_development: bool,
) -> Result<Self> {
let session_signing_secret = session_signing_secret.into();
if session_signing_secret.trim().is_empty() {
return Err(anyhow!("Session signing secret must be provided"));
}
Ok(Self {
client: CultNetClientSecurityOptions::new(connection_key)?,
session_signing_key: sha256(session_signing_secret.as_bytes()),
session_signing_secret,
is_development,
})
}
pub fn development() -> Self {
Self::new(
"gamecult-dev-connection-key",
"gamecult-dev-session-signing-secret",
true,
)
.expect("development security config is valid")
}
pub fn to_client_options(&self) -> CultNetClientSecurityOptions {
self.client.clone()
}
pub fn encryption_key(&self) -> [u8; 32] {
self.client.encryption_key()
}
pub fn session_signing_key(&self) -> [u8; 32] {
self.session_signing_key
}
}
pub trait CultNetEncryptionOptions {
fn encryption_key(&self) -> [u8; 32];
}
impl CultNetEncryptionOptions for CultNetClientSecurityOptions {
fn encryption_key(&self) -> [u8; 32] {
self.encryption_key()
}
}
impl CultNetEncryptionOptions for CultNetServerSecurityOptions {
fn encryption_key(&self) -> [u8; 32] {
self.encryption_key()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ValidatedCultNetSessionToken {
pub user_id: String,
pub expires_at_utc: DateTime<Utc>,
}
pub struct CultNetSecret;
impl CultNetSecret {
pub fn new_nonce() -> [u8; NONCE_LENGTH] {
let mut nonce = [0_u8; NONCE_LENGTH];
rand::rng().fill_bytes(&mut nonce);
nonce
}
pub fn encrypt_string(
input: Option<&str>,
nonce: &[u8],
options: &impl CultNetEncryptionOptions,
) -> Result<Option<Vec<u8>>> {
let Some(input) = input.filter(|value| !value.is_empty()) else {
return Ok(None);
};
Ok(Some(Self::encrypt_bytes(input.as_bytes(), nonce, options)?))
}
pub fn decrypt_string(
encrypted: Option<&[u8]>,
nonce: Option<&[u8]>,
options: &impl CultNetEncryptionOptions,
) -> Result<Option<String>> {
let (Some(encrypted), Some(nonce)) = (encrypted, nonce) else {
return Ok(None);
};
let bytes = Self::decrypt_bytes(encrypted, nonce, options)?;
Ok(Some(String::from_utf8(bytes)?))
}
pub fn encrypt_bytes(
input: &[u8],
nonce: &[u8],
options: &impl CultNetEncryptionOptions,
) -> Result<Vec<u8>> {
let nonce = validate_nonce(nonce)?;
let cipher = Aes256Gcm::new_from_slice(&options.encryption_key())?;
let encrypted = cipher
.encrypt(
Nonce::from_slice(nonce),
Payload {
msg: input,
aad: &[],
},
)
.map_err(|_| anyhow!("AES-GCM encryption failed"))?;
Ok(encrypted)
}
pub fn decrypt_bytes(
encrypted: &[u8],
nonce: &[u8],
options: &impl CultNetEncryptionOptions,
) -> Result<Vec<u8>> {
let nonce = validate_nonce(nonce)?;
let cipher = Aes256Gcm::new_from_slice(&options.encryption_key())?;
cipher
.decrypt(
Nonce::from_slice(nonce),
Payload {
msg: encrypted,
aad: &[],
},
)
.map_err(|_| anyhow!("AES-GCM decryption failed"))
}
pub fn create_session_token(
user_id: &str,
expires_at_utc: DateTime<Utc>,
options: &CultNetServerSecurityOptions,
) -> Result<String> {
let payload = format!("{}|{}", user_id, expires_at_utc.timestamp());
let signature = hmac_sha256(&options.session_signing_key(), payload.as_bytes())?;
Ok(format!(
"{}.{}",
URL_SAFE_NO_PAD.encode(payload.as_bytes()),
URL_SAFE_NO_PAD.encode(signature)
))
}
pub fn try_validate_session_token(
token: Option<&str>,
options: &CultNetServerSecurityOptions,
) -> Result<Option<ValidatedCultNetSessionToken>> {
let Some(token) = token.filter(|value| !value.trim().is_empty()) else {
return Ok(None);
};
let Some((payload_part, signature_part)) = token.split_once('.') else {
return Ok(None);
};
let payload = URL_SAFE_NO_PAD.decode(payload_part)?;
let signature = URL_SAFE_NO_PAD.decode(signature_part)?;
let expected = hmac_sha256(&options.session_signing_key(), &payload)?;
if !constant_time_eq(&signature, &expected) {
return Ok(None);
}
let payload = String::from_utf8(payload)?;
let Some((user_id, expires_at)) = payload.split_once('|') else {
return Ok(None);
};
let expires_at_seconds: i64 = expires_at.parse()?;
let Some(expires_at_utc) = Utc.timestamp_opt(expires_at_seconds, 0).single() else {
return Ok(None);
};
if expires_at_utc <= Utc::now() {
return Ok(None);
}
Ok(Some(ValidatedCultNetSessionToken {
user_id: user_id.to_string(),
expires_at_utc,
}))
}
pub fn to_base64_url(input: &[u8]) -> String {
URL_SAFE_NO_PAD.encode(input)
}
pub fn from_base64_url(input: &str) -> Result<Vec<u8>> {
Ok(URL_SAFE_NO_PAD.decode(input)?)
}
}
fn validate_nonce(nonce: &[u8]) -> Result<&[u8]> {
if nonce.len() != NONCE_LENGTH {
return Err(anyhow!("Invalid nonce"));
}
Ok(nonce)
}
fn sha256(input: &[u8]) -> [u8; 32] {
Sha256::digest(input).into()
}
fn hmac_sha256(key: &[u8], input: &[u8]) -> Result<Vec<u8>> {
let mut mac = <HmacSha256 as Mac>::new_from_slice(key)?;
mac.update(input);
Ok(mac.finalize().into_bytes().to_vec())
}
fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
if left.len() != right.len() {
return false;
}
left.iter()
.zip(right)
.fold(0_u8, |acc, (left, right)| acc | (left ^ right))
== 0
}

View file

@ -1,635 +0,0 @@
use anyhow::{Context, Result, anyhow, bail};
use cultcache_rs::{
CacheBackingStore, CultCacheEnvelope, CultCacheExpectedEnvelope,
SingleFileMessagePackBackingStore,
};
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand::RngCore;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::marker::PhantomData;
use std::path::Path;
pub const WINDOWS_SERVICE_IDENTITY_ASSURANCE: &str = "os_user_installation_bound_best_effort";
pub const LINUX_SERVICE_IDENTITY_ASSURANCE: &str = "os_installation_file_bound_cloneable_baseline";
/// Fixes every authority-bearing name at the call site. A service cannot open
/// another service's identity by supplying a convenient runtime string.
pub trait ServiceIdentityProfile: Send + Sync + 'static {
const PRIVATE_TYPE: &'static str;
const PRIVATE_SCHEMA: &'static str;
const PRIVATE_KEY: &'static str;
const TRUST_ANCHOR_TYPE: &'static str;
const TRUST_ANCHOR_SCHEMA: &'static str;
const TRUST_ANCHOR_KEY: &'static str;
const ID_DOMAIN: &'static [u8];
const SIGNATURE_DOMAIN: &'static [u8];
const PROTECTOR_CONTEXT: &'static str;
}
/// A purpose is a type, not caller-provided prose. Protocol implementations
/// define one zero-sized type per signed statement kind.
pub trait ServiceSignaturePurpose<P: ServiceIdentityProfile>: Send + Sync + 'static {
const PURPOSE: &'static [u8];
}
pub enum IdunnServiceIdentity {}
pub enum GameCultProviderHealthIdentity {}
pub struct IdunnSignedDaemonHealthPurpose;
impl ServiceSignaturePurpose<GameCultProviderHealthIdentity>
for IdunnSignedDaemonHealthPurpose
{
const PURPOSE: &'static [u8] = b"idunn.signed_daemon_health.v1";
}
impl ServiceIdentityProfile for GameCultProviderHealthIdentity {
const PRIVATE_TYPE: &'static str = "gamecult.provider_health_identity.private.v1";
const PRIVATE_SCHEMA: &'static str = "gamecult.provider_health_identity.private.v1";
const PRIVATE_KEY: &'static str = "gamecult-provider-health-identity";
const TRUST_ANCHOR_TYPE: &'static str = "gamecult.provider_health_identity.trust_anchor.v1";
const TRUST_ANCHOR_SCHEMA: &'static str = "gamecult.provider_health_identity.trust_anchor.v1";
const TRUST_ANCHOR_KEY: &'static str = "gamecult-provider-health-identity-public";
const ID_DOMAIN: &'static [u8] = b"gamecult.provider-health.identity.v1\0";
const SIGNATURE_DOMAIN: &'static [u8] = b"gamecult.provider-health.signature.v1\0";
const PROTECTOR_CONTEXT: &'static str = "gamecult-provider-health-identity-v1";
}
/// The only signing purpose accepted for Idunn's public projection of a
/// provider-authenticated health admission. Keeping this profile here makes
/// purpose selection a compile-time protocol choice rather than caller text.
pub struct IdunnAuthenticatedProviderHealthProjectionPurpose;
impl ServiceSignaturePurpose<IdunnServiceIdentity>
for IdunnAuthenticatedProviderHealthProjectionPurpose
{
const PURPOSE: &'static [u8] = b"idunn.authenticated-provider-health-projection.v1";
}
impl ServiceIdentityProfile for IdunnServiceIdentity {
const PRIVATE_TYPE: &'static str = "idunn.service_identity.private.v1";
const PRIVATE_SCHEMA: &'static str = "idunn.service_identity.private.v1";
const PRIVATE_KEY: &'static str = "idunn-service-identity";
const TRUST_ANCHOR_TYPE: &'static str = "idunn.service_identity.trust_anchor.v1";
const TRUST_ANCHOR_SCHEMA: &'static str = "idunn.service_identity.trust_anchor.v1";
const TRUST_ANCHOR_KEY: &'static str = "idunn-service-identity-public";
const ID_DOMAIN: &'static [u8] = b"idunn.service-identity.id.v1\0";
const SIGNATURE_DOMAIN: &'static [u8] = b"idunn.service-identity.signature.v1\0";
const PROTECTOR_CONTEXT: &'static str = "idunn-service-identity-v1";
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ServiceIdentityPrivateEntry {
pub schema_version: String,
pub identity_id: String,
pub public_key: Vec<u8>,
pub protected_private_seed: Vec<u8>,
pub protector_kind: String,
pub protector_binding: String,
pub protector_version: String,
pub assurance: String,
pub created_at: String,
pub enrollment_nonce: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServiceIdentityTrustAnchor {
pub schema_version: String,
pub identity_id: String,
pub public_key: Vec<u8>,
pub assurance: String,
pub identity_created_at: String,
pub source_identity_record_sha256: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServiceIdentitySignature {
pub identity_id: String,
pub signature: Vec<u8>,
}
/// The only value holding unprotected key material. It exposes signing, never
/// seed export or access to the underlying signing key.
pub struct ServiceIdentitySigner<P: ServiceIdentityProfile> {
entry: ServiceIdentityPrivateEntry,
signing_key: SigningKey,
profile: PhantomData<P>,
}
impl<P: ServiceIdentityProfile> ServiceIdentitySigner<P> {
pub fn entry(&self) -> &ServiceIdentityPrivateEntry {
&self.entry
}
pub fn trust_anchor(&self) -> Result<ServiceIdentityTrustAnchor> {
Ok(ServiceIdentityTrustAnchor {
schema_version: P::TRUST_ANCHOR_SCHEMA.into(),
identity_id: self.entry.identity_id.clone(),
public_key: self.entry.public_key.clone(),
assurance: self.entry.assurance.clone(),
identity_created_at: self.entry.created_at.clone(),
source_identity_record_sha256: format!(
"sha256-{}",
hex(&Sha256::digest(rmp_serde::to_vec(&self.entry)?))
),
})
}
pub fn sign<S: ServiceSignaturePurpose<P>>(&self, payload: &[u8]) -> ServiceIdentitySignature {
ServiceIdentitySignature {
identity_id: self.entry.identity_id.clone(),
signature: self
.signing_key
.sign(&signing_message::<P, S>(payload))
.to_bytes()
.to_vec(),
}
}
}
pub fn enroll_service_identity_at<P: ServiceIdentityProfile>(
path: &Path,
) -> Result<ServiceIdentitySigner<P>> {
if path.exists() {
bail!(
"service identity store {} already exists; enrollment is immutable",
path.display()
);
}
prepare_parent(path)?;
let mut seed = [0u8; 32];
rand::rng().fill_bytes(&mut seed);
let signing_key = SigningKey::from_bytes(&seed);
let mut nonce = [0u8; 32];
rand::rng().fill_bytes(&mut nonce);
let public_key = signing_key.verifying_key().to_bytes();
let binding = platform_binding::<P>()?;
let entry = ServiceIdentityPrivateEntry {
schema_version: P::PRIVATE_SCHEMA.into(),
identity_id: identity_id::<P>(&public_key),
public_key: public_key.to_vec(),
protected_private_seed: protect_seed::<P>(&seed, &binding)?,
protector_kind: platform_protector_kind().into(),
protector_binding: binding,
protector_version: "v1".into(),
assurance: platform_assurance().into(),
created_at: chrono::Utc::now().to_rfc3339(),
enrollment_nonce: nonce.to_vec(),
};
validate_private::<P>(&entry)?;
let envelope = private_envelope::<P>(&entry)?;
let backing = SingleFileMessagePackBackingStore::new(path);
let expected = CultCacheExpectedEnvelope {
r#type: P::PRIVATE_TYPE.into(),
key: P::PRIVATE_KEY.into(),
current: None,
};
if !backing.compare_exchange(&[expected], &[envelope])? {
bail!("service identity enrollment lost atomic create race; refusing existing state");
}
harden_store_permissions(path)?;
open_service_identity_at::<P>(path)
}
pub fn open_service_identity_at<P: ServiceIdentityProfile>(
path: &Path,
) -> Result<ServiceIdentitySigner<P>> {
if !path.is_file() {
bail!("service identity store {} does not exist", path.display());
}
let entries = SingleFileMessagePackBackingStore::new(path).pull_all()?;
if entries.len() != 1 {
bail!("service identity store must contain exactly one immutable envelope");
}
let envelope = &entries[0];
if envelope.r#type != P::PRIVATE_TYPE
|| envelope.key != P::PRIVATE_KEY
|| envelope.schema_id.as_deref() != Some(P::PRIVATE_SCHEMA)
{
bail!("service identity store belongs to a different profile or schema");
}
let entry: ServiceIdentityPrivateEntry = rmp_serde::from_slice(&envelope.payload)
.context("service identity private payload is malformed MessagePack")?;
validate_private::<P>(&entry)?;
if entry.protector_kind != platform_protector_kind() || entry.assurance != platform_assurance()
{
bail!("service identity protector does not belong to this platform implementation");
}
let binding = platform_binding::<P>()?;
if entry.protector_binding != binding {
bail!("service identity protector binding does not match this OS installation or profile");
}
let seed: [u8; 32] = unprotect_seed::<P>(&entry.protected_private_seed, &binding)?
.try_into()
.map_err(|_| anyhow!("unprotected service identity seed has invalid length"))?;
let signing_key = SigningKey::from_bytes(&seed);
if signing_key.verifying_key().to_bytes().as_slice() != entry.public_key.as_slice() {
bail!("service identity private seed does not match enrolled public key");
}
Ok(ServiceIdentitySigner {
entry,
signing_key,
profile: PhantomData,
})
}
pub fn export_service_identity_trust_anchor<P: ServiceIdentityProfile>(
signer: &ServiceIdentitySigner<P>,
path: &Path,
) -> Result<ServiceIdentityTrustAnchor> {
let anchor = signer.trust_anchor()?;
prepare_parent(path)?;
let envelope = CultCacheEnvelope {
key: P::TRUST_ANCHOR_KEY.into(),
r#type: P::TRUST_ANCHOR_TYPE.into(),
payload: rmp_serde::to_vec(&anchor)?,
stored_at: anchor.identity_created_at.clone(),
schema_id: Some(P::TRUST_ANCHOR_SCHEMA.into()),
};
let mut backing = SingleFileMessagePackBackingStore::new(path);
match backing.pull_all()?.as_slice() {
[] => backing.push(&envelope)?,
[current] if current == &envelope => {}
_ => bail!("service identity trust anchor output already contains different state"),
}
Ok(anchor)
}
pub fn verify_service_identity_signature<P, S>(
anchor: &ServiceIdentityTrustAnchor,
payload: &[u8],
proof: &ServiceIdentitySignature,
) -> Result<()>
where
P: ServiceIdentityProfile,
S: ServiceSignaturePurpose<P>,
{
validate_anchor::<P>(anchor)?;
if proof.identity_id != anchor.identity_id {
bail!("service identity signature names a different identity");
}
let key: [u8; 32] = anchor
.public_key
.as_slice()
.try_into()
.map_err(|_| anyhow!("service identity public key has invalid length"))?;
let signature = Signature::from_slice(&proof.signature)
.map_err(|_| anyhow!("service identity signature has invalid length"))?;
VerifyingKey::from_bytes(&key)?
.verify(&signing_message::<P, S>(payload), &signature)
.map_err(|_| anyhow!("service identity signature verification failed"))
}
/// Verifies against a public key already admitted by an owning trust store.
/// The identity is still derived from the profile; callers cannot name it.
pub fn verify_service_identity_signature_with_public_key<P, S>(
public_key: &[u8],
payload: &[u8],
proof: &ServiceIdentitySignature,
) -> Result<()>
where
P: ServiceIdentityProfile,
S: ServiceSignaturePurpose<P>,
{
if proof.identity_id != derive_service_identity_id::<P>(public_key)? {
bail!("service identity signature names a different identity");
}
let key: [u8; 32] = public_key
.try_into()
.map_err(|_| anyhow!("service identity public key has invalid length"))?;
let signature = Signature::from_slice(&proof.signature)
.map_err(|_| anyhow!("service identity signature has invalid length"))?;
VerifyingKey::from_bytes(&key)?
.verify(&signing_message::<P, S>(payload), &signature)
.map_err(|_| anyhow!("service identity signature verification failed"))
}
fn validate_private<P: ServiceIdentityProfile>(entry: &ServiceIdentityPrivateEntry) -> Result<()> {
if entry.schema_version != P::PRIVATE_SCHEMA
|| entry.public_key.len() != 32
|| entry.enrollment_nonce.len() != 32
|| entry.protected_private_seed.is_empty()
|| entry.protector_version != "v1"
{
bail!("service identity private entry violates its profile schema");
}
chrono::DateTime::parse_from_rfc3339(&entry.created_at)
.map_err(|_| anyhow!("service identity created_at is not RFC3339"))?;
if identity_id::<P>(&entry.public_key) != entry.identity_id {
bail!("service identity id does not match public key");
}
Ok(())
}
fn validate_anchor<P: ServiceIdentityProfile>(anchor: &ServiceIdentityTrustAnchor) -> Result<()> {
if anchor.schema_version != P::TRUST_ANCHOR_SCHEMA
|| anchor.public_key.len() != 32
|| derive_service_identity_id::<P>(&anchor.public_key)? != anchor.identity_id
{
bail!("service identity trust anchor violates its profile schema");
}
Ok(())
}
/// Derives the profile-bound identity id from an exact Ed25519 public key.
/// Consumers use this instead of accepting a caller-supplied identity string.
pub fn derive_service_identity_id<P: ServiceIdentityProfile>(public_key: &[u8]) -> Result<String> {
if public_key.len() != 32 {
bail!("service identity public key has invalid length");
}
Ok(hex(&Sha256::digest([P::ID_DOMAIN, public_key].concat())))
}
fn identity_id<P: ServiceIdentityProfile>(key: &[u8]) -> String {
derive_service_identity_id::<P>(key).expect("internal service identity key is Ed25519")
}
fn signing_message<P: ServiceIdentityProfile, S: ServiceSignaturePurpose<P>>(
payload: &[u8],
) -> Vec<u8> {
let mut out =
Vec::with_capacity(P::SIGNATURE_DOMAIN.len() + S::PURPOSE.len() + payload.len() + 16);
out.extend_from_slice(P::SIGNATURE_DOMAIN);
out.extend_from_slice(&(S::PURPOSE.len() as u64).to_be_bytes());
out.extend_from_slice(S::PURPOSE);
out.extend_from_slice(&(payload.len() as u64).to_be_bytes());
out.extend_from_slice(payload);
out
}
fn private_envelope<P: ServiceIdentityProfile>(
entry: &ServiceIdentityPrivateEntry,
) -> Result<CultCacheEnvelope> {
Ok(CultCacheEnvelope {
key: P::PRIVATE_KEY.into(),
r#type: P::PRIVATE_TYPE.into(),
payload: rmp_serde::to_vec(entry)?,
stored_at: entry.created_at.clone(),
schema_id: Some(P::PRIVATE_SCHEMA.into()),
})
}
fn prepare_parent(path: &Path) -> Result<()> {
let parent = path
.parent()
.ok_or_else(|| anyhow!("service identity path has no parent"))?;
std::fs::create_dir_all(parent)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700))?;
}
Ok(())
}
fn harden_store_permissions(_path: &Path) -> Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(_path, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
#[cfg(windows)]
fn platform_protector_kind() -> &'static str {
"windows_dpapi_current_user"
}
#[cfg(target_os = "linux")]
fn platform_protector_kind() -> &'static str {
"linux_file_mode_machine_id_binding"
}
#[cfg(windows)]
fn platform_assurance() -> &'static str {
WINDOWS_SERVICE_IDENTITY_ASSURANCE
}
#[cfg(target_os = "linux")]
fn platform_assurance() -> &'static str {
LINUX_SERVICE_IDENTITY_ASSURANCE
}
#[cfg(windows)]
fn platform_binding<P: ServiceIdentityProfile>() -> Result<String> {
Ok(format!("dpapi-current-user:{}", P::PROTECTOR_CONTEXT))
}
#[cfg(target_os = "linux")]
fn platform_binding<P: ServiceIdentityProfile>() -> Result<String> {
let raw = std::fs::read_to_string("/etc/machine-id")
.or_else(|_| std::fs::read_to_string("/var/lib/dbus/machine-id"))
.context("Linux machine-id is unavailable")?;
let id = raw.trim();
if id.is_empty() {
bail!("Linux machine-id is empty");
}
Ok(format!(
"{}:machine-id-sha256:{}",
P::PROTECTOR_CONTEXT,
hex(&Sha256::digest(id.as_bytes()))
))
}
#[cfg(windows)]
fn protect_seed<P: ServiceIdentityProfile>(seed: &[u8; 32], binding: &str) -> Result<Vec<u8>> {
dpapi::<P>(seed, binding, true)
}
#[cfg(windows)]
fn unprotect_seed<P: ServiceIdentityProfile>(seed: &[u8], binding: &str) -> Result<Vec<u8>> {
dpapi::<P>(seed, binding, false)
}
#[cfg(windows)]
fn dpapi<P: ServiceIdentityProfile>(input: &[u8], binding: &str, protect: bool) -> Result<Vec<u8>> {
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::Cryptography::{
CRYPT_INTEGER_BLOB, CRYPTPROTECT_UI_FORBIDDEN, CryptProtectData, CryptUnprotectData,
};
let mut input = input.to_vec();
let mut entropy = Sha256::digest(
[
b"gamecult-service-identity-dpapi-v1\0".as_slice(),
P::PROTECTOR_CONTEXT.as_bytes(),
binding.as_bytes(),
]
.concat(),
)
.to_vec();
let ib = CRYPT_INTEGER_BLOB {
cbData: input.len() as u32,
pbData: input.as_mut_ptr(),
};
let eb = CRYPT_INTEGER_BLOB {
cbData: entropy.len() as u32,
pbData: entropy.as_mut_ptr(),
};
let mut output = CRYPT_INTEGER_BLOB {
cbData: 0,
pbData: std::ptr::null_mut(),
};
let ok = unsafe {
if protect {
CryptProtectData(
&ib,
std::ptr::null(),
&eb,
std::ptr::null(),
std::ptr::null(),
CRYPTPROTECT_UI_FORBIDDEN,
&mut output,
)
} else {
CryptUnprotectData(
&ib,
std::ptr::null_mut(),
&eb,
std::ptr::null(),
std::ptr::null(),
CRYPTPROTECT_UI_FORBIDDEN,
&mut output,
)
}
};
if ok == 0 {
return Err(std::io::Error::last_os_error())
.context("DPAPI service identity operation failed");
}
let bytes =
unsafe { std::slice::from_raw_parts(output.pbData, output.cbData as usize).to_vec() };
unsafe {
LocalFree(output.pbData.cast());
}
Ok(bytes)
}
#[cfg(target_os = "linux")]
fn protect_seed<P: ServiceIdentityProfile>(seed: &[u8; 32], binding: &str) -> Result<Vec<u8>> {
xor_linux::<P>(seed, binding)
}
#[cfg(target_os = "linux")]
fn unprotect_seed<P: ServiceIdentityProfile>(seed: &[u8], binding: &str) -> Result<Vec<u8>> {
if seed.len() != 32 {
bail!("protected Linux service seed has invalid length");
}
xor_linux::<P>(seed, binding)
}
#[cfg(target_os = "linux")]
fn xor_linux<P: ServiceIdentityProfile>(seed: &[u8], binding: &str) -> Result<Vec<u8>> {
let mask = Sha256::digest(
[
b"gamecult-linux-service-seed-v1\0".as_slice(),
P::PROTECTOR_CONTEXT.as_bytes(),
binding.as_bytes(),
]
.concat(),
);
Ok(seed.iter().zip(mask).map(|(a, b)| a ^ b).collect())
}
fn hex(bytes: &[u8]) -> String {
const D: &[u8; 16] = b"0123456789abcdef";
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
s.push(D[(b >> 4) as usize] as char);
s.push(D[(b & 15) as usize] as char);
}
s
}
#[cfg(test)]
mod tests {
use super::*;
enum OtherPurpose {}
impl ServiceSignaturePurpose<IdunnServiceIdentity> for OtherPurpose {
const PURPOSE: &'static [u8] = b"idunn.other.v1";
}
#[test]
fn immutable_enrollment_reopens_and_is_purpose_and_payload_bound() -> Result<()> {
let temp = tempfile::tempdir()?;
let path = temp.path().join("idunn.ccmp");
let signer = enroll_service_identity_at::<IdunnServiceIdentity>(&path)?;
let proof = signer.sign::<IdunnAuthenticatedProviderHealthProjectionPurpose>(b"healthy");
let anchor = signer.trust_anchor()?;
verify_service_identity_signature::<
IdunnServiceIdentity,
IdunnAuthenticatedProviderHealthProjectionPurpose,
>(&anchor, b"healthy", &proof)?;
assert!(
verify_service_identity_signature::<
IdunnServiceIdentity,
IdunnAuthenticatedProviderHealthProjectionPurpose,
>(&anchor, b"unhealthy", &proof)
.is_err()
);
assert!(
verify_service_identity_signature::<IdunnServiceIdentity, OtherPurpose>(
&anchor, b"healthy", &proof
)
.is_err()
);
assert!(enroll_service_identity_at::<IdunnServiceIdentity>(&path).is_err());
assert_eq!(
derive_service_identity_id::<IdunnServiceIdentity>(&anchor.public_key)?,
anchor.identity_id
);
assert!(derive_service_identity_id::<IdunnServiceIdentity>(&[0; 31]).is_err());
assert_eq!(
open_service_identity_at::<IdunnServiceIdentity>(&path)?.entry(),
signer.entry()
);
Ok(())
}
#[test]
fn malformed_or_profile_substituted_state_fails_closed_without_replacement() -> Result<()> {
enum Alien {}
impl ServiceIdentityProfile for Alien {
const PRIVATE_TYPE: &'static str = "alien.private.v1";
const PRIVATE_SCHEMA: &'static str = "alien.private.v1";
const PRIVATE_KEY: &'static str = "alien";
const TRUST_ANCHOR_TYPE: &'static str = "alien.anchor.v1";
const TRUST_ANCHOR_SCHEMA: &'static str = "alien.anchor.v1";
const TRUST_ANCHOR_KEY: &'static str = "alien-public";
const ID_DOMAIN: &'static [u8] = b"alien.id\0";
const SIGNATURE_DOMAIN: &'static [u8] = b"alien.sig\0";
const PROTECTOR_CONTEXT: &'static str = "alien-v1";
}
let temp = tempfile::tempdir()?;
let malformed = temp.path().join("bad.ccmp");
std::fs::write(&malformed, b"rot")?;
let before = std::fs::read(&malformed)?;
assert!(open_service_identity_at::<IdunnServiceIdentity>(&malformed).is_err());
assert!(enroll_service_identity_at::<IdunnServiceIdentity>(&malformed).is_err());
assert_eq!(before, std::fs::read(&malformed)?);
let good = temp.path().join("good.ccmp");
enroll_service_identity_at::<IdunnServiceIdentity>(&good)?;
assert!(open_service_identity_at::<Alien>(&good).is_err());
Ok(())
}
#[test]
fn exported_anchor_is_public_only_immutable_and_rejects_identity_substitution() -> Result<()> {
let temp = tempfile::tempdir()?;
let signer =
enroll_service_identity_at::<IdunnServiceIdentity>(&temp.path().join("private.ccmp"))?;
let output = temp.path().join("public.ccmp");
let anchor = export_service_identity_trust_anchor(&signer, &output)?;
let bytes = std::fs::read(&output)?;
assert!(
!bytes
.windows(signer.entry().protected_private_seed.len())
.any(|w| w == signer.entry().protected_private_seed)
);
export_service_identity_trust_anchor(&signer, &output)?;
assert_eq!(bytes, std::fs::read(&output)?);
let other =
enroll_service_identity_at::<IdunnServiceIdentity>(&temp.path().join("other.ccmp"))?;
let proof = other.sign::<IdunnAuthenticatedProviderHealthProjectionPurpose>(b"healthy");
assert!(
verify_service_identity_signature::<
IdunnServiceIdentity,
IdunnAuthenticatedProviderHealthProjectionPurpose,
>(&anchor, b"healthy", &proof)
.is_err()
);
Ok(())
}
}

View file

@ -1,339 +0,0 @@
use anyhow::{Result, anyhow};
use std::collections::{BTreeMap, BTreeSet};
use crate::{CultNetDocumentRegistry, CultNetMessage, CultNetRawDocumentRecord};
/// Read-only backing surface for a CultNet snapshot server.
///
/// Records returned here are already the stored wire records. The snapshot
/// server selects and clones them; it never decodes payloads, rewrites source
/// metadata, or applies them to another cache.
pub trait CultNetRawSnapshotSource {
fn raw_snapshot(&self) -> Result<Vec<CultNetRawDocumentRecord>>;
}
impl CultNetRawSnapshotSource for Vec<CultNetRawDocumentRecord> {
fn raw_snapshot(&self) -> Result<Vec<CultNetRawDocumentRecord>> {
Ok(self.clone())
}
}
impl<F> CultNetRawSnapshotSource for F
where
F: Fn() -> Result<Vec<CultNetRawDocumentRecord>>,
{
fn raw_snapshot(&self) -> Result<Vec<CultNetRawDocumentRecord>> {
self()
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CultNetReadOnlySnapshotPolicy {
allowed_records: BTreeSet<(String, String)>,
}
impl CultNetReadOnlySnapshotPolicy {
pub fn new() -> Self {
Self::default()
}
pub fn allow(
&mut self,
schema_id: impl Into<String>,
record_key: impl Into<String>,
) -> Result<&mut Self> {
let schema_id = schema_id.into();
let record_key = record_key.into();
require_non_empty(&schema_id, "schema_id")?;
require_non_empty(&record_key, "record_key")?;
self.allowed_records.insert((schema_id, record_key));
Ok(self)
}
fn allows(&self, schema_id: &str, record_key: &str) -> bool {
self.allowed_records
.contains(&(schema_id.to_string(), record_key.to_string()))
}
}
/// Serve one raw snapshot request from an explicitly bounded, read-only view.
///
/// The document registry proves that every exposed schema belongs to the
/// runtime. The policy grants individual `(schema_id, record_key)` pairs. The
/// source owns the bytes and metadata; this function only selects records.
pub fn serve_read_only_raw_snapshot<S: CultNetRawSnapshotSource>(
document_registry: &CultNetDocumentRegistry,
policy: &CultNetReadOnlySnapshotPolicy,
source: &S,
request: &CultNetMessage,
) -> Result<CultNetMessage> {
let CultNetMessage::SnapshotRequest {
message_id,
schema_ids,
record_keys,
} = request
else {
return Err(anyhow!("expected cultnet.snapshot_request.v0"));
};
require_non_empty(message_id, "message_id")?;
reject_duplicates(schema_ids.as_deref(), "requested schema id")?;
reject_duplicates(record_keys.as_deref(), "requested record key")?;
let requested_schemas = schema_ids
.as_ref()
.map(|values| values.iter().map(String::as_str).collect::<BTreeSet<_>>());
let requested_keys = record_keys
.as_ref()
.map(|values| values.iter().map(String::as_str).collect::<BTreeSet<_>>());
let mut selected = Vec::new();
let mut seen = BTreeSet::new();
for document in source.raw_snapshot()? {
let identity = (document.schema_id.clone(), document.record_key.clone());
if !seen.insert(identity.clone()) {
return Err(anyhow!(
"snapshot source contains duplicate record {:?}/{:?}",
identity.0,
identity.1
));
}
if document_registry
.binding_by_schema_id(&document.schema_id)
.is_none()
{
return Err(anyhow!(
"snapshot source record {:?}/{:?} uses an unregistered schema",
document.schema_id,
document.record_key
));
}
if !policy.allows(&document.schema_id, &document.record_key) {
continue;
}
if requested_schemas
.as_ref()
.is_some_and(|schemas| !schemas.contains(document.schema_id.as_str()))
{
continue;
}
if requested_keys
.as_ref()
.is_some_and(|keys| !keys.contains(document.record_key.as_str()))
{
continue;
}
selected.push(document);
}
Ok(CultNetMessage::SnapshotResponseRaw {
message_id: message_id.clone(),
documents: selected,
})
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CultNetSnapshotSourceExpectation {
pub runtime_id: Option<String>,
pub agent_id: Option<String>,
pub role: Option<String>,
pub tags: Option<Vec<String>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetSnapshotRecordExpectation {
pub schema_id: String,
pub record_key: String,
pub source: CultNetSnapshotSourceExpectation,
}
impl CultNetSnapshotRecordExpectation {
pub fn new(schema_id: impl Into<String>, record_key: impl Into<String>) -> Self {
Self {
schema_id: schema_id.into(),
record_key: record_key.into(),
source: CultNetSnapshotSourceExpectation::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetRawSnapshotQuery {
message_id: String,
expectations: BTreeMap<(String, String), CultNetSnapshotSourceExpectation>,
}
impl CultNetRawSnapshotQuery {
pub fn new(
message_id: impl Into<String>,
records: Vec<CultNetSnapshotRecordExpectation>,
) -> Result<Self> {
let message_id = message_id.into();
require_non_empty(&message_id, "message_id")?;
if records.is_empty() {
return Err(anyhow!("snapshot query must request at least one record"));
}
let mut expectations = BTreeMap::new();
for record in records {
require_non_empty(&record.schema_id, "schema_id")?;
require_non_empty(&record.record_key, "record_key")?;
let identity = (record.schema_id, record.record_key);
if expectations
.insert(identity.clone(), record.source)
.is_some()
{
return Err(anyhow!(
"snapshot query contains duplicate requested record {:?}/{:?}",
identity.0,
identity.1
));
}
}
Ok(Self {
message_id,
expectations,
})
}
pub fn request(&self) -> CultNetMessage {
CultNetMessage::SnapshotRequest {
message_id: self.message_id.clone(),
schema_ids: Some(
self.expectations
.keys()
.map(|(schema_id, _)| schema_id.clone())
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
),
record_keys: Some(
self.expectations
.keys()
.map(|(_, record_key)| record_key.clone())
.collect::<BTreeSet<_>>()
.into_iter()
.collect(),
),
}
}
/// Validate a response and return records without mutating any local cache.
pub fn accept_response(
&self,
response: CultNetMessage,
) -> Result<Vec<CultNetRawDocumentRecord>> {
let CultNetMessage::SnapshotResponseRaw {
message_id,
documents,
} = response
else {
return Err(anyhow!("expected cultnet.snapshot_response_raw.v0"));
};
if message_id != self.message_id {
return Err(anyhow!(
"snapshot response message id {:?} does not match request {:?}",
message_id,
self.message_id
));
}
let mut seen = BTreeSet::new();
for document in &documents {
let identity = (document.schema_id.clone(), document.record_key.clone());
if !seen.insert(identity.clone()) {
return Err(anyhow!(
"snapshot response contains duplicate record {:?}/{:?}",
identity.0,
identity.1
));
}
let expected = self.expectations.get(&identity).ok_or_else(|| {
anyhow!(
"snapshot response contains unexpected record {:?}/{:?}",
identity.0,
identity.1
)
})?;
require_expected_metadata(
"source_runtime_id",
expected.runtime_id.as_deref(),
document.source_runtime_id.as_deref(),
&identity,
)?;
require_expected_metadata(
"source_agent_id",
expected.agent_id.as_deref(),
document.source_agent_id.as_deref(),
&identity,
)?;
require_expected_metadata(
"source_role",
expected.role.as_deref(),
document.source_role.as_deref(),
&identity,
)?;
if let Some(expected_tags) = expected.tags.as_ref()
&& document.tags.as_ref() != Some(expected_tags)
{
return Err(anyhow!(
"snapshot response record {:?}/{:?} has unexpected tags: expected {:?}, got {:?}",
identity.0,
identity.1,
expected_tags,
document.tags
));
}
}
Ok(documents)
}
}
pub fn query_read_only_raw_snapshot<F>(
query: &CultNetRawSnapshotQuery,
exchange: F,
) -> Result<Vec<CultNetRawDocumentRecord>>
where
F: FnOnce(CultNetMessage) -> Result<CultNetMessage>,
{
query.accept_response(exchange(query.request())?)
}
fn require_expected_metadata(
field: &str,
expected: Option<&str>,
actual: Option<&str>,
identity: &(String, String),
) -> Result<()> {
if let Some(expected) = expected
&& actual != Some(expected)
{
return Err(anyhow!(
"snapshot response record {:?}/{:?} has unexpected {field}: expected {:?}, got {:?}",
identity.0,
identity.1,
expected,
actual
));
}
Ok(())
}
fn reject_duplicates(values: Option<&[String]>, label: &str) -> Result<()> {
let Some(values) = values else {
return Ok(());
};
let mut seen = BTreeSet::new();
for value in values {
require_non_empty(value, label)?;
if !seen.insert(value) {
return Err(anyhow!("duplicate {label} {value:?}"));
}
}
Ok(())
}
fn require_non_empty(value: &str, field: &str) -> Result<()> {
if value.trim().is_empty() {
return Err(anyhow!("{field} must be non-empty"));
}
Ok(())
}

View file

@ -1,194 +0,0 @@
use anyhow::Result;
use anyhow::anyhow;
use serde::Deserialize;
use serde::Serialize;
use std::io::Read;
use std::io::Write;
use crate::CultNetTransportChannel;
use crate::CultNetTransportDelivery;
use crate::CultNetTransportDescriptor;
use crate::CultNetTransportOrdering;
use crate::CultNetTransportProfile;
use crate::CultNetTransportProtocol;
use crate::FRAME_HEADER_BYTES;
use crate::encode_frame;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CultNetTransportStats {
pub bytes_received: u64,
pub bytes_sent: u64,
pub frames_received: u64,
pub frames_sent: u64,
pub reliable_packets_expired: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CultNetTransportFrame {
pub channel_id: String,
pub payload: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CultNetReconnectPolicy {
pub schema_version: String,
pub policy_id: String,
pub base_delay_ms: u64,
pub max_delay_ms: u64,
pub max_jitter_ms: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_attempts: Option<u32>,
}
#[derive(Clone, Debug)]
pub struct CultNetReconnectPolicyOptions {
pub policy_id: String,
pub base_delay_ms: u64,
pub max_delay_ms: u64,
pub max_jitter_ms: u64,
pub max_attempts: Option<u32>,
}
impl Default for CultNetReconnectPolicyOptions {
fn default() -> Self {
Self {
policy_id: "default".to_string(),
base_delay_ms: 1_000,
max_delay_ms: 30_000,
max_jitter_ms: 250,
max_attempts: None,
}
}
}
pub fn create_reconnect_policy(options: CultNetReconnectPolicyOptions) -> CultNetReconnectPolicy {
CultNetReconnectPolicy {
schema_version: "cultnet.reconnect_policy.v0".to_string(),
policy_id: if options.policy_id.trim().is_empty() {
"default".to_string()
} else {
options.policy_id
},
base_delay_ms: options.base_delay_ms,
max_delay_ms: options.max_delay_ms,
max_jitter_ms: options.max_jitter_ms,
max_attempts: options.max_attempts,
}
}
pub fn compute_reconnect_delay_ms(
policy: &CultNetReconnectPolicy,
attempt: u32,
jitter_ms: u64,
) -> u64 {
let normalized_attempt = attempt.max(1);
let multiplier = 2_u64.saturating_pow(normalized_attempt.saturating_sub(1));
let capped_base_delay = policy
.base_delay_ms
.saturating_mul(multiplier)
.min(policy.max_delay_ms);
capped_base_delay + jitter_ms.min(policy.max_jitter_ms)
}
#[derive(Clone, Debug, Default)]
pub struct TcpFramedTransportProfileOptions {
pub transport_id: Option<String>,
pub host: Option<String>,
pub port: Option<u16>,
pub max_payload_bytes: Option<u32>,
pub max_fragment_bytes: Option<u32>,
}
pub fn create_tcp_framed_transport_profile(
runtime_id: impl Into<String>,
options: TcpFramedTransportProfileOptions,
) -> CultNetTransportProfile {
CultNetTransportProfile {
schema_version: "cultnet.transport_profile.v0".to_string(),
runtime_id: runtime_id.into(),
transports: vec![CultNetTransportDescriptor {
transport_id: options
.transport_id
.unwrap_or_else(|| "tcp-framed".to_string()),
protocol: CultNetTransportProtocol::TcpFramed,
host: options.host,
port: options.port,
path: None,
discovery_group: None,
wire_contracts: Some(vec!["cultnet.schema.v0".to_string()]),
channels: vec![CultNetTransportChannel {
channel_id: "schema".to_string(),
delivery: CultNetTransportDelivery::Reliable,
ordering: CultNetTransportOrdering::Ordered,
max_payload_bytes: options.max_payload_bytes,
max_fragment_bytes: options.max_fragment_bytes,
max_pending_reliable_packets: None,
reliable_expire_after_ms: None,
}],
}],
}
}
pub struct TcpFramedTransportConnection<TStream> {
stream: TStream,
pub profile: CultNetTransportProfile,
stats: CultNetTransportStats,
}
impl<TStream> TcpFramedTransportConnection<TStream> {
pub fn new(stream: TStream, profile: CultNetTransportProfile) -> Self {
Self {
stream,
profile,
stats: CultNetTransportStats::default(),
}
}
pub fn stats(&self) -> CultNetTransportStats {
self.stats.clone()
}
pub fn into_inner(self) -> TStream {
self.stream
}
}
impl<TStream> TcpFramedTransportConnection<TStream>
where
TStream: Write,
{
pub fn send(&mut self, channel_id: &str, payload: &[u8]) -> Result<()> {
if channel_id != "schema" {
return Err(anyhow!(
"tcp_framed transport only supports the schema channel, got {channel_id:?}"
));
}
let frame = encode_frame(payload)?;
self.stream.write_all(&frame)?;
self.stream.flush()?;
self.stats.bytes_sent += frame.len() as u64;
self.stats.frames_sent += 1;
Ok(())
}
}
impl<TStream> TcpFramedTransportConnection<TStream>
where
TStream: Read,
{
pub fn receive(&mut self) -> Result<CultNetTransportFrame> {
let mut header = [0_u8; FRAME_HEADER_BYTES];
self.stream.read_exact(&mut header)?;
let payload_len = u32::from_be_bytes(header) as usize;
let mut payload = vec![0_u8; payload_len];
self.stream.read_exact(&mut payload)?;
self.stats.bytes_received += (FRAME_HEADER_BYTES + payload_len) as u64;
self.stats.frames_received += 1;
Ok(CultNetTransportFrame {
channel_id: "schema".to_string(),
payload,
})
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,222 +0,0 @@
use anyhow::Result;
use cultnet_rs::{
CultNetDocumentBinding, CultNetDocumentRegistry, CultNetMessage, CultNetRawDocumentRecord,
CultNetRawPayloadEncoding, CultNetRawSnapshotQuery, CultNetReadOnlySnapshotPolicy,
CultNetSnapshotRecordExpectation, CultNetSnapshotSourceExpectation, CultNetWireContract,
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec, query_read_only_raw_snapshot,
serve_read_only_raw_snapshot,
};
const HEALTH_SCHEMA: &str = "idunn.managed_health_projection.v1";
fn registry() -> CultNetDocumentRegistry {
let mut registry = CultNetDocumentRegistry::new();
registry.register(CultNetDocumentBinding {
schema_id: HEALTH_SCHEMA.to_string(),
document_type: "idunn.managed-health-projection".to_string(),
mutation_contract: None,
payload_schema_version: Some(HEALTH_SCHEMA.to_string()),
});
registry
}
fn record(key: &str, payload: Vec<u8>) -> CultNetRawDocumentRecord {
CultNetRawDocumentRecord {
schema_id: HEALTH_SCHEMA.to_string(),
record_key: key.to_string(),
stored_at: "2026-07-19T20:00:00Z".to_string(),
payload_encoding: CultNetRawPayloadEncoding::Messagepack,
payload,
source_runtime_id: Some("idunn@yggdrasil".to_string()),
source_agent_id: Some("idunn".to_string()),
source_role: Some("deployment-owner".to_string()),
tags: Some(vec!["public-health".to_string()]),
}
}
fn expectation(key: &str) -> CultNetSnapshotRecordExpectation {
CultNetSnapshotRecordExpectation {
schema_id: HEALTH_SCHEMA.to_string(),
record_key: key.to_string(),
source: CultNetSnapshotSourceExpectation {
runtime_id: Some("idunn@yggdrasil".to_string()),
agent_id: Some("idunn".to_string()),
role: Some("deployment-owner".to_string()),
tags: Some(vec!["public-health".to_string()]),
},
}
}
#[test]
fn canonical_wire_loop_returns_exact_stored_raw_record_without_cache_apply() -> Result<()> {
let stored = record("epiphany-agent", vec![0x95, 0xc4, 0x02, 0xde, 0xad]);
let source = vec![stored.clone(), record("not-public", vec![0x01])];
let mut policy = CultNetReadOnlySnapshotPolicy::new();
policy.allow(HEALTH_SCHEMA, "epiphany-agent")?;
let query = CultNetRawSnapshotQuery::new("status-42", vec![expectation("epiphany-agent")])?;
let received = query_read_only_raw_snapshot(&query, |request| {
// This is the canonical transport loop: request and response both cross
// the CultNet wire codec. Neither side receives a cache to mutate.
let request_wire =
encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)?;
let decoded_request =
decode_cultnet_message_from_slice(&request_wire, CultNetWireContract::CultNetSchemaV0)?;
let response =
serve_read_only_raw_snapshot(&registry(), &policy, &source, &decoded_request)?;
let response_wire =
encode_cultnet_message_to_vec(&response, CultNetWireContract::CultNetSchemaV0)?;
decode_cultnet_message_from_slice(&response_wire, CultNetWireContract::CultNetSchemaV0)
})?;
assert_eq!(received, vec![stored]);
Ok(())
}
#[test]
fn server_filters_by_exact_policy_pair_and_request() -> Result<()> {
let source = vec![record("epiphany-agent", vec![1]), record("odin", vec![2])];
let mut policy = CultNetReadOnlySnapshotPolicy::new();
policy.allow(HEALTH_SCHEMA, "epiphany-agent")?;
let request = CultNetMessage::SnapshotRequest {
message_id: "bounded".to_string(),
schema_ids: Some(vec![HEALTH_SCHEMA.to_string()]),
record_keys: Some(vec!["epiphany-agent".to_string(), "odin".to_string()]),
};
let response = serve_read_only_raw_snapshot(&registry(), &policy, &source, &request)?;
let CultNetMessage::SnapshotResponseRaw { documents, .. } = response else {
panic!("expected raw response");
};
assert_eq!(documents, vec![source[0].clone()]);
Ok(())
}
#[test]
fn server_rejects_duplicate_request_terms_and_ambiguous_backing_records() -> Result<()> {
let mut policy = CultNetReadOnlySnapshotPolicy::new();
policy.allow(HEALTH_SCHEMA, "epiphany-agent")?;
let duplicate_request = CultNetMessage::SnapshotRequest {
message_id: "duplicate-request".to_string(),
schema_ids: Some(vec![HEALTH_SCHEMA.to_string(), HEALTH_SCHEMA.to_string()]),
record_keys: Some(vec!["epiphany-agent".to_string()]),
};
let error = serve_read_only_raw_snapshot(
&registry(),
&policy,
&vec![record("epiphany-agent", vec![1])],
&duplicate_request,
)
.unwrap_err();
assert!(error.to_string().contains("duplicate requested schema id"));
let request = CultNetMessage::SnapshotRequest {
message_id: "duplicate-source".to_string(),
schema_ids: None,
record_keys: None,
};
let duplicate = record("epiphany-agent", vec![1]);
let error = serve_read_only_raw_snapshot(
&registry(),
&policy,
&vec![duplicate.clone(), duplicate],
&request,
)
.unwrap_err();
assert!(error.to_string().contains("duplicate record"));
Ok(())
}
#[test]
fn query_rejects_duplicate_expectations_wrong_message_and_unrelated_message() -> Result<()> {
let error = CultNetRawSnapshotQuery::new(
"duplicate",
vec![expectation("epiphany-agent"), expectation("epiphany-agent")],
)
.unwrap_err();
assert!(error.to_string().contains("duplicate requested record"));
let query = CultNetRawSnapshotQuery::new("wanted", vec![expectation("epiphany-agent")])?;
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "somebody-elses-response".to_string(),
documents: vec![],
})
.unwrap_err();
assert!(error.to_string().contains("does not match request"));
let error = query
.accept_response(CultNetMessage::Error {
error: "unrelated".to_string(),
})
.unwrap_err();
assert!(
error
.to_string()
.contains("expected cultnet.snapshot_response_raw.v0")
);
Ok(())
}
#[test]
fn query_rejects_unexpected_identity_duplicates_and_source_metadata() -> Result<()> {
let query = CultNetRawSnapshotQuery::new("hostile", vec![expectation("epiphany-agent")])?;
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "hostile".to_string(),
documents: vec![record("odin", vec![1])],
})
.unwrap_err();
assert!(error.to_string().contains("unexpected record"));
let document = record("epiphany-agent", vec![1]);
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "hostile".to_string(),
documents: vec![document.clone(), document],
})
.unwrap_err();
assert!(error.to_string().contains("duplicate record"));
let mut forged = record("epiphany-agent", vec![1]);
forged.source_runtime_id = Some("mallory".to_string());
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "hostile".to_string(),
documents: vec![forged],
})
.unwrap_err();
assert!(error.to_string().contains("unexpected source_runtime_id"));
let mut forged = record("epiphany-agent", vec![1]);
forged.tags = Some(vec!["private".to_string()]);
let error = query
.accept_response(CultNetMessage::SnapshotResponseRaw {
message_id: "hostile".to_string(),
documents: vec![forged],
})
.unwrap_err();
assert!(error.to_string().contains("unexpected tags"));
Ok(())
}
#[test]
fn server_rejects_unregistered_source_schema_even_when_not_exposed() -> Result<()> {
let mut foreign = record("foreign", vec![1]);
foreign.schema_id = "xenos.unregistered.v0".to_string();
let request = CultNetMessage::SnapshotRequest {
message_id: "unregistered".to_string(),
schema_ids: None,
record_keys: None,
};
let error = serve_read_only_raw_snapshot(
&registry(),
&CultNetReadOnlySnapshotPolicy::new(),
&vec![foreign],
&request,
)
.unwrap_err();
assert!(error.to_string().contains("unregistered schema"));
Ok(())
}