Dungeon host returns without Eve: catalog, timelines, Begin, Deru API, accounts by invite
Restores play.rs, heimdall.rs, app_session.rs, idunn_health.rs, build.rs from parked/ghostlight-eve-surface; new catalog, timelines, begin, api, runtime, session_refresh, state_layout modules. Eve card tests read the turn-view JSON. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c43eb54962
commit
6575635237
17 changed files with 20785 additions and 6 deletions
680
Cargo.lock
generated
680
Cargo.lock
generated
|
|
@ -37,6 +37,15 @@ dependencies = [
|
|||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.6"
|
||||
|
|
@ -52,6 +61,28 @@ version = "1.0.104"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "async-stream"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
|
||||
dependencies = [
|
||||
"async-stream-impl",
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-stream-impl"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.92"
|
||||
|
|
@ -75,6 +106,70 @@ version = "1.5.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "axum"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
||||
dependencies = [
|
||||
"axum-core",
|
||||
"axum-macros",
|
||||
"bytes",
|
||||
"form_urlencoded",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-util",
|
||||
"itoa",
|
||||
"matchit",
|
||||
"memchr",
|
||||
"mime",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"serde_core",
|
||||
"serde_json",
|
||||
"serde_path_to_error",
|
||||
"serde_urlencoded",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-core"
|
||||
version = "0.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"mime",
|
||||
"pin-project-lite",
|
||||
"sync_wrapper",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-macros"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
|
|
@ -87,6 +182,12 @@ version = "0.23.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.1"
|
||||
|
|
@ -187,6 +288,12 @@ dependencies = [
|
|||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
|
|
@ -259,6 +366,85 @@ dependencies = [
|
|||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultmesh-rs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cultcache-rs",
|
||||
"cultnet-rs",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cultnet-rs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/GameCult/CultLib.git?rev=85f7024a35ea42cf9f0a0199a064526427150191#85f7024a35ea42cf9f0a0199a064526427150191"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"cultcache-rs",
|
||||
"ed25519-dalek",
|
||||
"hmac",
|
||||
"rand 0.9.5",
|
||||
"rmp-serde",
|
||||
"rmpv",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"socket2 0.5.10",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "4.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"curve25519-dalek-derive",
|
||||
"digest",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek-derive"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.7.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
|
|
@ -267,6 +453,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
|||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -280,6 +467,30 @@ dependencies = [
|
|||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "2.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
|
||||
dependencies = [
|
||||
"pkcs8",
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"serde",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
|
|
@ -296,6 +507,12 @@ version = "2.5.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.11"
|
||||
|
|
@ -404,6 +621,18 @@ dependencies = [
|
|||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
|
|
@ -413,7 +642,7 @@ dependencies = [
|
|||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"r-efi 6.0.0",
|
||||
"rand_core 0.10.1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
|
@ -454,6 +683,44 @@ dependencies = [
|
|||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ghostlight-dungeon"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"codex-connector",
|
||||
"cultcache-rs",
|
||||
"cultmesh-rs",
|
||||
"cultnet-rs",
|
||||
"ghostlight",
|
||||
"ghostlight-persona-projection",
|
||||
"hmac",
|
||||
"jsonwebtoken",
|
||||
"libc",
|
||||
"rand 0.9.5",
|
||||
"reqwest",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"uuid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ghostlight-persona-projection"
|
||||
version = "0.1.0"
|
||||
|
|
@ -475,6 +742,15 @@ dependencies = [
|
|||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.5.0"
|
||||
|
|
@ -508,12 +784,24 @@ dependencies = [
|
|||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http-range-header"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c"
|
||||
|
||||
[[package]]
|
||||
name = "httparse"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "httpdate"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.11.0"
|
||||
|
|
@ -527,6 +815,7 @@ dependencies = [
|
|||
"http",
|
||||
"http-body",
|
||||
"httparse",
|
||||
"httpdate",
|
||||
"itoa",
|
||||
"pin-project-lite",
|
||||
"smallvec",
|
||||
|
|
@ -567,7 +856,7 @@ dependencies = [
|
|||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2",
|
||||
"socket2 0.6.5",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
|
|
@ -733,6 +1022,27 @@ dependencies = [
|
|||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonwebtoken"
|
||||
version = "9.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"js-sys",
|
||||
"pem",
|
||||
"ring",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"simple_asn1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.189"
|
||||
|
|
@ -772,12 +1082,43 @@ version = "0.1.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||
dependencies = [
|
||||
"regex-automata",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matchit"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "mime"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "mime_guess"
|
||||
version = "2.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
|
||||
dependencies = [
|
||||
"mime",
|
||||
"unicase",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.2"
|
||||
|
|
@ -789,6 +1130,40 @@ dependencies = [
|
|||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
|
|
@ -833,6 +1208,16 @@ dependencies = [
|
|||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "percent-encoding"
|
||||
version = "2.3.2"
|
||||
|
|
@ -845,6 +1230,16 @@ version = "0.2.17"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "polyval"
|
||||
version = "0.6.2"
|
||||
|
|
@ -866,6 +1261,21 @@ dependencies = [
|
|||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
|
|
@ -888,7 +1298,7 @@ dependencies = [
|
|||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2",
|
||||
"socket2 0.6.5",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
|
|
@ -904,7 +1314,7 @@ dependencies = [
|
|||
"bytes",
|
||||
"getrandom 0.4.3",
|
||||
"lru-slab",
|
||||
"rand",
|
||||
"rand 0.10.2",
|
||||
"rand_pcg",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
|
|
@ -926,7 +1336,7 @@ dependencies = [
|
|||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2",
|
||||
"socket2 0.6.5",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
|
@ -940,12 +1350,28 @@ dependencies = [
|
|||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.2"
|
||||
|
|
@ -957,6 +1383,16 @@ dependencies = [
|
|||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
|
|
@ -966,6 +1402,15 @@ dependencies = [
|
|||
"getrandom 0.2.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.10.1"
|
||||
|
|
@ -999,6 +1444,23 @@ dependencies = [
|
|||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.12.28"
|
||||
|
|
@ -1080,6 +1542,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417"
|
||||
dependencies = [
|
||||
"rmp",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1088,6 +1552,15 @@ version = "2.1.3"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||
|
||||
[[package]]
|
||||
name = "rustc_version"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
|
||||
dependencies = [
|
||||
"semver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "1.1.4"
|
||||
|
|
@ -1154,6 +1627,12 @@ version = "1.2.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
|
|
@ -1207,6 +1686,17 @@ dependencies = [
|
|||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_path_to_error"
|
||||
version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
|
|
@ -1230,6 +1720,15 @@ dependencies = [
|
|||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sharded-slab"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
|
|
@ -1246,6 +1745,27 @@ dependencies = [
|
|||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
|
||||
dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simple_asn1"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d"
|
||||
dependencies = [
|
||||
"num-bigint",
|
||||
"num-traits",
|
||||
"thiserror",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
|
|
@ -1258,6 +1778,16 @@ version = "1.15.2"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.5.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.5"
|
||||
|
|
@ -1268,6 +1798,16 @@ dependencies = [
|
|||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
|
|
@ -1355,6 +1895,45 @@ dependencies = [
|
|||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread_local"
|
||||
version = "1.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"num-conv",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
|
||||
dependencies = [
|
||||
"num-conv",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.4"
|
||||
|
|
@ -1392,7 +1971,7 @@ dependencies = [
|
|||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"socket2 0.6.5",
|
||||
"tokio-macros",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
|
@ -1444,6 +2023,7 @@ dependencies = [
|
|||
"tokio",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1454,13 +2034,23 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
|||
dependencies = [
|
||||
"bitflags",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"http-range-header",
|
||||
"httpdate",
|
||||
"mime",
|
||||
"mime_guess",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
"url",
|
||||
]
|
||||
|
||||
|
|
@ -1482,6 +2072,7 @@ version = "0.1.44"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"log",
|
||||
"pin-project-lite",
|
||||
"tracing-attributes",
|
||||
"tracing-core",
|
||||
|
|
@ -1505,6 +2096,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"valuable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-log"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-subscriber"
|
||||
version = "0.3.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
|
||||
dependencies = [
|
||||
"matchers",
|
||||
"nu-ansi-term",
|
||||
"once_cell",
|
||||
"regex-automata",
|
||||
"sharded-slab",
|
||||
"smallvec",
|
||||
"thread_local",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
"tracing-log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1519,6 +2140,12 @@ version = "1.20.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||
|
||||
[[package]]
|
||||
name = "unicase"
|
||||
version = "2.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
|
|
@ -1592,6 +2219,12 @@ dependencies = [
|
|||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "valuable"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
|
|
@ -1613,6 +2246,15 @@ version = "0.11.1+wasi-snapshot-preview1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.4+wasi-0.2.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.127"
|
||||
|
|
@ -1882,6 +2524,12 @@ version = "0.52.6"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
|
|
@ -1911,6 +2559,26 @@ dependencies = [
|
|||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.56"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.56"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.8"
|
||||
|
|
|
|||
11
Cargo.toml
11
Cargo.toml
|
|
@ -1,6 +1,7 @@
|
|||
[workspace]
|
||||
members = [
|
||||
"crates/ghostlight",
|
||||
"crates/ghostlight-dungeon",
|
||||
"crates/ghostlight-persona-projection",
|
||||
"crates/ghostlight-verse",
|
||||
]
|
||||
|
|
@ -13,10 +14,19 @@ version = "0.1.0"
|
|||
|
||||
[workspace.dependencies]
|
||||
anyhow = "1"
|
||||
aes-gcm = "0.10"
|
||||
async-trait = "0.1"
|
||||
async-stream = "0.3"
|
||||
axum = { version = "0.8", features = ["macros"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
base64 = "0.22"
|
||||
codex-connector = { git = "https://github.com/GameCult/CodexConnector.git", rev = "68fe94b9475823de92ed766a97ea962d48723708" }
|
||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultcache-rs" }
|
||||
cultnet-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultnet-rs" }
|
||||
cultmesh-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "85f7024a35ea42cf9f0a0199a064526427150191", package = "cultmesh-rs" }
|
||||
jsonwebtoken = "9"
|
||||
hmac = "0.12"
|
||||
rand = "0.9"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "stream"] }
|
||||
rmp-serde = "1.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
|
@ -25,6 +35,7 @@ sha2 = "0.10"
|
|||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
unicode-segmentation = "1"
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
zeroize = "1.8"
|
||||
|
|
|
|||
46
crates/ghostlight-dungeon/Cargo.toml
Normal file
46
crates/ghostlight-dungeon/Cargo.toml
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
[package]
|
||||
name = "ghostlight-dungeon"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
autobins = false
|
||||
|
||||
[[bin]]
|
||||
name = "ghostlight-dungeon"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
aes-gcm.workspace = true
|
||||
async-trait.workspace = true
|
||||
async-stream.workspace = true
|
||||
axum.workspace = true
|
||||
chrono.workspace = true
|
||||
base64.workspace = true
|
||||
codex-connector.workspace = true
|
||||
cultcache-rs.workspace = true
|
||||
cultnet-rs.workspace = true
|
||||
cultmesh-rs.workspace = true
|
||||
jsonwebtoken.workspace = true
|
||||
libc = "0.2"
|
||||
hmac.workspace = true
|
||||
ghostlight = { path = "../ghostlight" }
|
||||
ghostlight-persona-projection = { path = "../ghostlight-persona-projection" }
|
||||
rand.workspace = true
|
||||
reqwest.workspace = true
|
||||
rmp-serde.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
uuid.workspace = true
|
||||
zeroize.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ghostlight = { path = "../ghostlight", features = ["test-support"] }
|
||||
tempfile = "3"
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
65
crates/ghostlight-dungeon/build.rs
Normal file
65
crates/ghostlight-dungeon/build.rs
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
use std::{env, path::Path, process::Command};
|
||||
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-env-changed=GHOSTLIGHT_BUILD_COMMIT");
|
||||
let manifest_dir =
|
||||
env::var("CARGO_MANIFEST_DIR").expect("Cargo must supply CARGO_MANIFEST_DIR");
|
||||
let repo_root = Path::new(&manifest_dir).join("../..");
|
||||
emit_git_rerun_paths(&repo_root);
|
||||
// Release tooling injects the clean-tree commit. Git discovery is only a
|
||||
// convenience for local builds. The exact ref and reflog dependencies above
|
||||
// keep that convenience from silently publishing stale provenance.
|
||||
let commit = env::var("GHOSTLIGHT_BUILD_COMMIT")
|
||||
.ok()
|
||||
.filter(|value| is_commit(value))
|
||||
.or_else(|| git_commit(&repo_root))
|
||||
.expect("GhostlightDungeon builds require an exact 40-hex source commit");
|
||||
println!("cargo:rustc-env=GHOSTLIGHT_BUILD_COMMIT={commit}");
|
||||
}
|
||||
|
||||
fn emit_git_rerun_paths(repo_root: &Path) {
|
||||
for git_path in ["HEAD", "logs/HEAD", "packed-refs"] {
|
||||
if let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", git_path]) {
|
||||
emit_rerun_path(repo_root, &path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(reference) = git_output(repo_root, &["symbolic-ref", "-q", "HEAD"])
|
||||
&& let Some(path) = git_output(repo_root, &["rev-parse", "--git-path", &reference])
|
||||
{
|
||||
emit_rerun_path(repo_root, &path);
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_rerun_path(repo_root: &Path, git_path: &str) {
|
||||
let path = Path::new(git_path);
|
||||
let resolved = if path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
repo_root.join(path)
|
||||
};
|
||||
println!("cargo:rerun-if-changed={}", resolved.display());
|
||||
}
|
||||
|
||||
fn git_commit(repo_root: &Path) -> Option<String> {
|
||||
git_output(repo_root, &["rev-parse", "HEAD"]).filter(|value| is_commit(value))
|
||||
}
|
||||
|
||||
fn git_output(repo_root: &Path, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(repo_root)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(output.stdout)
|
||||
.ok()
|
||||
.map(|value| value.trim().to_owned())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn is_commit(value: &str) -> bool {
|
||||
value.len() == 40 && value.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
}
|
||||
1040
crates/ghostlight-dungeon/src/api.rs
Normal file
1040
crates/ghostlight-dungeon/src/api.rs
Normal file
File diff suppressed because it is too large
Load diff
939
crates/ghostlight-dungeon/src/app_session.rs
Normal file
939
crates/ghostlight-dungeon/src/app_session.rs
Normal file
|
|
@ -0,0 +1,939 @@
|
|||
//! Local custody for authenticated Heimdall sessions.
|
||||
//!
|
||||
//! This store owns only browser-session continuity. It does not own world
|
||||
//! selection, commands, idempotency, exports, or fictional state.
|
||||
|
||||
use crate::heimdall::{VerifiedSessionAdmission, VerifiedSessionRefresh};
|
||||
use ghostlight::VerifiedPrincipalEvidence;
|
||||
use aes_gcm::{Aes256Gcm, KeyInit, aead::Aead};
|
||||
use anyhow::{Context, bail};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use chrono::{DateTime, Utc};
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||
use rand::RngCore;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
const STORE_TYPE: &str = "ghostlight.app_session_store.v2";
|
||||
/// `pub(crate)` so the recipe-drift test in `idunn_health.rs` can check the
|
||||
/// `app-sessions` state slot's schema against this constant.
|
||||
pub(crate) const STORE_SCHEMA: &str = "ghostlight.app_session_store.v2";
|
||||
const STORE_KEY: &str = "primary";
|
||||
const MAX_SESSION_RECORDS: usize = 1_024;
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct AppSessionState {
|
||||
schema: String,
|
||||
sessions: BTreeMap<String, AppSession>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct AppSession {
|
||||
schema: String,
|
||||
cookie_hash: String,
|
||||
account_subject_hash: String,
|
||||
heimdall_session_id: String,
|
||||
access_revision: u64,
|
||||
verified_capabilities: Vec<String>,
|
||||
access_expires_at: DateTime<Utc>,
|
||||
refresh_expires_at: DateTime<Utc>,
|
||||
encrypted_refresh_claim: String,
|
||||
created_at: DateTime<Utc>,
|
||||
last_refresh_at: DateTime<Utc>,
|
||||
revoked_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
/// The clause by which the local commit refuses a refresh Heimdall executed.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub(crate) enum RefreshRefusal {
|
||||
#[error("local session was revoked during refresh")]
|
||||
Revoked,
|
||||
#[error("local session moved to another revision since the refresh candidate was taken")]
|
||||
MovedSinceCandidate,
|
||||
#[error("refresh receipt revision went backwards")]
|
||||
RevisionWentBackwards,
|
||||
#[error("refresh receipt names a different Heimdall session")]
|
||||
SessionId,
|
||||
#[error("refresh receipt names a different account")]
|
||||
Account,
|
||||
}
|
||||
|
||||
pub(crate) struct RefreshCandidate {
|
||||
pub(crate) cookie_hash: String,
|
||||
pub(crate) account_subject_hash: String,
|
||||
pub(crate) heimdall_session_id: String,
|
||||
pub(crate) access_revision: u64,
|
||||
pub(crate) refresh_claim: String,
|
||||
}
|
||||
|
||||
pub(crate) struct AppSessionOwner {
|
||||
store: OwnedRedbMessagePackBackingStore,
|
||||
row: CultCacheEnvelope,
|
||||
state: AppSessionState,
|
||||
wrapping_key: [u8; 32],
|
||||
healthy: bool,
|
||||
}
|
||||
|
||||
impl AppSessionOwner {
|
||||
pub(crate) fn open(
|
||||
store_path: impl AsRef<Path>,
|
||||
wrapping_key_path: impl AsRef<Path>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let wrapping_key = read_wrapping_key(wrapping_key_path.as_ref())?;
|
||||
let store = OwnedRedbMessagePackBackingStore::new(store_path.as_ref())?;
|
||||
store
|
||||
.validate_path_identity()
|
||||
.context("app-session store path identity is invalid")?;
|
||||
let rows = store.pull_all()?;
|
||||
let (row, state) = match rows.as_slice() {
|
||||
[] => {
|
||||
let state = AppSessionState {
|
||||
schema: STORE_SCHEMA.into(),
|
||||
sessions: BTreeMap::new(),
|
||||
};
|
||||
let row = envelope(&state)?;
|
||||
if !store.compare_and_swap_batch(&[], vec![row.clone()])? {
|
||||
bail!("app-session store changed during initialization");
|
||||
}
|
||||
(row, state)
|
||||
}
|
||||
[row]
|
||||
if row.r#type == STORE_TYPE
|
||||
&& row.key == STORE_KEY
|
||||
&& row.schema_id.as_deref() == Some(STORE_SCHEMA) =>
|
||||
{
|
||||
let state: AppSessionState =
|
||||
rmp_serde::from_slice(&row.payload).context("app-session state is corrupt")?;
|
||||
if rmp_serde::to_vec_named(&state)? != row.payload {
|
||||
bail!("app-session state is not canonical");
|
||||
}
|
||||
if state.schema != STORE_SCHEMA {
|
||||
bail!("app-session state schema is invalid");
|
||||
}
|
||||
validate_state(&state, &wrapping_key)?;
|
||||
(row.clone(), state)
|
||||
}
|
||||
_ => bail!(
|
||||
"app-session v2 store contains foreign or legacy records; start with a fresh store"
|
||||
),
|
||||
};
|
||||
Ok(Self {
|
||||
store,
|
||||
row,
|
||||
state,
|
||||
wrapping_key,
|
||||
healthy: true,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn create_session(
|
||||
&mut self,
|
||||
input: VerifiedSessionAdmission,
|
||||
) -> anyhow::Result<String> {
|
||||
if !input
|
||||
.capabilities()
|
||||
.iter()
|
||||
.any(|value| value == "app_access")
|
||||
{
|
||||
bail!("Heimdall session lacks app_access");
|
||||
}
|
||||
if input.account_id().trim().is_empty()
|
||||
|| input.heimdall_session_id().trim().is_empty()
|
||||
|| input.refresh_claim().is_empty()
|
||||
|| input.refresh_expires_at() <= input.access_expires_at()
|
||||
{
|
||||
bail!("Heimdall session material is invalid");
|
||||
}
|
||||
let mut cookie = [0_u8; 32];
|
||||
rand::rng().fill_bytes(&mut cookie);
|
||||
let raw_cookie = URL_SAFE_NO_PAD.encode(cookie);
|
||||
let cookie_hash = secret_hash(&raw_cookie);
|
||||
let account_subject_hash = secret_hash(&format!("heimdall-account:{}", input.account_id()));
|
||||
let now = Utc::now();
|
||||
let session = AppSession {
|
||||
schema: "ghostlight.app_session.v2".into(),
|
||||
cookie_hash: cookie_hash.clone(),
|
||||
account_subject_hash: account_subject_hash.clone(),
|
||||
heimdall_session_id: input.heimdall_session_id().to_owned(),
|
||||
access_revision: input.access_revision(),
|
||||
verified_capabilities: input.capabilities().to_vec(),
|
||||
access_expires_at: input.access_expires_at(),
|
||||
refresh_expires_at: input.refresh_expires_at(),
|
||||
encrypted_refresh_claim: wrap_refresh(
|
||||
&self.wrapping_key,
|
||||
&account_subject_hash,
|
||||
input.heimdall_session_id(),
|
||||
input.refresh_claim(),
|
||||
)?,
|
||||
created_at: now,
|
||||
last_refresh_at: now,
|
||||
revoked_at: None,
|
||||
};
|
||||
let mut next = self.state.clone();
|
||||
for previous in next.sessions.values_mut().filter(|previous| {
|
||||
previous.revoked_at.is_none()
|
||||
&& previous.heimdall_session_id == input.heimdall_session_id()
|
||||
}) {
|
||||
previous.revoked_at = Some(now);
|
||||
}
|
||||
next.sessions.insert(cookie_hash, session);
|
||||
self.commit(next)?;
|
||||
Ok(raw_cookie)
|
||||
}
|
||||
|
||||
pub(crate) fn is_healthy(&self) -> bool {
|
||||
self.healthy
|
||||
}
|
||||
|
||||
pub(crate) fn validate_custody(&mut self) -> anyhow::Result<()> {
|
||||
self.ensure_owned()
|
||||
}
|
||||
|
||||
pub(crate) fn account_for_cookie(
|
||||
&mut self,
|
||||
raw_cookie: &str,
|
||||
now: DateTime<Utc>,
|
||||
) -> anyhow::Result<Option<VerifiedPrincipalEvidence>> {
|
||||
self.ensure_owned()?;
|
||||
let Some(session) = self.state.sessions.get(&secret_hash(raw_cookie)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok((session.revoked_at.is_none()
|
||||
&& session.access_expires_at > now
|
||||
&& session.refresh_expires_at > now
|
||||
&& session
|
||||
.verified_capabilities
|
||||
.iter()
|
||||
.any(|value| value == "app_access"))
|
||||
.then(|| {
|
||||
VerifiedPrincipalEvidence::new(
|
||||
session.account_subject_hash.clone(),
|
||||
session.access_expires_at,
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn revoke_cookie(&mut self, raw_cookie: &str) -> anyhow::Result<bool> {
|
||||
self.ensure_owned()?;
|
||||
let cookie_hash = secret_hash(raw_cookie);
|
||||
let mut next = self.state.clone();
|
||||
let Some(session) = next.sessions.get_mut(&cookie_hash) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if session.revoked_at.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
session.revoked_at = Some(Utc::now());
|
||||
self.commit(next)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn revoke_cookie_hash(&mut self, cookie_hash: &str) -> anyhow::Result<bool> {
|
||||
self.ensure_owned()?;
|
||||
let mut next = self.state.clone();
|
||||
let Some(session) = next.sessions.get_mut(cookie_hash) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if session.revoked_at.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
session.revoked_at = Some(Utc::now());
|
||||
self.commit(next)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub(crate) fn session_for_logout(
|
||||
&mut self,
|
||||
raw_cookie: &str,
|
||||
) -> anyhow::Result<Option<RefreshCandidate>> {
|
||||
self.ensure_owned()?;
|
||||
let Some(session) = self.state.sessions.get(&secret_hash(raw_cookie)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
match self.refresh_candidate(session) {
|
||||
Ok(candidate) => Ok(Some(candidate)),
|
||||
Err(error) => self.poison(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sessions_due_for_refresh(
|
||||
&mut self,
|
||||
now: DateTime<Utc>,
|
||||
refresh_before: chrono::Duration,
|
||||
) -> anyhow::Result<Vec<RefreshCandidate>> {
|
||||
self.ensure_owned()?;
|
||||
let candidates = self
|
||||
.state
|
||||
.sessions
|
||||
.values()
|
||||
.filter(|session| {
|
||||
session.revoked_at.is_none()
|
||||
&& session.refresh_expires_at > now
|
||||
&& session.access_expires_at <= now + refresh_before
|
||||
})
|
||||
.map(|session| self.refresh_candidate(session))
|
||||
.collect::<anyhow::Result<Vec<_>>>();
|
||||
match candidates {
|
||||
Ok(candidates) => Ok(candidates),
|
||||
Err(error) => self.poison(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn apply_refresh(
|
||||
&mut self,
|
||||
cookie_hash: &str,
|
||||
expected_access_revision: u64,
|
||||
input: VerifiedSessionRefresh,
|
||||
) -> anyhow::Result<()> {
|
||||
if !input
|
||||
.capabilities()
|
||||
.iter()
|
||||
.any(|value| value == "app_access")
|
||||
{
|
||||
bail!("refreshed Heimdall session lacks app_access");
|
||||
}
|
||||
if input.refresh_claim().is_empty()
|
||||
|| input.refresh_expires_at() <= input.access_expires_at()
|
||||
{
|
||||
bail!("refreshed Heimdall session material is invalid");
|
||||
}
|
||||
let mut next = self.state.clone();
|
||||
let session = next
|
||||
.sessions
|
||||
.get_mut(cookie_hash)
|
||||
.context("local session vanished during refresh")?;
|
||||
if session.revoked_at.is_some() {
|
||||
return Err(RefreshRefusal::Revoked.into());
|
||||
}
|
||||
if session.access_revision != expected_access_revision {
|
||||
return Err(RefreshRefusal::MovedSinceCandidate.into());
|
||||
}
|
||||
// Heimdall's access_revision is a revocation epoch: refresh rotates
|
||||
// the token at the same revision, so equal is the normal receipt and
|
||||
// only a lower one is a refusal.
|
||||
if input.access_revision() < expected_access_revision {
|
||||
return Err(RefreshRefusal::RevisionWentBackwards.into());
|
||||
}
|
||||
if session.heimdall_session_id != input.heimdall_session_id() {
|
||||
return Err(RefreshRefusal::SessionId.into());
|
||||
}
|
||||
if session.account_subject_hash
|
||||
!= secret_hash(&format!("heimdall-account:{}", input.account_id()))
|
||||
{
|
||||
return Err(RefreshRefusal::Account.into());
|
||||
}
|
||||
session.access_revision = input.access_revision();
|
||||
session.verified_capabilities = input.capabilities().to_vec();
|
||||
session.access_expires_at = input.access_expires_at();
|
||||
session.refresh_expires_at = input.refresh_expires_at();
|
||||
session.encrypted_refresh_claim = wrap_refresh(
|
||||
&self.wrapping_key,
|
||||
&session.account_subject_hash,
|
||||
&session.heimdall_session_id,
|
||||
input.refresh_claim(),
|
||||
)?;
|
||||
session.last_refresh_at = Utc::now();
|
||||
self.commit(next)
|
||||
}
|
||||
|
||||
fn refresh_candidate(&self, session: &AppSession) -> anyhow::Result<RefreshCandidate> {
|
||||
Ok(RefreshCandidate {
|
||||
cookie_hash: session.cookie_hash.clone(),
|
||||
account_subject_hash: session.account_subject_hash.clone(),
|
||||
heimdall_session_id: session.heimdall_session_id.clone(),
|
||||
access_revision: session.access_revision,
|
||||
refresh_claim: unwrap_refresh(
|
||||
&self.wrapping_key,
|
||||
&session.account_subject_hash,
|
||||
&session.heimdall_session_id,
|
||||
&session.encrypted_refresh_claim,
|
||||
)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn commit(&mut self, mut next: AppSessionState) -> anyhow::Result<()> {
|
||||
self.ensure_owned()?;
|
||||
prune_sessions(&mut next, Utc::now());
|
||||
let next_row = envelope(&next)?;
|
||||
let swapped = self
|
||||
.store
|
||||
.compare_and_swap_batch(std::slice::from_ref(&self.row), vec![next_row.clone()]);
|
||||
if !matches!(swapped, Ok(true)) {
|
||||
return self.poison(anyhow::anyhow!(
|
||||
"app-session commit outcome is uncertain; sole ownership was lost"
|
||||
));
|
||||
}
|
||||
if self.store.validate_path_identity().is_err() {
|
||||
return self.poison(anyhow::anyhow!(
|
||||
"app-session store path changed after durable commit"
|
||||
));
|
||||
}
|
||||
self.row = next_row;
|
||||
self.state = next;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_owned(&mut self) -> anyhow::Result<()> {
|
||||
if !self.healthy {
|
||||
bail!("app-session custody is poisoned; reopen the owner");
|
||||
}
|
||||
if self.store.validate_path_identity().is_err() {
|
||||
self.healthy = false;
|
||||
bail!("app-session store ownership was lost");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poison<T>(&mut self, error: anyhow::Error) -> anyhow::Result<T> {
|
||||
self.healthy = false;
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
|
||||
/// The idempotency key of the refresh that spends `refresh_claim`: a retry of
|
||||
/// that refresh derives the same key, the next refresh (a new claim) a new one,
|
||||
/// and the claim itself never leaves the process in it.
|
||||
pub(crate) fn refresh_idempotency_key(refresh_claim: &str) -> String {
|
||||
format!(
|
||||
"refresh:{}",
|
||||
secret_hash(&format!("heimdall-refresh-key:{refresh_claim}"))
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn secret_hash(value: &str) -> String {
|
||||
format!("sha256:{:x}", Sha256::digest(value.as_bytes()))
|
||||
}
|
||||
|
||||
fn envelope(state: &AppSessionState) -> anyhow::Result<CultCacheEnvelope> {
|
||||
Ok(CultCacheEnvelope {
|
||||
key: STORE_KEY.into(),
|
||||
r#type: STORE_TYPE.into(),
|
||||
payload: rmp_serde::to_vec_named(state)?,
|
||||
stored_at: Utc::now().to_rfc3339(),
|
||||
schema_id: Some(STORE_SCHEMA.into()),
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_state(state: &AppSessionState, wrapping_key: &[u8; 32]) -> anyhow::Result<()> {
|
||||
if state.schema != STORE_SCHEMA {
|
||||
bail!("app-session state schema is invalid");
|
||||
}
|
||||
for (key, session) in &state.sessions {
|
||||
if key != &session.cookie_hash
|
||||
|| !is_secret_hash(key)
|
||||
|| !is_secret_hash(&session.account_subject_hash)
|
||||
|| session.schema != "ghostlight.app_session.v2"
|
||||
|| session.heimdall_session_id.trim().is_empty()
|
||||
|| session.heimdall_session_id.trim() != session.heimdall_session_id
|
||||
|| !session
|
||||
.verified_capabilities
|
||||
.iter()
|
||||
.any(|value| value == "app_access")
|
||||
|| session.refresh_expires_at <= session.access_expires_at
|
||||
|| session.last_refresh_at < session.created_at
|
||||
|| session
|
||||
.revoked_at
|
||||
.is_some_and(|revoked_at| revoked_at < session.created_at)
|
||||
{
|
||||
bail!("app-session state contains a noncanonical session");
|
||||
}
|
||||
unwrap_refresh(
|
||||
wrapping_key,
|
||||
&session.account_subject_hash,
|
||||
&session.heimdall_session_id,
|
||||
&session.encrypted_refresh_claim,
|
||||
)
|
||||
.context("app-session state contains an unreadable refresh claim")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_secret_hash(value: &str) -> bool {
|
||||
value.len() == 71
|
||||
&& value.strip_prefix("sha256:").is_some_and(|hex| {
|
||||
hex.bytes()
|
||||
.all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
|
||||
})
|
||||
}
|
||||
|
||||
fn prune_sessions(state: &mut AppSessionState, now: DateTime<Utc>) {
|
||||
let retention_floor = now - chrono::Duration::days(7);
|
||||
state.sessions.retain(|_, session| {
|
||||
session.refresh_expires_at > retention_floor
|
||||
&& session
|
||||
.revoked_at
|
||||
.is_none_or(|revoked_at| revoked_at > retention_floor)
|
||||
});
|
||||
if state.sessions.len() <= MAX_SESSION_RECORDS {
|
||||
return;
|
||||
}
|
||||
let mut oldest = state
|
||||
.sessions
|
||||
.iter()
|
||||
.map(|(key, session)| {
|
||||
let live = session.revoked_at.is_none() && session.refresh_expires_at > now;
|
||||
(live, session.last_refresh_at, key.clone())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
oldest.sort();
|
||||
for (_, _, key) in oldest
|
||||
.into_iter()
|
||||
.take(state.sessions.len() - MAX_SESSION_RECORDS)
|
||||
{
|
||||
state.sessions.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_wrapping_key(path: &Path) -> anyhow::Result<[u8; 32]> {
|
||||
let source = std::fs::read(path)
|
||||
.with_context(|| format!("failed to read session wrapping key {}", path.display()))?;
|
||||
let decoded = if source.len() == 32 {
|
||||
source
|
||||
} else {
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(std::str::from_utf8(&source)?.trim())
|
||||
.context("session wrapping key must be 32 raw bytes or base64url")?
|
||||
};
|
||||
decoded
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("session wrapping key must be exactly 32 bytes"))
|
||||
}
|
||||
|
||||
fn wrap_refresh(
|
||||
key: &[u8; 32],
|
||||
account_hash: &str,
|
||||
session_id: &str,
|
||||
claim: &str,
|
||||
) -> anyhow::Result<String> {
|
||||
let mut iv = [0_u8; 12];
|
||||
rand::rng().fill_bytes(&mut iv);
|
||||
let aad = format!("ghostlight.app_session.refresh.v2\n{account_hash}\n{session_id}");
|
||||
let ciphertext = Aes256Gcm::new_from_slice(key)?
|
||||
.encrypt(
|
||||
(&iv).into(),
|
||||
aes_gcm::aead::Payload {
|
||||
msg: claim.as_bytes(),
|
||||
aad: aad.as_bytes(),
|
||||
},
|
||||
)
|
||||
.map_err(|_| anyhow::anyhow!("failed to wrap Heimdall refresh claim"))?;
|
||||
Ok(format!(
|
||||
"{}.{}",
|
||||
URL_SAFE_NO_PAD.encode(iv),
|
||||
URL_SAFE_NO_PAD.encode(ciphertext)
|
||||
))
|
||||
}
|
||||
|
||||
fn unwrap_refresh(
|
||||
key: &[u8; 32],
|
||||
account_hash: &str,
|
||||
session_id: &str,
|
||||
wrapped: &str,
|
||||
) -> anyhow::Result<String> {
|
||||
let (iv, ciphertext) = wrapped
|
||||
.split_once('.')
|
||||
.context("wrapped refresh claim is malformed")?;
|
||||
let iv: [u8; 12] = URL_SAFE_NO_PAD
|
||||
.decode(iv)?
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("wrapped refresh IV is invalid"))?;
|
||||
let ciphertext = URL_SAFE_NO_PAD.decode(ciphertext)?;
|
||||
let aad = format!("ghostlight.app_session.refresh.v2\n{account_hash}\n{session_id}");
|
||||
let plaintext = Aes256Gcm::new_from_slice(key)?
|
||||
.decrypt(
|
||||
(&iv).into(),
|
||||
aes_gcm::aead::Payload {
|
||||
msg: &ciphertext,
|
||||
aad: aad.as_bytes(),
|
||||
},
|
||||
)
|
||||
.map_err(|_| anyhow::anyhow!("failed to unwrap Heimdall refresh claim"))?;
|
||||
String::from_utf8(plaintext).context("Heimdall refresh claim is not UTF-8")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every `.rs` file under `src`, subdirectories included, with everything
|
||||
/// a `#[cfg(test)]` attribute guards removed — whatever that item is, and
|
||||
/// whatever a test module is called.
|
||||
///
|
||||
/// The item's extent is read from the layout: an attribute at indent `N`
|
||||
/// guards lines until the first later line at indent `N` that closes a
|
||||
/// block, or, for an item with no body, until the first line at indent `N`
|
||||
/// that ends in `;` or `,`. This is a claim about rustfmt's output, not
|
||||
/// about Rust's grammar, and it is the reason the scan does not try to
|
||||
/// balance braces: braces inside string and character literals are not
|
||||
/// block structure, and a scanner that counts them reads the end of a test
|
||||
/// module in the wrong place.
|
||||
fn production_sources() -> Vec<(std::path::PathBuf, String)> {
|
||||
fn indent(line: &str) -> usize {
|
||||
line.len() - line.trim_start().len()
|
||||
}
|
||||
|
||||
fn strip_cfg_test(text: &str) -> String {
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
let mut kept: Vec<&str> = Vec::new();
|
||||
let mut index = 0;
|
||||
while index < lines.len() {
|
||||
let line = lines[index];
|
||||
if line.trim() != "#[cfg(test)]" {
|
||||
kept.push(line);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
let guard = indent(line);
|
||||
index += 1;
|
||||
// A body opens on the attribute's own item; without one, the
|
||||
// item ends at its first terminator.
|
||||
let mut opened = lines
|
||||
.get(index)
|
||||
.is_some_and(|next| next.trim_end().ends_with('{'));
|
||||
while index < lines.len() {
|
||||
let body = lines[index];
|
||||
index += 1;
|
||||
let trimmed = body.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if opened {
|
||||
if indent(body) == guard
|
||||
&& (trimmed == "}" || trimmed == "};" || trimmed == "},")
|
||||
{
|
||||
break;
|
||||
}
|
||||
} else if indent(body) == guard
|
||||
&& (trimmed.ends_with(';') || trimmed.ends_with(','))
|
||||
{
|
||||
break;
|
||||
} else if indent(body) == guard && trimmed.ends_with('{') {
|
||||
opened = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
kept.join("\n")
|
||||
}
|
||||
|
||||
let mut sources = Vec::new();
|
||||
let mut pending = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
|
||||
while let Some(directory) = pending.pop() {
|
||||
for entry in std::fs::read_dir(&directory).expect("the source tree reads") {
|
||||
let path = entry.expect("a readable entry").path();
|
||||
if path.is_dir() {
|
||||
pending.push(path);
|
||||
continue;
|
||||
}
|
||||
if path.extension().and_then(|value| value.to_str()) != Some("rs") {
|
||||
continue;
|
||||
}
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.expect("the source reads")
|
||||
.replace("\r\n", "\n");
|
||||
sources.push((path, strip_cfg_test(&text)));
|
||||
}
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
/// True when the text immediately following the type's name calls its
|
||||
/// `new`. Written as a scan rather than one literal so the qualified
|
||||
/// `<Type>::new(` form and any whitespace the formatter may introduce
|
||||
/// count the same as the plain path.
|
||||
fn calls_new(tail: &str) -> bool {
|
||||
let tail = tail.trim_start();
|
||||
let tail = tail.strip_prefix('>').unwrap_or(tail).trim_start();
|
||||
let Some(tail) = tail.strip_prefix("::") else {
|
||||
return false;
|
||||
};
|
||||
let Some(tail) = tail.trim_start().strip_prefix("new") else {
|
||||
return false;
|
||||
};
|
||||
tail.trim_start().starts_with('(')
|
||||
}
|
||||
|
||||
/// The library owns `VerifiedPrincipalEvidence` and gives it a public
|
||||
/// constructor, so the single-minter rule its private fields used to
|
||||
/// enforce is this one: production mints it in `account_for_cookie` and
|
||||
/// nowhere else, from a live cookie this owner holds custody of. A second
|
||||
/// minter anywhere in Dungeon's production source is a second authority
|
||||
/// over who the kernel believes is speaking.
|
||||
///
|
||||
/// The type is followed by name, so production may not give it a second
|
||||
/// name: an `as` import or a type alias is refused outright rather than
|
||||
/// counted, because a renamed minter is one this test cannot follow. What
|
||||
/// it still cannot see is a call that never spells the type — a macro
|
||||
/// expansion, or a generic instantiated elsewhere.
|
||||
#[test]
|
||||
fn soul_exactly_one_production_site_mints_verified_principal_evidence() {
|
||||
// Assembled from halves so this test's own source is never a match,
|
||||
// whatever the scan above decides about this module's extent.
|
||||
let name = format!("VerifiedPrincipal{}", "Evidence");
|
||||
let mut sites = Vec::new();
|
||||
for (path, production) in production_sources() {
|
||||
for (at, _) in production.match_indices(name.as_str()) {
|
||||
let tail = &production[at + name.len()..];
|
||||
assert!(
|
||||
!tail.trim_start().starts_with("as "),
|
||||
"{} renames {name} on import",
|
||||
path.display()
|
||||
);
|
||||
if calls_new(tail) {
|
||||
sites.push(path.clone());
|
||||
}
|
||||
}
|
||||
for line in production.lines() {
|
||||
assert!(
|
||||
!(line.trim_start().starts_with("type ") && line.contains(name.as_str())),
|
||||
"{} aliases {name} to another name: {line}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
sites.len(),
|
||||
1,
|
||||
"production mints {name} in exactly one place: {sites:?}"
|
||||
);
|
||||
assert!(
|
||||
sites[0].ends_with("app_session.rs"),
|
||||
"the one minter is not this owner: {:?}",
|
||||
sites[0]
|
||||
);
|
||||
}
|
||||
|
||||
fn session(claim: &str) -> VerifiedSessionAdmission {
|
||||
VerifiedSessionAdmission::fixture(
|
||||
"account-1",
|
||||
"heimdall-session-1",
|
||||
3,
|
||||
Utc::now() + chrono::Duration::minutes(5),
|
||||
Utc::now() + chrono::Duration::days(7),
|
||||
claim,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_rejects_an_alternate_messagepack_shape() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [5_u8; 32]).unwrap();
|
||||
let store_path = directory.path().join("app-sessions-v2.cc");
|
||||
let store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap();
|
||||
let state = AppSessionState {
|
||||
schema: STORE_SCHEMA.into(),
|
||||
sessions: BTreeMap::new(),
|
||||
};
|
||||
let row = CultCacheEnvelope {
|
||||
key: STORE_KEY.into(),
|
||||
r#type: STORE_TYPE.into(),
|
||||
payload: rmp_serde::to_vec(&state).unwrap(),
|
||||
stored_at: Utc::now().to_rfc3339(),
|
||||
schema_id: Some(STORE_SCHEMA.into()),
|
||||
};
|
||||
assert!(store.compare_and_swap_batch(&[], vec![row]).unwrap());
|
||||
drop(store);
|
||||
assert!(AppSessionOwner::open(&store_path, &key).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stores_only_session_custody_and_reopens() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [7_u8; 32]).unwrap();
|
||||
let store = directory.path().join("app-sessions-v2.cc");
|
||||
let mut owner = AppSessionOwner::open(&store, &key).unwrap();
|
||||
let cookie = owner
|
||||
.create_session(session("private-refresh-claim"))
|
||||
.unwrap();
|
||||
let account = owner
|
||||
.account_for_cookie(&cookie, Utc::now())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let account_hash = account.account_subject_hash().to_owned();
|
||||
drop(owner);
|
||||
|
||||
let mut reopened = AppSessionOwner::open(&store, &key).unwrap();
|
||||
assert_eq!(
|
||||
reopened
|
||||
.account_for_cookie(&cookie, Utc::now())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.account_subject_hash(),
|
||||
account_hash
|
||||
);
|
||||
assert!(reopened.revoke_cookie(&cookie).unwrap());
|
||||
assert_eq!(
|
||||
reopened.account_for_cookie(&cookie, Utc::now()).unwrap(),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_heimdall_adoption_retry_rotates_the_only_live_cookie() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [9_u8; 32]).unwrap();
|
||||
let store = directory.path().join("app-sessions-v2.cc");
|
||||
let mut owner = AppSessionOwner::open(&store, &key).unwrap();
|
||||
let first = owner
|
||||
.create_session(session("same-refresh-receipt"))
|
||||
.unwrap();
|
||||
let second = owner
|
||||
.create_session(session("same-refresh-receipt"))
|
||||
.unwrap();
|
||||
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(owner.account_for_cookie(&first, Utc::now()).unwrap(), None);
|
||||
assert!(
|
||||
owner
|
||||
.account_for_cookie(&second, Utc::now())
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(
|
||||
owner
|
||||
.state
|
||||
.sessions
|
||||
.values()
|
||||
.filter(|session| session.revoked_at.is_none())
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_legacy_or_foreign_store_instead_of_migrating_it() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [3_u8; 32]).unwrap();
|
||||
let store_path = directory.path().join("app-sessions-v2.cc");
|
||||
let store = OwnedRedbMessagePackBackingStore::new(&store_path).unwrap();
|
||||
let foreign = CultCacheEnvelope {
|
||||
key: "primary".into(),
|
||||
r#type: "app_session_store.v1".into(),
|
||||
payload: vec![],
|
||||
stored_at: Utc::now().to_rfc3339(),
|
||||
schema_id: Some("ghostlight.app_session_store.v1".into()),
|
||||
};
|
||||
assert!(store.compare_and_swap_batch(&[], vec![foreign]).unwrap());
|
||||
assert!(AppSessionOwner::open(&store_path, &key).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refresh_for_a_session_that_moved_is_refused_by_name() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [5_u8; 32]).unwrap();
|
||||
let mut owner =
|
||||
AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap();
|
||||
let cookie = owner
|
||||
.create_session(VerifiedSessionAdmission::fixture(
|
||||
"account",
|
||||
"session",
|
||||
1,
|
||||
Utc::now() + chrono::Duration::minutes(1),
|
||||
Utc::now() + chrono::Duration::days(1),
|
||||
"claim-0",
|
||||
))
|
||||
.unwrap();
|
||||
let receipt = VerifiedSessionRefresh::fixture(
|
||||
"account",
|
||||
"session",
|
||||
1,
|
||||
Utc::now() + chrono::Duration::minutes(1),
|
||||
Utc::now() + chrono::Duration::days(1),
|
||||
"claim-1",
|
||||
);
|
||||
let error = owner
|
||||
.apply_refresh(&secret_hash(&cookie), 0, receipt)
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<RefreshRefusal>(),
|
||||
Some(&RefreshRefusal::MovedSinceCandidate)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_claim_is_encrypted_and_exactly_bound() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [11_u8; 32]).unwrap();
|
||||
let store = directory.path().join("app-sessions-v2.cc");
|
||||
let mut owner = AppSessionOwner::open(&store, &key).unwrap();
|
||||
let cookie = owner
|
||||
.create_session(session("needle-private-refresh"))
|
||||
.unwrap();
|
||||
let candidate = owner.session_for_logout(&cookie).unwrap().unwrap();
|
||||
assert_eq!(candidate.refresh_claim, "needle-private-refresh");
|
||||
drop(owner);
|
||||
let bytes = std::fs::read(store).unwrap();
|
||||
assert!(
|
||||
!bytes
|
||||
.windows("needle-private-refresh".len())
|
||||
.any(|window| window == b"needle-private-refresh")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_the_store_path_revokes_session_authentication_until_reopen() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [19_u8; 32]).unwrap();
|
||||
let path = directory.path().join("app-sessions-v2.cc");
|
||||
let displaced = directory.path().join("displaced.cc");
|
||||
let mut owner = AppSessionOwner::open(&path, &key).unwrap();
|
||||
let cookie = owner
|
||||
.create_session(session("private-refresh-claim"))
|
||||
.unwrap();
|
||||
|
||||
std::fs::rename(&path, &displaced).unwrap();
|
||||
std::fs::File::create(&path).unwrap();
|
||||
assert!(owner.account_for_cookie(&cookie, Utc::now()).is_err());
|
||||
assert!(!owner.is_healthy());
|
||||
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::rename(&displaced, &path).unwrap();
|
||||
assert!(owner.account_for_cookie(&cookie, Utc::now()).is_err());
|
||||
drop(owner);
|
||||
|
||||
let mut reopened = AppSessionOwner::open(&path, &key).unwrap();
|
||||
assert!(
|
||||
reopened
|
||||
.account_for_cookie(&cookie, Utc::now())
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reopen_rejects_corrupt_inner_session_custody() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [23_u8; 32]).unwrap();
|
||||
let path = directory.path().join("app-sessions-v2.cc");
|
||||
let mut owner = AppSessionOwner::open(&path, &key).unwrap();
|
||||
owner
|
||||
.create_session(session("private-refresh-claim"))
|
||||
.unwrap();
|
||||
drop(owner);
|
||||
|
||||
let store = OwnedRedbMessagePackBackingStore::new(&path).unwrap();
|
||||
let rows = store.pull_all().unwrap();
|
||||
let mut state: AppSessionState = rmp_serde::from_slice(&rows[0].payload).unwrap();
|
||||
state
|
||||
.sessions
|
||||
.values_mut()
|
||||
.next()
|
||||
.unwrap()
|
||||
.encrypted_refresh_claim = "not-an-encrypted-claim".into();
|
||||
let corrupt = envelope(&state).unwrap();
|
||||
assert!(store.compare_and_swap_batch(&rows, vec![corrupt]).unwrap());
|
||||
drop(store);
|
||||
|
||||
assert!(AppSessionOwner::open(&path, &key).is_err());
|
||||
}
|
||||
}
|
||||
462
crates/ghostlight-dungeon/src/begin.rs
Normal file
462
crates/ghostlight-dungeon/src/begin.rs
Normal file
|
|
@ -0,0 +1,462 @@
|
|||
//! Begin: the one step that makes a world and its root timeline.
|
||||
//!
|
||||
//! The player gives a title, a name, an optional brief and an optional vault
|
||||
//! profile. Begin creates the world through the kernel, records the world and
|
||||
//! its root timeline in the catalog, seeds from the vault snapshot when a
|
||||
//! profile was chosen, then approves and activates. With no profile the world
|
||||
//! activates unseeded. Every kernel command is a separate command with a
|
||||
//! derived id, so replaying the same key resumes where the last attempt
|
||||
//! stopped and never repeats what the kernel already committed.
|
||||
|
||||
use crate::{
|
||||
catalog::{Catalog, Timeline, WorldRecord, timeline_id},
|
||||
timelines::{TimelineHost, Timelines},
|
||||
};
|
||||
use chrono::Utc;
|
||||
use ghostlight::{
|
||||
CommandBody, CommandId, ControllerError, CreateWorldIntent, EvidenceSource, Lens, LensWeights,
|
||||
MailboxError, PrincipalCommandIntent, SeedPort, VerifiedPrincipalEvidence, WorldPhase,
|
||||
WorldSnapshot,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
use tokio::sync::Mutex;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Seeding sessions Begin may spend before approving. Each session is one
|
||||
/// model round trip, so this is the credit bound of a Begin.
|
||||
const BEGIN_SEED_SESSIONS: usize = 8;
|
||||
|
||||
/// A vault snapshot ready to seed from: its content id and the evidence
|
||||
/// source that reads only that snapshot.
|
||||
pub(crate) struct VaultSeed {
|
||||
pub(crate) snapshot_id: String,
|
||||
pub(crate) evidence: Arc<dyn EvidenceSource>,
|
||||
}
|
||||
|
||||
/// The vault profiles a player may choose at Begin. Opening one yields the
|
||||
/// snapshot to seed from.
|
||||
pub(crate) trait Vaults: Send + Sync {
|
||||
fn names(&self) -> Vec<String>;
|
||||
fn open(&self, profile: &str) -> anyhow::Result<VaultSeed>;
|
||||
}
|
||||
|
||||
/// No profile is configured: every Begin activates unseeded. Cut 1c replaces
|
||||
/// this with the snapshot-backed profile catalog once vault import lands.
|
||||
pub(crate) struct NoVaults;
|
||||
|
||||
impl Vaults for NoVaults {
|
||||
fn names(&self) -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn open(&self, profile: &str) -> anyhow::Result<VaultSeed> {
|
||||
anyhow::bail!("vault profile `{profile}` is not configured")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct BeginRequest {
|
||||
/// The client's idempotency key, a uuid.
|
||||
pub(crate) key: String,
|
||||
pub(crate) title: String,
|
||||
/// What the player is called in the world.
|
||||
pub(crate) name: String,
|
||||
pub(crate) brief: Option<String>,
|
||||
pub(crate) vault: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct Begun {
|
||||
pub(crate) timeline: String,
|
||||
pub(crate) reached: &'static str,
|
||||
}
|
||||
|
||||
/// Why a Begin stopped. What the kernel committed before stays committed, and
|
||||
/// the same key resumes it.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct BeginError {
|
||||
pub(crate) step: &'static str,
|
||||
pub(crate) cause: String,
|
||||
/// The outcome of a submitted command is unknown; the caller must not read
|
||||
/// it as a refusal.
|
||||
pub(crate) unknown: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BeginError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "the begin stopped at its {} step: {}", self.step, self.cause)
|
||||
}
|
||||
}
|
||||
|
||||
fn stopped(step: &'static str, cause: impl std::fmt::Display) -> BeginError {
|
||||
BeginError {
|
||||
step,
|
||||
cause: cause.to_string(),
|
||||
unknown: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_mailbox(step: &'static str, error: MailboxError) -> BeginError {
|
||||
BeginError {
|
||||
step,
|
||||
unknown: matches!(error, MailboxError::OutcomeUnknown { .. }),
|
||||
cause: error.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The timeline a key mints, derived so a replayed Begin finds its own
|
||||
/// timeline instead of making a second one.
|
||||
fn derived_timeline(key: Uuid) -> String {
|
||||
let digest = Sha256::new()
|
||||
.chain_update(b"ghostlight.dungeon.begin.timeline.v1")
|
||||
.chain_update(key.as_bytes())
|
||||
.finalize();
|
||||
let mut bytes = [0_u8; 16];
|
||||
bytes.copy_from_slice(&digest[..16]);
|
||||
timeline_id(Uuid::from_bytes(bytes))
|
||||
}
|
||||
|
||||
fn derived_step_id(key: Uuid, step: &str) -> Result<CommandId, BeginError> {
|
||||
let digest = Sha256::new()
|
||||
.chain_update(b"ghostlight.world.begin.v1")
|
||||
.chain_update(key.as_bytes())
|
||||
.chain_update(step.as_bytes())
|
||||
.finalize();
|
||||
let mut bytes = [0_u8; 16];
|
||||
bytes.copy_from_slice(&digest[..16]);
|
||||
CommandId::parse_uuid(&Uuid::from_bytes(bytes).to_string()).map_err(|error| stopped("id", error))
|
||||
}
|
||||
|
||||
async fn current(host: &TimelineHost) -> Result<Option<WorldSnapshot>, MailboxError> {
|
||||
match host.world.snapshot().await {
|
||||
Ok(snapshot) => Ok(Some(snapshot)),
|
||||
Err(MailboxError::Kernel(ghostlight::KernelError::WorldNotCreated)) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn begin(
|
||||
catalog: &Mutex<Catalog>,
|
||||
timelines: &Timelines,
|
||||
vaults: &dyn Vaults,
|
||||
principal: &VerifiedPrincipalEvidence,
|
||||
request: BeginRequest,
|
||||
) -> Result<Begun, BeginError> {
|
||||
let owner = principal.account_subject_hash().to_owned();
|
||||
let key = Uuid::parse_str(&request.key).map_err(|_| stopped("key", "the begin key is not a uuid"))?;
|
||||
let command_id =
|
||||
CommandId::parse_uuid(&request.key).map_err(|_| stopped("key", "the begin key is not a uuid"))?;
|
||||
if request.title.trim().is_empty() || request.name.trim().is_empty() {
|
||||
return Err(stopped("request", "a world needs a title and a name"));
|
||||
}
|
||||
let timeline = derived_timeline(key);
|
||||
{
|
||||
let catalog = catalog.lock().await;
|
||||
if catalog.timeline(&timeline).is_some() && catalog.owned_timeline(&owner, &timeline).is_none() {
|
||||
return Err(stopped("key", "that begin key belongs to another player"));
|
||||
}
|
||||
}
|
||||
// The vault is resolved before anything is created: an unknown profile
|
||||
// refuses the Begin whole.
|
||||
let vault = match request.vault.as_deref() {
|
||||
Some(profile) => Some(vaults.open(profile).map_err(|error| stopped("vault", error))?),
|
||||
None => None,
|
||||
};
|
||||
let host = timelines
|
||||
.host(&timeline)
|
||||
.await
|
||||
.map_err(|error| stopped("open", error))?;
|
||||
|
||||
let brief = request.brief.unwrap_or_default();
|
||||
let world_id = match current(&host).await.map_err(|error| from_mailbox("create", error))? {
|
||||
Some(world) => world.world_id,
|
||||
None => {
|
||||
host.world
|
||||
.create(
|
||||
CreateWorldIntent {
|
||||
id: command_id,
|
||||
title: request.title.clone(),
|
||||
brief: brief.clone(),
|
||||
human_subject_label: request.name,
|
||||
narrative_persona_label: None,
|
||||
operational_agent_label: None,
|
||||
targets: BTreeMap::new(),
|
||||
jurisdictions: Vec::new(),
|
||||
lens_weights: uniform_lens_weights(),
|
||||
},
|
||||
principal,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| from_mailbox("create", error))?
|
||||
.world_id
|
||||
}
|
||||
};
|
||||
let world_key = serde_json::to_value(world_id)
|
||||
.ok()
|
||||
.and_then(|value| value.as_str().map(str::to_owned))
|
||||
.ok_or_else(|| stopped("create", "the world id is not a string"))?;
|
||||
{
|
||||
let mut catalog = catalog.lock().await;
|
||||
if catalog.timeline(&timeline).is_none() {
|
||||
catalog
|
||||
.mint_timeline(
|
||||
Some(WorldRecord {
|
||||
world_id: world_key.clone(),
|
||||
title: request.title,
|
||||
owner,
|
||||
snapshot_id: vault.as_ref().map(|seed| seed.snapshot_id.clone()),
|
||||
created_at: Utc::now(),
|
||||
}),
|
||||
Timeline {
|
||||
id: timeline.clone(),
|
||||
world_id: world_key,
|
||||
parent: None,
|
||||
},
|
||||
)
|
||||
.map_err(|error| stopped("record", error))?;
|
||||
}
|
||||
}
|
||||
|
||||
let mut reached = "created";
|
||||
if let Some(world) = current(&host).await.map_err(|error| from_mailbox("seed", error))?
|
||||
&& world.phase == WorldPhase::Draft
|
||||
{
|
||||
if let Some(vault) = vault {
|
||||
let runner = host.controllers.seeder(
|
||||
SeedPort::new(host.world.clone(), principal.clone()),
|
||||
vault.evidence,
|
||||
(!brief.is_empty()).then_some(brief),
|
||||
);
|
||||
runner.sweep(BEGIN_SEED_SESSIONS).await.map_err(|error| {
|
||||
tracing::warn!(%error, "seeding a world could not complete");
|
||||
stopped("seed", describe_seed_failure(&error))
|
||||
})?;
|
||||
reached = "seeded";
|
||||
}
|
||||
for (name, body, done) in [
|
||||
("approve", CommandBody::ApproveDraft, "approved"),
|
||||
("activate", CommandBody::ActivateWorld, "activated"),
|
||||
] {
|
||||
let world = current(&host)
|
||||
.await
|
||||
.map_err(|error| from_mailbox(name, error))?
|
||||
.ok_or_else(|| stopped(name, "the world could not be read"))?;
|
||||
host.world
|
||||
.submit_principal(
|
||||
PrincipalCommandIntent {
|
||||
id: derived_step_id(key, name)?,
|
||||
world_id,
|
||||
expected_revision: world.revision,
|
||||
body,
|
||||
},
|
||||
principal,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| from_mailbox(name, error))?;
|
||||
reached = done;
|
||||
}
|
||||
} else {
|
||||
reached = "activated";
|
||||
}
|
||||
Ok(Begun { timeline, reached })
|
||||
}
|
||||
|
||||
/// A seed failure reaches the player as a category, never as the error's own
|
||||
/// text, which can name this process's endpoints.
|
||||
fn describe_seed_failure(error: &ControllerError) -> &'static str {
|
||||
match error {
|
||||
ControllerError::Inference { .. } | ControllerError::ProviderContract { .. } => {
|
||||
"seeding could not reach the model"
|
||||
}
|
||||
_ => "seeding could not complete",
|
||||
}
|
||||
}
|
||||
|
||||
/// Dungeon policy for a world created before Session Zero's sliders exist.
|
||||
fn uniform_lens_weights() -> LensWeights {
|
||||
LensWeights::new(Lens::ALL.into_iter().map(|lens| (lens, 1)).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
play::tests::{ScriptedPort, output},
|
||||
timelines::Shared,
|
||||
};
|
||||
use ghostlight::ControllerModels;
|
||||
use tokio::sync::{Semaphore, mpsc};
|
||||
|
||||
pub(crate) struct Rig {
|
||||
pub(crate) directory: tempfile::TempDir,
|
||||
pub(crate) catalog: Arc<Mutex<Catalog>>,
|
||||
pub(crate) timelines: Arc<Timelines>,
|
||||
pub(crate) port: Arc<ScriptedPort>,
|
||||
_fatal: mpsc::UnboundedReceiver<String>,
|
||||
}
|
||||
|
||||
/// One catalog and one timeline registry over a scripted inference port.
|
||||
pub(crate) fn rig(script: Vec<ghostlight::InferenceOutput>) -> Rig {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = std::fs::canonicalize(directory.path()).unwrap();
|
||||
crate::state_layout::prepare_admitted_state_layout(&root).unwrap();
|
||||
let port = ScriptedPort::new(script);
|
||||
let (fatal, receiver) = mpsc::unbounded_channel();
|
||||
let timelines = Timelines::new(
|
||||
root.clone(),
|
||||
Shared {
|
||||
inference: port.clone(),
|
||||
models: ControllerModels {
|
||||
projector: "claude-sonnet-5-5".into(),
|
||||
persona: "claude-sonnet-5-5".into(),
|
||||
interpreter: "claude-haiku-5-5".into(),
|
||||
operational_agent: "claude-haiku-5-5".into(),
|
||||
elaborator: "claude-sonnet-5-5".into(),
|
||||
},
|
||||
play_model: "claude-sonnet-5-5".into(),
|
||||
permits: Arc::new(Semaphore::new(2)),
|
||||
},
|
||||
fatal,
|
||||
);
|
||||
Rig {
|
||||
catalog: Arc::new(Mutex::new(Catalog::open(root.join("catalog.cc")).unwrap())),
|
||||
timelines: Arc::new(timelines),
|
||||
port,
|
||||
directory,
|
||||
_fatal: receiver,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn principal(account: &str) -> VerifiedPrincipalEvidence {
|
||||
VerifiedPrincipalEvidence::new(account, Utc::now() + chrono::Duration::hours(4))
|
||||
}
|
||||
|
||||
pub(crate) fn request(key: Uuid, vault: Option<&str>) -> BeginRequest {
|
||||
BeginRequest {
|
||||
key: key.to_string(),
|
||||
title: "Ashfall".into(),
|
||||
name: "Deru".into(),
|
||||
brief: Some("A cold harbor town.".into()),
|
||||
vault: vault.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
struct OneVault;
|
||||
|
||||
struct EmptyEvidence;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl EvidenceSource for EmptyEvidence {
|
||||
async fn retrieve(
|
||||
&self,
|
||||
_query: &ghostlight::EvidenceQuery,
|
||||
) -> Result<Vec<ghostlight::EvidenceReceipt>, ghostlight::EvidenceError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl Vaults for OneVault {
|
||||
fn names(&self) -> Vec<String> {
|
||||
vec!["delvehold".into()]
|
||||
}
|
||||
|
||||
fn open(&self, profile: &str) -> anyhow::Result<VaultSeed> {
|
||||
anyhow::ensure!(profile == "delvehold", "unknown profile");
|
||||
Ok(VaultSeed {
|
||||
snapshot_id: "vault-snapshot:feedface".into(),
|
||||
evidence: Arc::new(EmptyEvidence),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn one_vault() -> Arc<dyn Vaults> {
|
||||
Arc::new(OneVault)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn begin_with_a_profile_binds_the_snapshot_seeds_and_activates() {
|
||||
let rig = rig(vec![output("seed-1", vec![])]);
|
||||
let alice = principal("alice");
|
||||
let begun = begin(&rig.catalog, &rig.timelines, &OneVault, &alice, request(Uuid::new_v4(), Some("delvehold")))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(begun.reached, "activated");
|
||||
let catalog = rig.catalog.lock().await;
|
||||
let (timeline, world) = catalog.owned_timeline("alice", &begun.timeline).unwrap();
|
||||
assert_eq!(world.snapshot_id.as_deref(), Some("vault-snapshot:feedface"));
|
||||
assert!(timeline.parent.is_none());
|
||||
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(begun.timeline.as_str()));
|
||||
drop(catalog);
|
||||
// The seed went through the seed lane: the scripted model was asked,
|
||||
// on the elaborator's model, before the world activated.
|
||||
let seen = rig.port.seen_requests();
|
||||
assert!(!seen.is_empty(), "seeding must have called the model");
|
||||
let host = rig.timelines.host(&begun.timeline).await.unwrap();
|
||||
assert_eq!(host.world.snapshot().await.unwrap().phase, WorldPhase::Active);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn begin_without_a_profile_activates_unseeded_and_asks_no_model() {
|
||||
let rig = rig(vec![]);
|
||||
let begun = begin(&rig.catalog, &rig.timelines, &NoVaults, &principal("alice"), request(Uuid::new_v4(), None))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(begun.reached, "activated");
|
||||
assert!(rig.port.seen_requests().is_empty());
|
||||
let catalog = rig.catalog.lock().await;
|
||||
assert_eq!(catalog.owned_timeline("alice", &begun.timeline).unwrap().1.snapshot_id, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unknown_profile_refuses_the_begin_before_anything_is_made() {
|
||||
let rig = rig(vec![]);
|
||||
let error = begin(&rig.catalog, &rig.timelines, &OneVault, &principal("alice"), request(Uuid::new_v4(), Some("nowhere")))
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.step, "vault");
|
||||
assert!(rig.catalog.lock().await.timelines_of("alice").is_empty());
|
||||
assert!(rig.timelines.opened().await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replaying_a_begin_key_returns_the_same_timeline_and_makes_no_second_world() {
|
||||
let rig = rig(vec![]);
|
||||
let alice = principal("alice");
|
||||
let key = Uuid::new_v4();
|
||||
let first = begin(&rig.catalog, &rig.timelines, &NoVaults, &alice, request(key, None)).await.unwrap();
|
||||
let again = begin(&rig.catalog, &rig.timelines, &NoVaults, &alice, request(key, None)).await.unwrap();
|
||||
assert_eq!(first.timeline, again.timeline);
|
||||
assert_eq!(rig.catalog.lock().await.timelines_of("alice").len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn another_players_replay_of_a_begin_key_is_refused() {
|
||||
let rig = rig(vec![]);
|
||||
let key = Uuid::new_v4();
|
||||
begin(&rig.catalog, &rig.timelines, &NoVaults, &principal("alice"), request(key, None)).await.unwrap();
|
||||
let error = begin(&rig.catalog, &rig.timelines, &NoVaults, &principal("mallory"), request(key, None))
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.step, "key");
|
||||
assert!(rig.catalog.lock().await.timelines_of("mallory").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_seed_failure_stops_the_begin_without_leaking_the_error_text() {
|
||||
// An exhausted scripted port faults with its own detail.
|
||||
let rig = rig(vec![]);
|
||||
let error = begin(&rig.catalog, &rig.timelines, &OneVault, &principal("alice"), request(Uuid::new_v4(), Some("delvehold")))
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.step, "seed");
|
||||
assert!(!error.cause.contains("scripted port exhausted"), "{}", error.cause);
|
||||
// The world exists and is still a Draft; the same key resumes it.
|
||||
let catalog = rig.catalog.lock().await;
|
||||
let timeline = catalog.timelines_of("alice")[0].0.id.clone();
|
||||
drop(catalog);
|
||||
let host = rig.timelines.host(&timeline).await.unwrap();
|
||||
assert_eq!(host.world.snapshot().await.unwrap().phase, WorldPhase::Draft);
|
||||
}
|
||||
}
|
||||
482
crates/ghostlight-dungeon/src/catalog.rs
Normal file
482
crates/ghostlight-dungeon/src/catalog.rs
Normal file
|
|
@ -0,0 +1,482 @@
|
|||
//! The catalog: which worlds exist, which timelines belong to them, and where
|
||||
//! each player is standing.
|
||||
//!
|
||||
//! The kernel owns world state and `PlayTable` owns turns; this store owns only
|
||||
//! the rows that say which store belongs to whom. One row holds all three
|
||||
//! tables, written by compare-and-swap, so a world record and its root
|
||||
//! timeline can never be seen apart.
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
use uuid::Uuid;
|
||||
|
||||
const STORE_TYPE: &str = "ghostlight.dungeon_catalog.v1";
|
||||
const STORE_KEY: &str = "primary";
|
||||
|
||||
/// A world and who may play it. `snapshot_id` is the vault snapshot the world
|
||||
/// was seeded from, `None` for a world that began unseeded.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct WorldRecord {
|
||||
pub(crate) world_id: String,
|
||||
pub(crate) title: String,
|
||||
pub(crate) owner: String,
|
||||
pub(crate) snapshot_id: Option<String>,
|
||||
pub(crate) created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// One playable line of a world. A fork records `(parent timeline, commit)`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Timeline {
|
||||
pub(crate) id: String,
|
||||
pub(crate) world_id: String,
|
||||
pub(crate) parent: Option<(String, String)>,
|
||||
}
|
||||
|
||||
/// A player's one pointer: which timeline they are in, and where they mean to
|
||||
/// go next. Keyed by principal, so every device of one player reads the same.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct PlayerSession {
|
||||
pub(crate) principal: String,
|
||||
pub(crate) timeline: Option<String>,
|
||||
pub(crate) destination: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
/// A Dungeon account: minted here, linked to the external identities Heimdall
|
||||
/// authenticates. Heimdall holds no accounts.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Account {
|
||||
pub(crate) account_id: String,
|
||||
pub(crate) identities: Vec<String>,
|
||||
pub(crate) created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Why a sign-in got no account.
|
||||
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub(crate) enum SignInRefusal {
|
||||
#[error("this sign-in has no account and no live invite")]
|
||||
NoInvite,
|
||||
}
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct CatalogState {
|
||||
worlds: BTreeMap<String, WorldRecord>,
|
||||
timelines: BTreeMap<String, Timeline>,
|
||||
players: BTreeMap<String, PlayerSession>,
|
||||
accounts: BTreeMap<String, Account>,
|
||||
/// External identity (a Heimdall account id) to Dungeon account id.
|
||||
identities: BTreeMap<String, String>,
|
||||
/// Unconsumed invites: sha256 of the token to its expiry. Only the hash is kept.
|
||||
invites: BTreeMap<String, DateTime<Utc>>,
|
||||
}
|
||||
|
||||
pub(crate) struct Catalog {
|
||||
store: OwnedRedbMessagePackBackingStore,
|
||||
row: CultCacheEnvelope,
|
||||
state: CatalogState,
|
||||
}
|
||||
|
||||
/// `timeline:<uuid>`: the only shape that names a timeline, so the id can be a
|
||||
/// directory name without ever carrying a path.
|
||||
pub(crate) fn timeline_id(uuid: Uuid) -> String {
|
||||
format!("timeline:{}", uuid.hyphenated())
|
||||
}
|
||||
|
||||
/// The directory name a timeline id maps to, or `None` for anything that is
|
||||
/// not exactly `timeline:<canonical uuid>`.
|
||||
pub(crate) fn timeline_directory_name(id: &str) -> Option<String> {
|
||||
let uuid = Uuid::parse_str(id.strip_prefix("timeline:")?).ok()?;
|
||||
(timeline_id(uuid) == id).then(|| uuid.hyphenated().to_string())
|
||||
}
|
||||
|
||||
impl Catalog {
|
||||
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
|
||||
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
|
||||
store
|
||||
.validate_path_identity()
|
||||
.context("catalog store path identity is invalid")?;
|
||||
let rows = store.pull_all()?;
|
||||
let (row, state) = match rows.as_slice() {
|
||||
[] => {
|
||||
let state = CatalogState::default();
|
||||
let row = envelope(&state)?;
|
||||
ensure!(
|
||||
store.compare_and_swap_batch(&[], vec![row.clone()])?,
|
||||
"catalog store changed during initialization"
|
||||
);
|
||||
(row, state)
|
||||
}
|
||||
[row]
|
||||
if row.r#type == STORE_TYPE
|
||||
&& row.key == STORE_KEY
|
||||
&& row.schema_id.as_deref() == Some(STORE_TYPE) =>
|
||||
{
|
||||
let state: CatalogState =
|
||||
rmp_serde::from_slice(&row.payload).context("catalog state is corrupt")?;
|
||||
ensure!(
|
||||
rmp_serde::to_vec_named(&state)? == row.payload,
|
||||
"catalog state is not canonical"
|
||||
);
|
||||
(row.clone(), state)
|
||||
}
|
||||
_ => bail!("catalog store contains foreign records"),
|
||||
};
|
||||
Ok(Self { store, row, state })
|
||||
}
|
||||
|
||||
pub(crate) fn validate_custody(&self) -> anyhow::Result<()> {
|
||||
self.store
|
||||
.validate_path_identity()
|
||||
.context("catalog store path identity changed")
|
||||
}
|
||||
|
||||
fn commit(&mut self, next: CatalogState) -> anyhow::Result<()> {
|
||||
let next_row = envelope(&next)?;
|
||||
let swapped = self
|
||||
.store
|
||||
.compare_and_swap_batch(std::slice::from_ref(&self.row), vec![next_row.clone()]);
|
||||
ensure!(
|
||||
matches!(swapped, Ok(true)),
|
||||
"catalog commit outcome is uncertain; sole ownership was lost"
|
||||
);
|
||||
self.row = next_row;
|
||||
self.state = next;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The one function that makes a timeline. Begin passes the new world's
|
||||
/// record beside its root timeline; a fork passes `None` and a parent. The
|
||||
/// player's pointer moves to the new timeline in the same write.
|
||||
pub(crate) fn mint_timeline(
|
||||
&mut self,
|
||||
new_world: Option<WorldRecord>,
|
||||
timeline: Timeline,
|
||||
) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
timeline_directory_name(&timeline.id).is_some(),
|
||||
"timeline id is not canonical"
|
||||
);
|
||||
ensure!(
|
||||
!self.state.timelines.contains_key(&timeline.id),
|
||||
"timeline already exists"
|
||||
);
|
||||
let mut next = self.state.clone();
|
||||
let owner = match new_world {
|
||||
Some(record) => {
|
||||
ensure!(
|
||||
record.world_id == timeline.world_id && timeline.parent.is_none(),
|
||||
"a new world's first timeline is its root"
|
||||
);
|
||||
ensure!(
|
||||
!next.worlds.contains_key(&record.world_id),
|
||||
"world record already exists"
|
||||
);
|
||||
let owner = record.owner.clone();
|
||||
next.worlds.insert(record.world_id.clone(), record);
|
||||
owner
|
||||
}
|
||||
None => {
|
||||
let (parent, _) = timeline
|
||||
.parent
|
||||
.as_ref()
|
||||
.context("a timeline in an existing world names its parent")?;
|
||||
let parent = next.timelines.get(parent).context("parent timeline is unknown")?;
|
||||
ensure!(parent.world_id == timeline.world_id, "fork crosses worlds");
|
||||
next.worlds
|
||||
.get(&timeline.world_id)
|
||||
.context("world record is unknown")?
|
||||
.owner
|
||||
.clone()
|
||||
}
|
||||
};
|
||||
let player = next
|
||||
.players
|
||||
.entry(owner.clone())
|
||||
.or_insert_with(|| PlayerSession {
|
||||
principal: owner,
|
||||
timeline: None,
|
||||
destination: None,
|
||||
});
|
||||
player.timeline = Some(timeline.id.clone());
|
||||
next.timelines.insert(timeline.id.clone(), timeline);
|
||||
self.commit(next)
|
||||
}
|
||||
|
||||
/// Mints a single-use invite and returns its token, the only time it is
|
||||
/// visible. The catalog keeps its hash and expiry.
|
||||
pub(crate) fn mint_invite(&mut self, now: DateTime<Utc>, ttl: chrono::Duration) -> anyhow::Result<String> {
|
||||
let token = format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple());
|
||||
let mut next = self.state.clone();
|
||||
next.invites.retain(|_, expires| *expires > now);
|
||||
next.invites.insert(token_hash(&token), now + ttl);
|
||||
self.commit(next)?;
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// The account an authenticated external identity lands on. A known
|
||||
/// identity reaches its account, on any device. An unknown one needs a
|
||||
/// live invite, which is consumed in the same write that creates the
|
||||
/// account and binds the identity. No account and no live invite: refused,
|
||||
/// never enrolled. Returns the account's principal key, the identity the
|
||||
/// account was first created from.
|
||||
pub(crate) fn sign_in(
|
||||
&mut self,
|
||||
identity: &str,
|
||||
invite: Option<&str>,
|
||||
now: DateTime<Utc>,
|
||||
) -> anyhow::Result<Result<String, SignInRefusal>> {
|
||||
if let Some(account) = self.state.identities.get(identity) {
|
||||
let account = &self.state.accounts[account];
|
||||
return Ok(Ok(account.identities[0].clone()));
|
||||
}
|
||||
let Some(hash) = invite.map(token_hash) else {
|
||||
return Ok(Err(SignInRefusal::NoInvite));
|
||||
};
|
||||
match self.state.invites.get(&hash) {
|
||||
Some(expires) if *expires > now => {}
|
||||
_ => return Ok(Err(SignInRefusal::NoInvite)),
|
||||
}
|
||||
let mut next = self.state.clone();
|
||||
next.invites.remove(&hash);
|
||||
next.invites.retain(|_, expires| *expires > now);
|
||||
let account_id = format!("account:{}", Uuid::new_v4());
|
||||
next.identities.insert(identity.to_owned(), account_id.clone());
|
||||
next.accounts.insert(
|
||||
account_id.clone(),
|
||||
Account {
|
||||
account_id,
|
||||
identities: vec![identity.to_owned()],
|
||||
created_at: now,
|
||||
},
|
||||
);
|
||||
self.commit(next)?;
|
||||
Ok(Ok(identity.to_owned()))
|
||||
}
|
||||
|
||||
pub(crate) fn timeline(&self, id: &str) -> Option<&Timeline> {
|
||||
self.state.timelines.get(id)
|
||||
}
|
||||
|
||||
pub(crate) fn world(&self, world_id: &str) -> Option<&WorldRecord> {
|
||||
self.state.worlds.get(world_id)
|
||||
}
|
||||
|
||||
/// The timeline and its world, only if `principal` owns the world.
|
||||
pub(crate) fn owned_timeline(
|
||||
&self,
|
||||
principal: &str,
|
||||
id: &str,
|
||||
) -> Option<(&Timeline, &WorldRecord)> {
|
||||
let timeline = self.state.timelines.get(id)?;
|
||||
let world = self.state.worlds.get(&timeline.world_id)?;
|
||||
(world.owner == principal).then_some((timeline, world))
|
||||
}
|
||||
|
||||
pub(crate) fn timelines_of(&self, principal: &str) -> Vec<(&Timeline, &WorldRecord)> {
|
||||
self.state
|
||||
.timelines
|
||||
.values()
|
||||
.filter_map(|timeline| {
|
||||
let world = self.state.worlds.get(&timeline.world_id)?;
|
||||
(world.owner == principal).then_some((timeline, world))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn player(&self, principal: &str) -> Option<&PlayerSession> {
|
||||
self.state.players.get(principal)
|
||||
}
|
||||
|
||||
/// Moves the player's pointer to a timeline they own.
|
||||
pub(crate) fn set_current(&mut self, principal: &str, timeline: &str) -> anyhow::Result<()> {
|
||||
ensure!(
|
||||
self.owned_timeline(principal, timeline).is_some(),
|
||||
"that timeline is not this player's"
|
||||
);
|
||||
let mut next = self.state.clone();
|
||||
next.players
|
||||
.entry(principal.to_owned())
|
||||
.or_insert_with(|| PlayerSession {
|
||||
principal: principal.to_owned(),
|
||||
timeline: None,
|
||||
destination: None,
|
||||
})
|
||||
.timeline = Some(timeline.to_owned());
|
||||
self.commit(next)
|
||||
}
|
||||
}
|
||||
|
||||
fn envelope(state: &CatalogState) -> anyhow::Result<CultCacheEnvelope> {
|
||||
Ok(CultCacheEnvelope {
|
||||
key: STORE_KEY.into(),
|
||||
r#type: STORE_TYPE.into(),
|
||||
payload: rmp_serde::to_vec_named(state)?,
|
||||
stored_at: Utc::now().to_rfc3339(),
|
||||
schema_id: Some(STORE_TYPE.into()),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn record(world: &str, owner: &str) -> WorldRecord {
|
||||
WorldRecord {
|
||||
world_id: world.into(),
|
||||
title: "t".into(),
|
||||
owner: owner.into(),
|
||||
snapshot_id: Some("vault-snapshot:abc".into()),
|
||||
created_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn root(world: &str) -> Timeline {
|
||||
Timeline {
|
||||
id: timeline_id(Uuid::new_v4()),
|
||||
world_id: world.into(),
|
||||
parent: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeline_id_is_a_directory_name_or_nothing() {
|
||||
let good = timeline_id(Uuid::new_v4());
|
||||
assert!(timeline_directory_name(&good).is_some());
|
||||
for bad in [
|
||||
"timeline:../../etc",
|
||||
"timeline:",
|
||||
"../timeline:00000000-0000-4000-8000-000000000000",
|
||||
"timeline:00000000-0000-4000-8000-000000000000/..",
|
||||
"timeline:00000000000040008000000000000000",
|
||||
"timeline:00000000-0000-4000-8000-00000000000A",
|
||||
] {
|
||||
assert!(timeline_directory_name(bad).is_none(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restart_reads_back_what_begin_wrote() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("catalog.cc");
|
||||
let line = root("w1");
|
||||
{
|
||||
let mut catalog = Catalog::open(&path).unwrap();
|
||||
catalog.mint_timeline(Some(record("w1", "alice")), line.clone()).unwrap();
|
||||
}
|
||||
let catalog = Catalog::open(&path).unwrap();
|
||||
assert_eq!(catalog.timeline(&line.id), Some(&line));
|
||||
assert_eq!(catalog.world("w1").unwrap().snapshot_id.as_deref(), Some("vault-snapshot:abc"));
|
||||
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(line.id.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_owner_reaches_a_timeline() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
|
||||
let line = root("w1");
|
||||
catalog.mint_timeline(Some(record("w1", "alice")), line.clone()).unwrap();
|
||||
assert!(catalog.owned_timeline("alice", &line.id).is_some());
|
||||
assert!(catalog.owned_timeline("mallory", &line.id).is_none());
|
||||
assert!(catalog.timelines_of("mallory").is_empty());
|
||||
assert!(catalog.set_current("mallory", &line.id).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fork_is_minted_by_the_same_function_and_must_name_a_real_parent() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
|
||||
let first = root("w1");
|
||||
catalog.mint_timeline(Some(record("w1", "alice")), first.clone()).unwrap();
|
||||
let fork = Timeline {
|
||||
id: timeline_id(Uuid::new_v4()),
|
||||
world_id: "w1".into(),
|
||||
parent: Some((first.id.clone(), "commit-1".into())),
|
||||
};
|
||||
catalog.mint_timeline(None, fork.clone()).unwrap();
|
||||
assert_eq!(catalog.player("alice").unwrap().timeline.as_deref(), Some(fork.id.as_str()));
|
||||
let orphan = Timeline {
|
||||
id: timeline_id(Uuid::new_v4()),
|
||||
world_id: "w1".into(),
|
||||
parent: Some(("timeline:00000000-0000-4000-8000-000000000000".into(), "c".into())),
|
||||
};
|
||||
assert!(catalog.mint_timeline(None, orphan).is_err());
|
||||
assert!(catalog.mint_timeline(None, root("w1")).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn token_hash(token: &str) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
format!("{:x}", Sha256::digest(token.as_bytes()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sign_in_tests {
|
||||
use super::*;
|
||||
use chrono::Duration;
|
||||
|
||||
fn catalog() -> (tempfile::TempDir, Catalog) {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let catalog = Catalog::open(directory.path().join("catalog.cc")).unwrap();
|
||||
(directory, catalog)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_invite_is_single_use() {
|
||||
let (_d, mut catalog) = catalog();
|
||||
let now = Utc::now();
|
||||
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||
assert!(catalog.sign_in("google:deru", Some(&token), now).unwrap().is_ok());
|
||||
// The same invite for a second, different identity is spent.
|
||||
assert_eq!(
|
||||
catalog.sign_in("google:other", Some(&token), now).unwrap(),
|
||||
Err(SignInRefusal::NoInvite)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_expired_invite_is_refused() {
|
||||
let (_d, mut catalog) = catalog();
|
||||
let now = Utc::now();
|
||||
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||
let later = now + Duration::hours(2);
|
||||
assert_eq!(
|
||||
catalog.sign_in("google:deru", Some(&token), later).unwrap(),
|
||||
Err(SignInRefusal::NoInvite)
|
||||
);
|
||||
assert!(catalog.state.accounts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_account_and_no_invite_is_refused_and_enrols_nobody() {
|
||||
let (_d, mut catalog) = catalog();
|
||||
let now = Utc::now();
|
||||
assert_eq!(catalog.sign_in("google:deru", None, now).unwrap(), Err(SignInRefusal::NoInvite));
|
||||
assert_eq!(
|
||||
catalog.sign_in("google:deru", Some("not-a-token"), now).unwrap(),
|
||||
Err(SignInRefusal::NoInvite)
|
||||
);
|
||||
assert!(catalog.state.accounts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_identity_on_a_second_device_lands_on_the_same_account_without_an_invite() {
|
||||
let (directory, mut catalog) = catalog();
|
||||
let now = Utc::now();
|
||||
let token = catalog.mint_invite(now, Duration::hours(1)).unwrap();
|
||||
let first = catalog.sign_in("google:deru", Some(&token), now).unwrap().unwrap();
|
||||
let second = catalog.sign_in("google:deru", None, now).unwrap().unwrap();
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(catalog.state.accounts.len(), 1);
|
||||
// And it survives a restart.
|
||||
drop(catalog);
|
||||
let mut reopened = Catalog::open(directory.path().join("catalog.cc")).unwrap();
|
||||
assert_eq!(reopened.sign_in("google:deru", None, now).unwrap().unwrap(), first);
|
||||
}
|
||||
}
|
||||
1678
crates/ghostlight-dungeon/src/heimdall.rs
Normal file
1678
crates/ghostlight-dungeon/src/heimdall.rs
Normal file
File diff suppressed because it is too large
Load diff
1831
crates/ghostlight-dungeon/src/idunn_health.rs
Normal file
1831
crates/ghostlight-dungeon/src/idunn_health.rs
Normal file
File diff suppressed because it is too large
Load diff
25
crates/ghostlight-dungeon/src/main.rs
Normal file
25
crates/ghostlight-dungeon/src/main.rs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
mod api;
|
||||
mod app_session;
|
||||
mod begin;
|
||||
mod catalog;
|
||||
mod heimdall;
|
||||
mod idunn_health;
|
||||
mod play;
|
||||
mod runtime;
|
||||
mod session_refresh;
|
||||
mod state_layout;
|
||||
mod timelines;
|
||||
|
||||
use anyhow::bail;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args = std::env::args_os().skip(1).collect::<Vec<_>>();
|
||||
let state_root = match args.as_slice() {
|
||||
[flag, path] if flag == "--state-root" => Some(PathBuf::from(path)),
|
||||
[] => None,
|
||||
_ => bail!("usage: ghostlight-dungeon [--state-root PATH]"),
|
||||
};
|
||||
runtime::run(state_root).await
|
||||
}
|
||||
11905
crates/ghostlight-dungeon/src/play.rs
Normal file
11905
crates/ghostlight-dungeon/src/play.rs
Normal file
File diff suppressed because it is too large
Load diff
665
crates/ghostlight-dungeon/src/runtime.rs
Normal file
665
crates/ghostlight-dungeon/src/runtime.rs
Normal file
|
|
@ -0,0 +1,665 @@
|
|||
//! One-process runtime: admission, shared inference, the catalog and the
|
||||
//! timeline registry, served over one router.
|
||||
|
||||
use crate::{
|
||||
api,
|
||||
app_session::AppSessionOwner,
|
||||
begin::{NoVaults, Vaults},
|
||||
catalog::Catalog,
|
||||
heimdall::HeimdallClient,
|
||||
idunn_health::{
|
||||
IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT, ProcessWriteLeaseGuard, RuntimePresencePublisher,
|
||||
TARGET as GHOSTLIGHT_TARGET,
|
||||
},
|
||||
session_refresh::run_refresh_loop,
|
||||
state_layout::{admitted_runtime_root, prepare_admitted_state_layout},
|
||||
timelines::{Shared, Timelines},
|
||||
};
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::Bytes,
|
||||
extract::{ConnectInfo, DefaultBodyLimit, State},
|
||||
http::{HeaderMap, HeaderValue, StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use chrono::Utc;
|
||||
use cultnet_rs::{
|
||||
CultNetMessage, CultNetWireContract, GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA,
|
||||
decode_cultnet_message_from_slice, encode_cultnet_message_to_vec,
|
||||
};
|
||||
use ghostlight::{
|
||||
ConnectorBinding, ControllerModels, ControllerWorkCustody, InferencePort, open_inference,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
fs,
|
||||
net::SocketAddr,
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::{Mutex, Semaphore, mpsc};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
const CULTNET_SNAPSHOT_BODY_LIMIT: usize = 16 * 1024;
|
||||
const CONNECTOR_ADDRESS_ENVIRONMENT: &str = "GHOSTLIGHT_CONNECTOR_ADDR";
|
||||
const CONNECTOR_KEY_CREDENTIAL: &str = "connector-key";
|
||||
const CONNECTOR_CALLER: &str = "ghostlight";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RuntimeHealthOwner {
|
||||
publisher: Arc<Mutex<RuntimePresencePublisher>>,
|
||||
write_lease: Arc<ProcessWriteLeaseGuard>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AppState {
|
||||
pub(crate) catalog: Arc<Mutex<Catalog>>,
|
||||
pub(crate) timelines: Arc<Timelines>,
|
||||
pub(crate) vaults: Arc<dyn Vaults>,
|
||||
pub(crate) sessions: Arc<Mutex<AppSessionOwner>>,
|
||||
pub(crate) heimdall: Arc<HeimdallClient>,
|
||||
pub(crate) runtime_id: String,
|
||||
pub(crate) runtime_health: Option<RuntimeHealthOwner>,
|
||||
pub(crate) fatal: mpsc::UnboundedSender<String>,
|
||||
}
|
||||
|
||||
struct ProductionAdmission {
|
||||
health: RuntimePresencePublisher,
|
||||
write_lease: ProcessWriteLeaseGuard,
|
||||
}
|
||||
|
||||
/// The connector binding the Dungeon opens its one inference port with. The
|
||||
/// key is read here and nowhere else, from the systemd credential directory,
|
||||
/// and only its path is handed on.
|
||||
fn connector_binding() -> anyhow::Result<ConnectorBinding> {
|
||||
let endpoint = std::env::var(CONNECTOR_ADDRESS_ENVIRONMENT)
|
||||
.with_context(|| format!("{CONNECTOR_ADDRESS_ENVIRONMENT} is required"))?
|
||||
.parse()
|
||||
.with_context(|| format!("{CONNECTOR_ADDRESS_ENVIRONMENT} is not a socket address"))?;
|
||||
let credentials =
|
||||
std::env::var_os("CREDENTIALS_DIRECTORY").context("CREDENTIALS_DIRECTORY is required")?;
|
||||
Ok(ConnectorBinding {
|
||||
endpoint,
|
||||
key_path: PathBuf::from(credentials).join(CONNECTOR_KEY_CREDENTIAL),
|
||||
caller_runtime_id: CONNECTOR_CALLER.into(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The model each lane runs on, from env with the tiered defaults.
|
||||
fn lane_models() -> (ControllerModels, String) {
|
||||
let lane = |name: &str, default: &str| std::env::var(name).unwrap_or_else(|_| default.into());
|
||||
(
|
||||
ControllerModels {
|
||||
projector: lane("GHOSTLIGHT_CONTROLLER_PROJECTOR_MODEL", "claude-sonnet-5-5"),
|
||||
persona: lane("GHOSTLIGHT_CONTROLLER_PERSONA_MODEL", "claude-sonnet-5-5"),
|
||||
interpreter: lane("GHOSTLIGHT_CONTROLLER_INTERPRETER_MODEL", "claude-haiku-5-5"),
|
||||
operational_agent: lane("GHOSTLIGHT_CONTROLLER_OPERATIONAL_MODEL", "claude-haiku-5-5"),
|
||||
elaborator: lane("GHOSTLIGHT_CONTROLLER_ELABORATOR_MODEL", "claude-sonnet-5-5"),
|
||||
},
|
||||
lane("GHOSTLIGHT_PLAY_MODEL", "claude-sonnet-5-5"),
|
||||
)
|
||||
}
|
||||
|
||||
/// The one routed inference port every timeline and lane shares.
|
||||
fn open_shared() -> anyhow::Result<Shared> {
|
||||
let (models, play_model) = lane_models();
|
||||
let mut all: Vec<&str> = models.each().to_vec();
|
||||
all.push(&play_model);
|
||||
let inference: Arc<dyn InferencePort> =
|
||||
open_inference(Some(connector_binding()?), None, None, None, &all)?;
|
||||
Ok(Shared {
|
||||
inference,
|
||||
models,
|
||||
play_model,
|
||||
permits: Arc::new(Semaphore::new(configured_controller_concurrency())),
|
||||
})
|
||||
}
|
||||
|
||||
/// Sized to the connector's per-caller quota. `Capacity` and `InFlight`
|
||||
/// refusals are retryable faults, so a pool above that quota degrades to retry.
|
||||
fn configured_controller_concurrency() -> usize {
|
||||
std::env::var("GHOSTLIGHT_CONTROLLER_MAX_CONCURRENT")
|
||||
.ok()
|
||||
.and_then(|value| value.trim().parse::<usize>().ok())
|
||||
.filter(|value| *value >= 1)
|
||||
.unwrap_or(4)
|
||||
}
|
||||
|
||||
pub(crate) fn service_router(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.route("/health", get(health))
|
||||
.route(
|
||||
"/cultnet/snapshot",
|
||||
post(cultnet_snapshot).layer(DefaultBodyLimit::max(CULTNET_SNAPSHOT_BODY_LIMIT)),
|
||||
)
|
||||
.merge(api::router())
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
pub(crate) async fn run(state_root_binding: Option<PathBuf>) -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(EnvFilter::from_default_env())
|
||||
.init();
|
||||
let runtime_root = admitted_runtime_root(state_root_binding)?;
|
||||
let service_root = runtime_root.join("service");
|
||||
// The bound socket is service observation, not configuration. Retain it
|
||||
// unopened to application traffic while Warming waits for Idunn's lease.
|
||||
let requested_address = candidate_bind()?;
|
||||
let listener = tokio::net::TcpListener::bind(requested_address).await?;
|
||||
let bound_address = listener.local_addr()?;
|
||||
let (fatal, mut fatal_events) = mpsc::unbounded_channel();
|
||||
let production_admission = initialize_production_admission(bound_address).await?;
|
||||
let dependency_bindings = production_admission
|
||||
.as_ref()
|
||||
.map(|admission| admission.health.dependency_bindings().clone());
|
||||
let runtime_id = match &production_admission {
|
||||
Some(admission) => admission.health.runtime_id().to_owned(),
|
||||
None => std::env::var("GHOSTLIGHT_RUNTIME_ID")
|
||||
.context("GHOSTLIGHT_RUNTIME_ID is required outside managed runtime")?,
|
||||
};
|
||||
if runtime_id.is_empty() || runtime_id.trim() != runtime_id {
|
||||
bail!("GHOSTLIGHT_RUNTIME_ID must be a canonical non-empty identity");
|
||||
}
|
||||
|
||||
// Production may bind but not serve its candidate socket, then publish
|
||||
// Warming. Catalog, session and timeline state stay unopened until Idunn
|
||||
// grants the lease bound to that exact observed process.
|
||||
let mut write_lease_guard = None;
|
||||
let mut idunn_health = match production_admission {
|
||||
Some(ProductionAdmission { health, write_lease }) => {
|
||||
write_lease.require_current()?;
|
||||
write_lease_guard = Some(write_lease);
|
||||
Some(health)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
require_no_runtime_custody_failure(&mut fatal_events)?;
|
||||
require_current_write_lease(write_lease_guard.as_ref())?;
|
||||
if write_lease_guard.is_none() {
|
||||
fs::create_dir_all(&runtime_root)?;
|
||||
}
|
||||
prepare_admitted_state_layout(&runtime_root)?;
|
||||
require_current_write_lease(write_lease_guard.as_ref())?;
|
||||
let catalog = Catalog::open(runtime_root.join("catalog.cc"))?;
|
||||
let shared = open_shared()?;
|
||||
require_no_runtime_custody_failure(&mut fatal_events)?;
|
||||
let wrapping_key = std::env::var_os("GHOSTLIGHT_SESSION_WRAPPING_KEY_FILE")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| runtime_root.join("secrets/session-wrapping.key"));
|
||||
let sessions = AppSessionOwner::open(service_root.join("app-sessions-v2.cc"), wrapping_key)?;
|
||||
let odin_endpoint = dependency_bindings
|
||||
.as_ref()
|
||||
.map(|bindings| bindings.odin_rudp)
|
||||
.map(Ok)
|
||||
.unwrap_or_else(configured_odin_endpoint)?;
|
||||
// Heimdall is discovered through Odin at use and is not an Idunn
|
||||
// dependency; loopback-only, non-secret-bearing, app-bound envelopes are
|
||||
// enforced regardless.
|
||||
let heimdall = Arc::new(HeimdallClient::from_env(&runtime_id, odin_endpoint, None)?);
|
||||
require_no_runtime_custody_failure(&mut fatal_events)?;
|
||||
let mut state = AppState {
|
||||
catalog: Arc::new(Mutex::new(catalog)),
|
||||
timelines: Arc::new(Timelines::new(runtime_root.clone(), shared, fatal.clone())),
|
||||
vaults: Arc::new(NoVaults),
|
||||
sessions: Arc::new(Mutex::new(sessions)),
|
||||
heimdall,
|
||||
runtime_id,
|
||||
runtime_health: None,
|
||||
fatal,
|
||||
};
|
||||
require_no_runtime_custody_failure(&mut fatal_events)?;
|
||||
require_current_write_lease(write_lease_guard.as_ref())?;
|
||||
canonical_readiness(&state)
|
||||
.await
|
||||
.context("runtime is not ready for active signed health")?;
|
||||
if let Some(publisher) = idunn_health.as_mut() {
|
||||
let write_lease = write_lease_guard
|
||||
.as_ref()
|
||||
.context("production runtime lost its process write lease")?;
|
||||
// Odin refuses Active until it has correlated the lease Idunn just
|
||||
// granted; each call is a fresh sequenced message.
|
||||
retry_until_deadline(
|
||||
|| publisher.publish_active(write_lease),
|
||||
INITIAL_PRESENCE_RETRY_CADENCE,
|
||||
Instant::now() + WRITE_LEASE_WAIT_TIMEOUT,
|
||||
"publishing initial active runtime presence",
|
||||
Instant::now,
|
||||
|duration| tokio::time::sleep(duration),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
require_current_write_lease(write_lease_guard.as_ref())?;
|
||||
state.runtime_health = match (idunn_health, write_lease_guard) {
|
||||
(Some(publisher), Some(write_lease)) => Some(RuntimeHealthOwner {
|
||||
publisher: Arc::new(Mutex::new(publisher)),
|
||||
write_lease: Arc::new(write_lease),
|
||||
}),
|
||||
(None, None) => None,
|
||||
_ => bail!("managed runtime health authority is partial"),
|
||||
};
|
||||
let app = service_router(state.clone());
|
||||
tracing::info!(address = %bound_address, "Ghostlight Dungeon serving");
|
||||
let server = axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
);
|
||||
tokio::select! {
|
||||
result = server => result.context("Ghostlight HTTP server stopped"),
|
||||
result = maintain_runtime_health(state.clone()) => {
|
||||
result?;
|
||||
bail!("runtime readiness owner stopped while the daemon was serving")
|
||||
}
|
||||
result = run_refresh_loop(&state.sessions, state.heimdall.as_ref()) => {
|
||||
result?;
|
||||
bail!("app-session refresh owner stopped while the daemon was serving")
|
||||
}
|
||||
detail = fatal_events.recv() => {
|
||||
bail!(
|
||||
"runtime custody failed: {}",
|
||||
detail.unwrap_or_else(|| "fatal signal channel closed".into())
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn cultnet_snapshot(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<AppState>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
if !peer.ip().is_loopback() {
|
||||
return StatusCode::FORBIDDEN.into_response();
|
||||
}
|
||||
if headers.get(header::CONTENT_TYPE) != Some(&HeaderValue::from_static("application/msgpack")) {
|
||||
return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
|
||||
}
|
||||
let message_id = match exact_route_observation_message_id(&body) {
|
||||
Ok(message_id) => message_id,
|
||||
Err(_) => return StatusCode::BAD_REQUEST.into_response(),
|
||||
};
|
||||
let Some(owner) = state.runtime_health.clone() else {
|
||||
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||
};
|
||||
|
||||
// Hold the one publisher across readiness observation and signing so a
|
||||
// periodic publication cannot age the checked state before this challenge
|
||||
// is bound into the signed record.
|
||||
let write_lease = owner.write_lease.clone();
|
||||
let mut publisher = owner.publisher.clone().lock_owned().await;
|
||||
let ready = canonical_readiness(&state).await.is_ok();
|
||||
let response = tokio::task::spawn_blocking(move || {
|
||||
let response = publisher.route_observation(&message_id, ready, &write_lease)?;
|
||||
encode_cultnet_message_to_vec(&response, CultNetWireContract::CultNetSchemaV0)
|
||||
})
|
||||
.await;
|
||||
let Ok(Ok(response)) = response else {
|
||||
return StatusCode::SERVICE_UNAVAILABLE.into_response();
|
||||
};
|
||||
(
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, "application/msgpack")],
|
||||
response,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn exact_route_observation_message_id(body: &[u8]) -> anyhow::Result<String> {
|
||||
let request = decode_cultnet_message_from_slice(body, CultNetWireContract::CultNetSchemaV0)
|
||||
.context("decoding route-observation request")?;
|
||||
ensure!(
|
||||
encode_cultnet_message_to_vec(&request, CultNetWireContract::CultNetSchemaV0)? == body,
|
||||
"route-observation request is not canonical MessagePack"
|
||||
);
|
||||
let CultNetMessage::SnapshotRequest {
|
||||
message_id,
|
||||
schema_ids,
|
||||
record_keys,
|
||||
} = request
|
||||
else {
|
||||
bail!("route-observation request is not a snapshot request");
|
||||
};
|
||||
ensure!(
|
||||
!message_id.is_empty(),
|
||||
"route-observation message id is empty"
|
||||
);
|
||||
ensure!(
|
||||
matches!(
|
||||
schema_ids.as_deref(),
|
||||
Some([schema_id]) if schema_id == GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA
|
||||
) && matches!(
|
||||
record_keys.as_deref(),
|
||||
Some([record_key]) if record_key == GHOSTLIGHT_TARGET
|
||||
),
|
||||
"route-observation request is not the exact Ghostlight presence record"
|
||||
);
|
||||
let detail = format!("route-observation:{message_id}");
|
||||
ensure!(
|
||||
detail.len() <= 512 && !detail.chars().any(char::is_control),
|
||||
"route-observation message id cannot be signed canonically"
|
||||
);
|
||||
Ok(message_id)
|
||||
}
|
||||
|
||||
async fn health(State(state): State<AppState>) -> Response {
|
||||
match runtime_readiness(&state).await {
|
||||
Ok(health) => Json(health).into_response(),
|
||||
Err(error) => (
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(json!({"status":"failed","message":error.to_string()})),
|
||||
)
|
||||
.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The custody every response rests on: the catalog and the session store.
|
||||
async fn canonical_readiness(state: &AppState) -> anyhow::Result<Value> {
|
||||
state
|
||||
.catalog
|
||||
.lock()
|
||||
.await
|
||||
.validate_custody()
|
||||
.context("catalog is not ready")?;
|
||||
state
|
||||
.sessions
|
||||
.lock()
|
||||
.await
|
||||
.validate_custody()
|
||||
.context("app-session owner is not ready")?;
|
||||
Ok(json!({
|
||||
"schema":"ghostlight.service_health.v3",
|
||||
"status":"ok",
|
||||
"updatedAtUtc":Utc::now().to_rfc3339(),
|
||||
"runtime":state.runtime_id,
|
||||
"commit":option_env!("GHOSTLIGHT_BUILD_COMMIT").unwrap_or("development"),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn runtime_readiness(state: &AppState) -> anyhow::Result<Value> {
|
||||
let mut health = canonical_readiness(state).await?;
|
||||
let opened = state.timelines.opened().await;
|
||||
let mut controller_status = "ok";
|
||||
let mut play_status = "ok".to_owned();
|
||||
for (id, host) in &opened {
|
||||
match tokio::time::timeout(Duration::from_millis(100), host.controllers.custody_probe())
|
||||
.await
|
||||
{
|
||||
Ok(Ok(ControllerWorkCustody::Owned { .. })) => {}
|
||||
Ok(Ok(ControllerWorkCustody::Uncertain { .. })) | Ok(Err(_)) => {
|
||||
controller_status = "degraded";
|
||||
}
|
||||
Err(_) => controller_status = "busy",
|
||||
}
|
||||
// A retired unreadable play row is reported, not hidden.
|
||||
if let Some(sidecar) = host.play.retired_row_sidecar() {
|
||||
play_status = format!("a play-turn row of {id} was retired to {}", sidecar.display());
|
||||
}
|
||||
}
|
||||
if state.timelines.shared().permits.available_permits() == 0 && controller_status == "ok" {
|
||||
controller_status = "active";
|
||||
}
|
||||
health["openTimelines"] = json!(opened.len());
|
||||
health["controllerStatus"] = Value::String(controller_status.into());
|
||||
health["playStatus"] = Value::String(play_status);
|
||||
Ok(health)
|
||||
}
|
||||
|
||||
/// Idunn publishes Expected and starts the unit before it observes the
|
||||
/// running process on a later tick and publishes the activation. Until then,
|
||||
/// Odin refuses every Warming presence this daemon publishes. This is the
|
||||
/// bound both the initial Warming publish retries against and
|
||||
/// `wait_for_write_lease`'s own timeout.
|
||||
const WRITE_LEASE_WAIT_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
/// Matches Muninn's own Warming re-publish cadence while tolerating the same
|
||||
/// activation-publication gap.
|
||||
const INITIAL_PRESENCE_RETRY_CADENCE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Retries `attempt` at `cadence` until it returns `Ok` or `deadline` passes,
|
||||
/// returning the last error once the deadline is reached. `sleep` and `now`
|
||||
/// are seams so the bounded-retry policy is provable without waiting.
|
||||
async fn retry_until_deadline<T, Attempt, Sleep, SleepFut>(
|
||||
mut attempt: Attempt,
|
||||
cadence: Duration,
|
||||
deadline: Instant,
|
||||
what: &str,
|
||||
mut now: impl FnMut() -> Instant,
|
||||
mut sleep: Sleep,
|
||||
) -> anyhow::Result<T>
|
||||
where
|
||||
Attempt: FnMut() -> anyhow::Result<T>,
|
||||
Sleep: FnMut(Duration) -> SleepFut,
|
||||
SleepFut: std::future::Future<Output = ()>,
|
||||
{
|
||||
loop {
|
||||
match attempt() {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "{what} failed; retrying");
|
||||
if now() >= deadline {
|
||||
return Err(error).context(format!("{what} timed out"));
|
||||
}
|
||||
sleep(cadence).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn initialize_production_admission(
|
||||
bound_endpoint: SocketAddr,
|
||||
) -> anyhow::Result<Option<ProductionAdmission>> {
|
||||
let Some(mut publisher) = RuntimePresencePublisher::from_environment(bound_endpoint)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
// Each `publish_warming()` mints a fresh sequence and timestamp, so a
|
||||
// retried publish is a new message Odin evaluates, never a duplicate.
|
||||
let warming = retry_until_deadline(
|
||||
|| publisher.publish_warming(),
|
||||
INITIAL_PRESENCE_RETRY_CADENCE,
|
||||
Instant::now() + WRITE_LEASE_WAIT_TIMEOUT,
|
||||
"publishing initial Warming runtime presence",
|
||||
Instant::now,
|
||||
|duration| tokio::time::sleep(duration),
|
||||
)
|
||||
.await?;
|
||||
let write_lease = publisher
|
||||
.wait_for_write_lease(&warming, WRITE_LEASE_WAIT_TIMEOUT)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"waiting for process lease bound to Warming {}",
|
||||
warming.canonical_sha256()
|
||||
)
|
||||
})?;
|
||||
Ok(Some(ProductionAdmission {
|
||||
health: publisher,
|
||||
write_lease,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn maintain_runtime_health(state: AppState) -> anyhow::Result<()> {
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(10));
|
||||
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
interval.tick().await;
|
||||
canonical_readiness(&state)
|
||||
.await
|
||||
.context("runtime is not ready for signed health")?;
|
||||
let Some(owner) = state.runtime_health.clone() else {
|
||||
continue;
|
||||
};
|
||||
owner
|
||||
.write_lease
|
||||
.require_current()
|
||||
.context("runtime process write lease is not current")?;
|
||||
let mut publisher = owner.publisher.clone().lock_owned().await;
|
||||
let published = tokio::task::spawn_blocking(move || {
|
||||
publisher.republish_active()?;
|
||||
Ok::<(), anyhow::Error>(())
|
||||
})
|
||||
.await;
|
||||
let Ok(result) = published else {
|
||||
tracing::warn!("runtime-presence worker panicked; publication will retry");
|
||||
continue;
|
||||
};
|
||||
if let Err(error) = result {
|
||||
tracing::warn!(%error, "signed runtime-presence publication failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn candidate_bind() -> anyhow::Result<SocketAddr> {
|
||||
match std::env::var(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT) {
|
||||
Ok(value) => value
|
||||
.parse()
|
||||
.context("Idunn candidate bind is not a socket address"),
|
||||
Err(_) => {
|
||||
#[cfg(target_os = "linux")]
|
||||
bail!("{IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT} is mandatory on Linux");
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
return Ok("127.0.0.1:8831".parse()?);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn configured_odin_endpoint() -> anyhow::Result<SocketAddr> {
|
||||
std::env::var("GHOSTLIGHT_ODIN_RUDP")
|
||||
.context("GHOSTLIGHT_ODIN_RUDP is required")?
|
||||
.parse()
|
||||
.context("GHOSTLIGHT_ODIN_RUDP is not a socket address")
|
||||
}
|
||||
|
||||
fn require_current_write_lease(lease: Option<&ProcessWriteLeaseGuard>) -> anyhow::Result<()> {
|
||||
match lease {
|
||||
Some(lease) => lease.require_current(),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_no_runtime_custody_failure(
|
||||
failures: &mut mpsc::UnboundedReceiver<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
match failures.try_recv() {
|
||||
Ok(detail) => bail!("runtime custody failed before serving: {detail}"),
|
||||
Err(mpsc::error::TryRecvError::Empty) => Ok(()),
|
||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||
bail!("runtime custody signal channel closed before serving")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct FakeClock {
|
||||
now: std::cell::Cell<Instant>,
|
||||
}
|
||||
|
||||
impl FakeClock {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
now: std::cell::Cell::new(Instant::now()),
|
||||
}
|
||||
}
|
||||
fn now(&self) -> Instant {
|
||||
self.now.get()
|
||||
}
|
||||
fn advance(&self, by: Duration) {
|
||||
self.now.set(self.now.get() + by);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retry_until_deadline_returns_the_first_accepted_value() {
|
||||
let clock = FakeClock::new();
|
||||
let deadline = clock.now() + Duration::from_secs(120);
|
||||
let mut calls = 0;
|
||||
let result = retry_until_deadline(
|
||||
|| {
|
||||
calls += 1;
|
||||
if calls < 3 {
|
||||
Err(anyhow::anyhow!("refused (attempt {calls})"))
|
||||
} else {
|
||||
Ok(format!("accepted on attempt {calls}"))
|
||||
}
|
||||
},
|
||||
Duration::from_secs(2),
|
||||
deadline,
|
||||
"test publish",
|
||||
|| clock.now(),
|
||||
|cadence| {
|
||||
clock.advance(cadence);
|
||||
std::future::ready(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap(), "accepted on attempt 3");
|
||||
assert_eq!(calls, 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retry_until_deadline_fails_with_the_last_error_after_the_window() {
|
||||
let clock = FakeClock::new();
|
||||
let deadline = clock.now() + Duration::from_secs(10);
|
||||
let mut calls = 0;
|
||||
let result: anyhow::Result<()> = retry_until_deadline(
|
||||
|| {
|
||||
calls += 1;
|
||||
Err(anyhow::anyhow!("refused (attempt {calls})"))
|
||||
},
|
||||
Duration::from_secs(2),
|
||||
deadline,
|
||||
"test publish",
|
||||
|| clock.now(),
|
||||
|cadence| {
|
||||
clock.advance(cadence);
|
||||
std::future::ready(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let error = result.unwrap_err();
|
||||
assert!(format!("{error:#}").contains("test publish timed out"));
|
||||
assert!(format!("{error:#}").contains("refused (attempt"));
|
||||
assert_eq!(calls, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lanes_default_to_the_tiered_claude_models() {
|
||||
let (models, play) = lane_models();
|
||||
assert_eq!(play, "claude-sonnet-5-5");
|
||||
assert_eq!(models.interpreter, "claude-haiku-5-5");
|
||||
assert_eq!(models.operational_agent, "claude-haiku-5-5");
|
||||
assert_eq!(models.persona, "claude-sonnet-5-5");
|
||||
}
|
||||
|
||||
/// The connector key is a credential path, never a value: the binding
|
||||
/// carries the path under CREDENTIALS_DIRECTORY and the caller id, and
|
||||
/// nothing else of it.
|
||||
#[test]
|
||||
fn the_connector_key_is_bound_by_credential_path_only() {
|
||||
// SAFETY: the test sets and clears process env it alone reads.
|
||||
unsafe {
|
||||
std::env::set_var(CONNECTOR_ADDRESS_ENVIRONMENT, "127.0.0.1:7001");
|
||||
std::env::set_var("CREDENTIALS_DIRECTORY", "/run/credentials/ghostlight.service");
|
||||
}
|
||||
let binding = connector_binding().unwrap();
|
||||
assert_eq!(binding.caller_runtime_id, "ghostlight");
|
||||
assert_eq!(
|
||||
binding.key_path,
|
||||
PathBuf::from("/run/credentials/ghostlight.service").join("connector-key")
|
||||
);
|
||||
unsafe {
|
||||
std::env::remove_var("CREDENTIALS_DIRECTORY");
|
||||
}
|
||||
assert!(connector_binding().is_err(), "no credential directory, no binding");
|
||||
unsafe {
|
||||
std::env::remove_var(CONNECTOR_ADDRESS_ENVIRONMENT);
|
||||
}
|
||||
}
|
||||
}
|
||||
618
crates/ghostlight-dungeon/src/session_refresh.rs
Normal file
618
crates/ghostlight-dungeon/src/session_refresh.rs
Normal file
|
|
@ -0,0 +1,618 @@
|
|||
//! The app-session refresh loop: renews Heimdall sessions before they lapse
|
||||
//! and revokes any whose custody changed.
|
||||
|
||||
use crate::{
|
||||
app_session::{AppSessionOwner, RefreshRefusal},
|
||||
heimdall::{self, HeimdallDenied, SessionRefresher, VerificationUnavailable},
|
||||
};
|
||||
use anyhow::Context;
|
||||
use chrono::Utc;
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
const SESSION_REFRESH_PERIOD: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Runs `refresh_due_sessions` once per `SESSION_REFRESH_PERIOD` for as long
|
||||
/// as the daemon serves. The receipts it holds are Heimdall refreshes already
|
||||
/// spent upstream whose verification could not yet be judged.
|
||||
pub(crate) async fn run_refresh_loop(
|
||||
sessions: &Mutex<AppSessionOwner>,
|
||||
heimdall: &impl SessionRefresher,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut interval = tokio::time::interval(SESSION_REFRESH_PERIOD);
|
||||
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut unverified = HashMap::new();
|
||||
loop {
|
||||
interval.tick().await;
|
||||
refresh_due_sessions(sessions, heimdall, &mut unverified).await?;
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass of the refresh loop over every session due for refresh.
|
||||
/// `unverified` holds, per session, a receipt Heimdall issued for a refresh
|
||||
/// that is already spent upstream but whose signing keys could not be
|
||||
/// fetched: the next pass verifies it instead of refreshing again.
|
||||
async fn refresh_due_sessions(
|
||||
sessions: &Mutex<AppSessionOwner>,
|
||||
heimdall: &impl SessionRefresher,
|
||||
unverified: &mut HashMap<String, heimdall::AuthCompletionReceipt>,
|
||||
) -> anyhow::Result<()> {
|
||||
let candidates = sessions
|
||||
.lock()
|
||||
.await
|
||||
.sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2))
|
||||
.context("app-session refresh scan lost custody")?;
|
||||
unverified.retain(|cookie_hash, _| {
|
||||
candidates
|
||||
.iter()
|
||||
.any(|candidate| &candidate.cookie_hash == cookie_hash)
|
||||
});
|
||||
for candidate in candidates {
|
||||
let completion = match unverified.remove(&candidate.cookie_hash) {
|
||||
Some(completion) => completion,
|
||||
None => {
|
||||
let idempotency =
|
||||
crate::app_session::refresh_idempotency_key(&candidate.refresh_claim);
|
||||
match heimdall.refresh(&candidate.refresh_claim, &idempotency).await {
|
||||
Ok(value) => value,
|
||||
Err(error) if error.downcast_ref::<HeimdallDenied>().is_some() => {
|
||||
// Heimdall refused this refresh claim: it can never succeed.
|
||||
tracing::warn!(%error, "Heimdall denied the refresh; revoking the local session");
|
||||
let mut sessions = sessions.lock().await;
|
||||
if let Err(revoke_error) =
|
||||
sessions.revoke_cookie_hash(&candidate.cookie_hash)
|
||||
{
|
||||
return Err(revoke_error)
|
||||
.context("denied Heimdall refresh could not revoke local custody");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Heimdall refresh transport unavailable");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let verified = match heimdall.verify_refresh(completion.clone()).await {
|
||||
Ok(value) => value,
|
||||
Err(error) if error.downcast_ref::<VerificationUnavailable>().is_some() => {
|
||||
// The claim is spent upstream and the receipt may be genuine:
|
||||
// keep it and verify again on the next pass.
|
||||
tracing::warn!(%error, "Heimdall refresh receipt could not be verified yet");
|
||||
unverified.insert(candidate.cookie_hash.clone(), completion);
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "Heimdall refresh receipt was invalid");
|
||||
let mut sessions = sessions.lock().await;
|
||||
if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) {
|
||||
return Err(revoke_error)
|
||||
.context("invalid Heimdall refresh could not revoke local custody");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if verified.heimdall_session_id() != candidate.heimdall_session_id
|
||||
|| crate::app_session::secret_hash(&format!(
|
||||
"heimdall-account:{}",
|
||||
verified.account_id()
|
||||
)) != candidate.account_subject_hash
|
||||
{
|
||||
tracing::warn!("Heimdall refresh changed local session custody");
|
||||
let mut sessions = sessions.lock().await;
|
||||
if let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash) {
|
||||
return Err(revoke_error)
|
||||
.context("changed Heimdall custody could not revoke local session");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut sessions = sessions.lock().await;
|
||||
if let Err(error) =
|
||||
sessions.apply_refresh(&candidate.cookie_hash, candidate.access_revision, verified)
|
||||
{
|
||||
if !sessions.is_healthy() {
|
||||
return Err(error).context("app-session refresh commit lost custody");
|
||||
}
|
||||
tracing::warn!(%error, "local app session refused Heimdall refresh");
|
||||
// The refresh claim is spent upstream, so a receipt that went
|
||||
// backwards leaves nothing to retry. A session that merely moved
|
||||
// is newer state: the next scan decides.
|
||||
if error.downcast_ref::<RefreshRefusal>()
|
||||
== Some(&RefreshRefusal::RevisionWentBackwards)
|
||||
&& let Err(revoke_error) = sessions.revoke_cookie_hash(&candidate.cookie_hash)
|
||||
{
|
||||
return Err(revoke_error)
|
||||
.context("backwards Heimdall refresh could not revoke local session");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Idunn publishes Expected and starts the unit before it observes the
|
||||
/// running process on a later tick and publishes the activation
|
||||
/// (Idunn/src/control_plane.rs). Until that activation exists, Odin refuses
|
||||
|
||||
/// queue and records the claim and idempotency key it was sent.
|
||||
#[cfg(test)]
|
||||
mod refresh_loop_tests {
|
||||
use super::*;
|
||||
use crate::heimdall::{AuthCompletionReceipt, VerificationUnavailable, VerifiedSessionRefresh};
|
||||
use std::{collections::VecDeque, sync::Mutex as StdMutex};
|
||||
|
||||
enum Reply {
|
||||
Deny,
|
||||
Timeout,
|
||||
Receipt { revision: u64, claim: &'static str },
|
||||
/// A receipt for the same claim but another Heimdall session.
|
||||
OtherSession,
|
||||
/// A receipt for the same claim but another account.
|
||||
OtherAccount,
|
||||
}
|
||||
|
||||
/// What `verify_refresh` answers; an empty queue accepts the receipt.
|
||||
enum Verdict {
|
||||
/// The signing keys could not be fetched.
|
||||
Unavailable,
|
||||
/// The receipt positively fails verification.
|
||||
Invalid,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ScriptedHeimdall {
|
||||
replies: StdMutex<VecDeque<Reply>>,
|
||||
verdicts: StdMutex<VecDeque<Verdict>>,
|
||||
verifications: StdMutex<usize>,
|
||||
/// While answering a refresh, apply a newer revision to this store,
|
||||
/// as a concurrent refresh of the same session would.
|
||||
moving: Option<std::sync::Arc<Mutex<AppSessionOwner>>>,
|
||||
pending: StdMutex<Option<VerifiedSessionRefresh>>,
|
||||
calls: StdMutex<Vec<(String, String)>>,
|
||||
/// Verify receipts with this real client, against the access token
|
||||
/// each receipt carries, instead of from the verdict queue.
|
||||
real: Option<(HeimdallClient, String)>,
|
||||
}
|
||||
|
||||
impl ScriptedHeimdall {
|
||||
fn answering(replies: Vec<Reply>) -> Self {
|
||||
Self {
|
||||
replies: StdMutex::new(replies.into()),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn verifying(mut self, verdicts: Vec<Verdict>) -> Self {
|
||||
self.verdicts = StdMutex::new(verdicts.into());
|
||||
self
|
||||
}
|
||||
|
||||
fn verifying_for_real(mut self, client: HeimdallClient, token: String) -> Self {
|
||||
self.real = Some((client, token));
|
||||
self
|
||||
}
|
||||
|
||||
fn verifications(&self) -> usize {
|
||||
*self.verifications.lock().unwrap()
|
||||
}
|
||||
|
||||
fn calls(&self) -> Vec<(String, String)> {
|
||||
self.calls.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SessionRefresher for ScriptedHeimdall {
|
||||
async fn refresh(
|
||||
&self,
|
||||
refresh_token: &str,
|
||||
idempotency_key: &str,
|
||||
) -> anyhow::Result<AuthCompletionReceipt> {
|
||||
self.calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((refresh_token.into(), idempotency_key.into()));
|
||||
if let Some(sessions) = &self.moving {
|
||||
let mut sessions = sessions.lock().await;
|
||||
let candidate = sessions
|
||||
.sessions_due_for_refresh(Utc::now(), chrono::Duration::minutes(2))
|
||||
.unwrap()
|
||||
.remove(0);
|
||||
sessions
|
||||
.apply_refresh(
|
||||
&candidate.cookie_hash,
|
||||
candidate.access_revision,
|
||||
VerifiedSessionRefresh::fixture(
|
||||
"operator-account",
|
||||
"heimdall-session",
|
||||
candidate.access_revision + 1,
|
||||
Utc::now() + chrono::Duration::seconds(90),
|
||||
Utc::now() + chrono::Duration::days(1),
|
||||
"claim-moved",
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
match self.replies.lock().unwrap().pop_front().expect("scripted reply") {
|
||||
Reply::Deny => Err(HeimdallDenied {
|
||||
diagnostics: "Idempotency key was reused".into(),
|
||||
}
|
||||
.into()),
|
||||
Reply::Timeout => bail!("Heimdall private command timed out"),
|
||||
reply @ (Reply::Receipt { .. } | Reply::OtherSession | Reply::OtherAccount) => {
|
||||
let (account, session, revision, claim) = match reply {
|
||||
Reply::OtherSession => ("operator-account", "other-session", 1, "claim-1"),
|
||||
Reply::OtherAccount => ("other-account", "heimdall-session", 1, "claim-1"),
|
||||
Reply::Receipt { revision, claim } => {
|
||||
("operator-account", "heimdall-session", revision, claim)
|
||||
}
|
||||
_ => unreachable!("matched above"),
|
||||
};
|
||||
*self.pending.lock().unwrap() = Some(VerifiedSessionRefresh::fixture(
|
||||
account,
|
||||
session,
|
||||
revision,
|
||||
Utc::now() + chrono::Duration::seconds(90),
|
||||
Utc::now() + chrono::Duration::days(1),
|
||||
claim,
|
||||
));
|
||||
Ok(AuthCompletionReceipt {
|
||||
status: "authenticated".into(),
|
||||
handle: None,
|
||||
error: None,
|
||||
account: None,
|
||||
session: None,
|
||||
access_token: self.real.as_ref().map(|(_, token)| token.clone()),
|
||||
refresh_token: None,
|
||||
refresh: None,
|
||||
shared_capabilities: Vec::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn verify_refresh(
|
||||
&self,
|
||||
completion: AuthCompletionReceipt,
|
||||
) -> anyhow::Result<VerifiedSessionRefresh> {
|
||||
*self.verifications.lock().unwrap() += 1;
|
||||
if let Some((client, _)) = &self.real {
|
||||
return client.verify_refresh(completion).await;
|
||||
}
|
||||
match self.verdicts.lock().unwrap().pop_front() {
|
||||
Some(Verdict::Unavailable) => {
|
||||
Err(VerificationUnavailable::new("timed out").into())
|
||||
}
|
||||
Some(Verdict::Invalid) => bail!("Heimdall access token signature is invalid"),
|
||||
None => Ok(self.pending.lock().unwrap().take().expect("scripted receipt")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A store holding one live session at `revision` whose access expires in
|
||||
/// a minute, so every pass finds it due.
|
||||
fn due_session(
|
||||
revision: u64,
|
||||
) -> (tempfile::TempDir, std::sync::Arc<Mutex<AppSessionOwner>>, String) {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let key = directory.path().join("session.key");
|
||||
std::fs::write(&key, [23_u8; 32]).unwrap();
|
||||
let mut owner = AppSessionOwner::open(directory.path().join("sessions.cc"), &key).unwrap();
|
||||
let cookie = owner
|
||||
.create_session(heimdall::VerifiedSessionAdmission::fixture(
|
||||
"operator-account",
|
||||
"heimdall-session",
|
||||
revision,
|
||||
Utc::now() + chrono::Duration::seconds(60),
|
||||
Utc::now() + chrono::Duration::days(1),
|
||||
"claim-0",
|
||||
))
|
||||
.unwrap();
|
||||
(directory, std::sync::Arc::new(Mutex::new(owner)), cookie)
|
||||
}
|
||||
|
||||
/// One refresh pass with no receipt carried over from an earlier one.
|
||||
async fn pass(sessions: &Mutex<AppSessionOwner>, heimdall: &ScriptedHeimdall) {
|
||||
refresh_due_sessions(sessions, heimdall, &mut HashMap::new())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn is_live(sessions: &Mutex<AppSessionOwner>, cookie: &str) -> bool {
|
||||
sessions
|
||||
.lock()
|
||||
.await
|
||||
.account_for_cookie(cookie, Utc::now())
|
||||
.unwrap()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Captured(std::sync::Arc<StdMutex<Vec<u8>>>);
|
||||
|
||||
impl std::io::Write for Captured {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Captured {
|
||||
type Writer = Captured;
|
||||
|
||||
fn make_writer(&'a self) -> Captured {
|
||||
self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_real_refresh_at_an_equal_revision_is_applied_and_the_session_stays_live() {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![
|
||||
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||
Reply::Timeout,
|
||||
]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(is_live(&sessions, &cookie).await);
|
||||
// The wrapped claim is the receipt's: the next refresh spends it.
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert_eq!(heimdall.calls()[1].0, "claim-1");
|
||||
assert!(is_live(&sessions, &cookie).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_retry_of_the_same_refresh_sends_the_same_key() {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![Reply::Timeout, Reply::Timeout]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
pass(&sessions, &heimdall).await;
|
||||
let calls = heimdall.calls();
|
||||
assert_eq!(calls.len(), 2, "a transport failure leaves the session offered");
|
||||
assert_eq!(calls[0], calls[1]);
|
||||
assert!(is_live(&sessions, &cookie).await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_refresh_after_a_successful_one_sends_a_new_key() {
|
||||
let (_directory, sessions, _cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![
|
||||
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||
Reply::Timeout,
|
||||
]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
pass(&sessions, &heimdall).await;
|
||||
let calls = heimdall.calls();
|
||||
assert_ne!(calls[0].1, calls[1].1);
|
||||
assert!(calls.iter().all(|(claim, key)| !key.contains(claim)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_receipt_with_a_lower_revision_is_refused_and_the_session_revoked() {
|
||||
let (_directory, sessions, cookie) = due_session(2);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![
|
||||
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||
Reply::Timeout,
|
||||
]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(!is_live(&sessions, &cookie).await);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert_eq!(heimdall.calls().len(), 1, "a revoked session is not offered again");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_receipt_for_another_session_or_account_revokes_the_local_session() {
|
||||
for reply in [Reply::OtherSession, Reply::OtherAccount] {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![reply]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(!is_live(&sessions, &cookie).await);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_heimdall_denial_revokes_the_session_and_it_is_not_offered_again() {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![Reply::Deny, Reply::Timeout]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(!is_live(&sessions, &cookie).await);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert_eq!(heimdall.calls().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_local_refusal_logs_the_clause_that_fired() {
|
||||
let (_directory, sessions, _cookie) = due_session(2);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
|
||||
revision: 1,
|
||||
claim: "claim-1",
|
||||
}]);
|
||||
let captured = Captured::default();
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_writer(captured.clone())
|
||||
.with_ansi(false)
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
pass(&sessions, &heimdall).await;
|
||||
let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
|
||||
assert!(
|
||||
logged.contains("refresh receipt revision went backwards"),
|
||||
"{logged}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_receipt_whose_keys_were_unavailable_is_kept_and_applied_on_the_next_pass() {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![
|
||||
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||
Reply::Timeout,
|
||||
])
|
||||
.verifying(vec![Verdict::Unavailable]);
|
||||
let mut unverified = HashMap::new();
|
||||
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||
assert!(is_live(&sessions, &cookie).await, "unavailable keys do not revoke");
|
||||
assert_eq!(unverified.len(), 1);
|
||||
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||
assert_eq!(heimdall.calls().len(), 1, "the spent claim is not sent again");
|
||||
assert_eq!(heimdall.verifications(), 2);
|
||||
assert!(unverified.is_empty(), "an applied receipt is not kept");
|
||||
assert!(is_live(&sessions, &cookie).await);
|
||||
// The applied receipt's claim is the one the next refresh spends.
|
||||
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||
assert_eq!(heimdall.calls()[1].0, "claim-1");
|
||||
assert_eq!(heimdall.verifications(), 2, "the receipt was applied once");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_receipt_that_positively_fails_verification_revokes_and_is_not_kept() {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![
|
||||
Reply::Receipt { revision: 1, claim: "claim-1" },
|
||||
Reply::Timeout,
|
||||
])
|
||||
.verifying(vec![Verdict::Invalid]);
|
||||
let mut unverified = HashMap::new();
|
||||
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||
assert!(!is_live(&sessions, &cookie).await);
|
||||
assert!(unverified.is_empty());
|
||||
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||
assert_eq!(heimdall.calls().len(), 1);
|
||||
assert_eq!(heimdall.verifications(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_kept_receipt_for_a_session_that_is_gone_is_dropped() {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
|
||||
revision: 1,
|
||||
claim: "claim-1",
|
||||
}])
|
||||
.verifying(vec![Verdict::Unavailable]);
|
||||
let mut unverified = HashMap::new();
|
||||
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||
assert_eq!(unverified.len(), 1);
|
||||
let cookie_hash = unverified.keys().next().unwrap().clone();
|
||||
sessions.lock().await.revoke_cookie_hash(&cookie_hash).unwrap();
|
||||
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||
assert!(unverified.is_empty());
|
||||
assert!(!is_live(&sessions, &cookie).await);
|
||||
assert_eq!(heimdall.verifications(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_session_that_moved_while_refreshing_is_not_revoked() {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let mut heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
|
||||
revision: 1,
|
||||
claim: "claim-1",
|
||||
}]);
|
||||
heimdall.moving = Some(sessions.clone());
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(is_live(&sessions, &cookie).await);
|
||||
// The newer state wins: the next refresh spends its claim, not the
|
||||
// stale receipt's.
|
||||
heimdall.moving = None;
|
||||
heimdall.replies.lock().unwrap().push_back(Reply::Timeout);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert_eq!(heimdall.calls()[1].0, "claim-moved");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_receipt_with_a_higher_revision_is_applied() {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![
|
||||
Reply::Receipt { revision: 2, claim: "claim-1" },
|
||||
Reply::Receipt { revision: 1, claim: "claim-2" },
|
||||
]);
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert!(is_live(&sessions, &cookie).await);
|
||||
// The session now sits at revision 2, so a revision-1 receipt is
|
||||
// backwards.
|
||||
pass(&sessions, &heimdall).await;
|
||||
assert_eq!(heimdall.calls()[1].0, "claim-1");
|
||||
assert!(!is_live(&sessions, &cookie).await);
|
||||
}
|
||||
|
||||
/// Lets the loop under test run everything that is ready, without moving
|
||||
/// the paused clock.
|
||||
async fn settle() {
|
||||
for _ in 0..16 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn the_refresh_loop_runs_a_pass_every_sixty_seconds_and_keeps_going() {
|
||||
let (_directory, sessions, _cookie) = due_session(1);
|
||||
let heimdall = ScriptedHeimdall::answering((0..64).map(|_| Reply::Timeout).collect());
|
||||
let observed = async {
|
||||
settle().await;
|
||||
assert_eq!(heimdall.calls().len(), 1, "the first pass runs at once");
|
||||
tokio::time::advance(Duration::from_millis(59_999)).await;
|
||||
settle().await;
|
||||
assert_eq!(heimdall.calls().len(), 1, "no pass before sixty seconds");
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
settle().await;
|
||||
assert_eq!(heimdall.calls().len(), 2, "the second pass at sixty seconds");
|
||||
for passes in 3..=12 {
|
||||
tokio::time::advance(Duration::from_secs(60)).await;
|
||||
settle().await;
|
||||
assert_eq!(heimdall.calls().len(), passes);
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
ran = run_refresh_loop(&sessions, &heimdall) => panic!("the loop returned: {ran:?}"),
|
||||
() = observed => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A refresh receipt verified by the real client against `issuer_url`,
|
||||
/// whose key-set fetch fails. Returns whether the session stayed live,
|
||||
/// how many receipts were kept, and the log the pass wrote.
|
||||
async fn pass_through_real_verification(issuer_url: &str) -> (bool, usize, String) {
|
||||
let (_directory, sessions, cookie) = due_session(1);
|
||||
let client = HeimdallClient::fixture().with_issuer(issuer_url);
|
||||
let token = heimdall::test_issuer::signed_token(issuer_url);
|
||||
let heimdall = ScriptedHeimdall::answering(vec![Reply::Receipt {
|
||||
revision: 1,
|
||||
claim: "claim-1",
|
||||
}])
|
||||
.verifying_for_real(client, token);
|
||||
let captured = Captured::default();
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_writer(captured.clone())
|
||||
.with_ansi(false)
|
||||
.finish();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
let mut unverified = HashMap::new();
|
||||
refresh_due_sessions(&sessions, &heimdall, &mut unverified).await.unwrap();
|
||||
let logged = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
|
||||
(is_live(&sessions, &cookie).await, unverified.len(), logged)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_key_fetch_failure_in_the_real_verification_keeps_the_session_and_the_receipt() {
|
||||
let failing = heimdall::test_issuer::Issuer::start(heimdall::test_issuer::Answer::ServerError)
|
||||
.await;
|
||||
for issuer_url in [heimdall::test_issuer::Issuer::closed_url(), failing.url.clone()] {
|
||||
let (live, kept, logged) = pass_through_real_verification(&issuer_url).await;
|
||||
assert!(live, "{issuer_url}: a key-fetch failure signed the session out");
|
||||
assert_eq!(kept, 1, "{issuer_url}: the spent receipt was not kept");
|
||||
assert!(logged.contains("could not be verified yet"), "{logged}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_unverified_warning_names_the_error_class_and_no_url() {
|
||||
let canary = format!("{}/canary-q7x1", heimdall::test_issuer::Issuer::closed_url());
|
||||
let (_, _, logged) = pass_through_real_verification(&canary).await;
|
||||
assert!(logged.contains("could not connect"), "{logged}");
|
||||
for leaked in [canary.as_str(), "canary-q7x1", "127.0.0.1", "jwks.json"] {
|
||||
assert!(!logged.contains(leaked), "{leaked} leaked into the log: {logged}");
|
||||
}
|
||||
}
|
||||
}
|
||||
200
crates/ghostlight-dungeon/src/state_layout.rs
Normal file
200
crates/ghostlight-dungeon/src/state_layout.rs
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
//! The admitted state layout: every declared state path must be a direct,
|
||||
//! single-linked regular file or directory before anything is written to it.
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
/// The stores one timeline owns, each proved direct before it is opened.
|
||||
pub(crate) const TIMELINE_STORES: [&str; 3] = ["world.cc", "controller-work.cc", "play-turn-v1.cc"];
|
||||
|
||||
fn default_runtime_root() -> PathBuf {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
PathBuf::from(r"F:\GameCult\GhostlightDungeon")
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
PathBuf::from("/var/lib/gamecult/ghostlight-dungeon")
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn admitted_runtime_root(binding: Option<PathBuf>) -> anyhow::Result<PathBuf> {
|
||||
let Some(binding) = binding else {
|
||||
#[cfg(target_os = "linux")]
|
||||
bail!("--state-root is mandatory for the managed Linux runtime");
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
return Ok(default_runtime_root());
|
||||
};
|
||||
ensure!(binding.is_absolute(), "state-root binding is not absolute");
|
||||
let metadata = fs::symlink_metadata(&binding)
|
||||
.with_context(|| format!("inspecting state-root binding {}", binding.display()))?;
|
||||
ensure!(
|
||||
metadata.is_dir() && !metadata.file_type().is_symlink(),
|
||||
"state-root binding is not a direct directory"
|
||||
);
|
||||
let canonical = fs::canonicalize(&binding)
|
||||
.with_context(|| format!("canonicalizing state-root binding {}", binding.display()))?;
|
||||
ensure!(
|
||||
canonical == binding,
|
||||
"state-root binding is indirect or non-canonical"
|
||||
);
|
||||
Ok(binding)
|
||||
}
|
||||
|
||||
fn ensure_direct_directory(path: &Path, label: &str) -> anyhow::Result<()> {
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
fs::create_dir(path)
|
||||
.with_context(|| format!("creating direct {label} {}", path.display()))?;
|
||||
}
|
||||
Err(error) => return Err(error).with_context(|| format!("inspecting {label}")),
|
||||
}
|
||||
let metadata = fs::symlink_metadata(path)
|
||||
.with_context(|| format!("inspecting {label} {}", path.display()))?;
|
||||
ensure!(
|
||||
metadata.is_dir() && !metadata.file_type().is_symlink(),
|
||||
"{label} is indirect or not a directory"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_admitted_state_layout(runtime_root: &Path) -> anyhow::Result<()> {
|
||||
let rebound = admitted_runtime_root(Some(runtime_root.to_owned()))?;
|
||||
ensure!(
|
||||
rebound == runtime_root,
|
||||
"state-root binding changed after process-write-lease admission"
|
||||
);
|
||||
let service_root = runtime_root.join("service");
|
||||
ensure_direct_directory(&service_root, "service state directory")?;
|
||||
ensure_direct_directory(&runtime_root.join("timelines"), "timelines directory")?;
|
||||
for path in [
|
||||
runtime_root.join("catalog.cc"),
|
||||
service_root.join("app-sessions-v2.cc"),
|
||||
] {
|
||||
require_direct_state_file_or_absent(&path)?;
|
||||
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Proves a timeline's stores direct before it is opened and returns its
|
||||
/// directory, created if absent.
|
||||
pub(crate) fn prepare_timeline_directory(
|
||||
runtime_root: &Path,
|
||||
directory_name: &str,
|
||||
) -> anyhow::Result<PathBuf> {
|
||||
let directory = runtime_root.join("timelines").join(directory_name);
|
||||
ensure_direct_directory(&directory, "timeline directory")?;
|
||||
for name in TIMELINE_STORES {
|
||||
let path = directory.join(name);
|
||||
require_direct_state_file_or_absent(&path)?;
|
||||
require_direct_state_file_or_absent(&sibling_state_lock_path(&path))?;
|
||||
}
|
||||
Ok(directory)
|
||||
}
|
||||
|
||||
fn require_direct_state_file_or_absent(path: &Path) -> anyhow::Result<()> {
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(metadata) => {
|
||||
ensure!(
|
||||
metadata.is_file() && !metadata.file_type().is_symlink(),
|
||||
"declared state path {} is indirect or not a regular file",
|
||||
path.display()
|
||||
);
|
||||
#[cfg(target_os = "linux")]
|
||||
ensure!(
|
||||
std::os::unix::fs::MetadataExt::nlink(&metadata) == 1,
|
||||
"declared state path {} is multiply linked",
|
||||
path.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(error) => {
|
||||
Err(error).with_context(|| format!("inspecting declared state path {}", path.display()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sibling_state_lock_path(path: &Path) -> PathBuf {
|
||||
let mut name = path
|
||||
.file_name()
|
||||
.map(|value| value.to_os_string())
|
||||
.unwrap_or_else(|| "state.cc".into());
|
||||
name.push(".lock");
|
||||
path.with_file_name(name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn managed_linux_runtime_requires_the_admitted_state_root_binding() {
|
||||
assert!(admitted_runtime_root(None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admitted_state_root_must_name_the_direct_canonical_directory() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = fs::canonicalize(directory.path()).unwrap();
|
||||
assert_eq!(admitted_runtime_root(Some(root.clone())).unwrap(), root);
|
||||
assert!(admitted_runtime_root(Some(directory.path().join("missing"))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_lease_state_layout_creates_only_the_direct_declared_directories() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = fs::canonicalize(directory.path()).unwrap();
|
||||
prepare_admitted_state_layout(&root).unwrap();
|
||||
for name in ["service", "timelines"] {
|
||||
let metadata = fs::symlink_metadata(root.join(name)).unwrap();
|
||||
assert!(metadata.is_dir());
|
||||
assert!(!metadata.file_type().is_symlink());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn post_lease_state_layout_rejects_symlinks_and_hardlinks() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let symlink_directory = tempfile::tempdir().unwrap();
|
||||
let symlink_root = fs::canonicalize(symlink_directory.path()).unwrap();
|
||||
let target = symlink_root.join("other.cc");
|
||||
fs::write(&target, b"not-catalog").unwrap();
|
||||
symlink(&target, symlink_root.join("catalog.cc")).unwrap();
|
||||
assert!(prepare_admitted_state_layout(&symlink_root).is_err());
|
||||
|
||||
let hardlink_directory = tempfile::tempdir().unwrap();
|
||||
let hardlink_root = fs::canonicalize(hardlink_directory.path()).unwrap();
|
||||
let target = hardlink_root.join("other.cc");
|
||||
fs::write(&target, b"not-catalog").unwrap();
|
||||
fs::hard_link(&target, hardlink_root.join("catalog.cc")).unwrap();
|
||||
assert!(prepare_admitted_state_layout(&hardlink_root).is_err());
|
||||
}
|
||||
|
||||
/// A timeline's own stores get the same proof as the service's, before the
|
||||
/// timeline is opened: a symlink standing in for its play-turn store is
|
||||
/// refused.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn a_symlinked_timeline_store_is_refused() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let root = fs::canonicalize(directory.path()).unwrap();
|
||||
prepare_admitted_state_layout(&root).unwrap();
|
||||
let name = "00000000-0000-4000-8000-000000000001";
|
||||
let timeline = prepare_timeline_directory(&root, name).unwrap();
|
||||
let target = root.join("other.cc");
|
||||
fs::write(&target, b"not-play-turn").unwrap();
|
||||
symlink(&target, timeline.join("play-turn-v1.cc")).unwrap();
|
||||
assert!(prepare_timeline_directory(&root, name).is_err());
|
||||
}
|
||||
}
|
||||
117
crates/ghostlight-dungeon/src/timelines.rs
Normal file
117
crates/ghostlight-dungeon/src/timelines.rs
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
//! Many timelines in one daemon.
|
||||
//!
|
||||
//! Each timeline is its own kernel store with its own mailbox, play table and
|
||||
//! controller work; every one shares the single routed inference port and the
|
||||
//! one concurrency pool. A timeline opens on first use and stays warm.
|
||||
|
||||
use crate::{
|
||||
catalog::timeline_directory_name,
|
||||
play::PlayTable,
|
||||
state_layout::prepare_timeline_directory,
|
||||
};
|
||||
use ghostlight::{
|
||||
ControllerModels, ControllerPort, ControllerRunner, InferencePort, PersonaLane, WorldMailbox,
|
||||
open_controller_work,
|
||||
};
|
||||
use anyhow::Context;
|
||||
use std::{collections::HashMap, path::PathBuf, sync::Arc};
|
||||
use tokio::sync::{Mutex, Semaphore, broadcast, mpsc};
|
||||
|
||||
/// What every timeline shares: the one inference port all lanes route through,
|
||||
/// the model each lane runs on, and the concurrency pool sized to the
|
||||
/// connector's quota.
|
||||
pub(crate) struct Shared {
|
||||
pub(crate) inference: Arc<dyn InferencePort>,
|
||||
pub(crate) models: ControllerModels,
|
||||
pub(crate) play_model: String,
|
||||
pub(crate) permits: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
/// One opened timeline.
|
||||
pub(crate) struct TimelineHost {
|
||||
pub(crate) world: WorldMailbox,
|
||||
pub(crate) controllers: ControllerRunner,
|
||||
pub(crate) play: Arc<PlayTable>,
|
||||
/// Pulsed whenever this timeline's turn changes; the stream wakes on it.
|
||||
pub(crate) changes: broadcast::Sender<()>,
|
||||
}
|
||||
|
||||
pub(crate) struct Timelines {
|
||||
root: PathBuf,
|
||||
shared: Shared,
|
||||
hosts: Mutex<HashMap<String, Arc<TimelineHost>>>,
|
||||
fatal: mpsc::UnboundedSender<String>,
|
||||
}
|
||||
|
||||
impl Timelines {
|
||||
pub(crate) fn new(root: PathBuf, shared: Shared, fatal: mpsc::UnboundedSender<String>) -> Self {
|
||||
Self {
|
||||
root,
|
||||
shared,
|
||||
hosts: Mutex::new(HashMap::new()),
|
||||
fatal,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn shared(&self) -> &Shared {
|
||||
&self.shared
|
||||
}
|
||||
|
||||
/// The host for `id`, opened on first use. Refuses an id that is not
|
||||
/// exactly `timeline:<canonical uuid>`.
|
||||
pub(crate) async fn host(&self, id: &str) -> anyhow::Result<Arc<TimelineHost>> {
|
||||
let name = timeline_directory_name(id).context("timeline id is not canonical")?;
|
||||
let mut hosts = self.hosts.lock().await;
|
||||
if let Some(host) = hosts.get(id) {
|
||||
return Ok(host.clone());
|
||||
}
|
||||
let directory = prepare_timeline_directory(&self.root, &name)?;
|
||||
let (world, owner) = WorldMailbox::open(directory.join("world.cc"))?;
|
||||
let fatal = self.fatal.clone();
|
||||
let label = id.to_owned();
|
||||
tokio::spawn(async move {
|
||||
let _ = owner.await;
|
||||
let _ = fatal.send(format!("world owner of {label} stopped while serving"));
|
||||
});
|
||||
let work = open_controller_work(directory.join("controller-work.cc"))?;
|
||||
let controllers = ControllerRunner::open(
|
||||
world.clone(),
|
||||
self.shared.inference.clone(),
|
||||
work,
|
||||
self.shared.models.clone(),
|
||||
)?;
|
||||
let personas = PersonaLane::new(
|
||||
ControllerPort::new(world.clone()),
|
||||
self.shared.inference.clone(),
|
||||
self.shared.models.projector.clone(),
|
||||
self.shared.models.persona.clone(),
|
||||
)?;
|
||||
let play = PlayTable::new(
|
||||
world.clone(),
|
||||
personas,
|
||||
self.shared.inference.clone(),
|
||||
self.shared.play_model.clone(),
|
||||
self.shared.permits.clone(),
|
||||
directory.join("play-turn-v1.cc"),
|
||||
)?;
|
||||
let (changes, _) = broadcast::channel(16);
|
||||
let host = Arc::new(TimelineHost {
|
||||
world,
|
||||
controllers,
|
||||
play: Arc::new(play),
|
||||
changes,
|
||||
});
|
||||
hosts.insert(id.to_owned(), host.clone());
|
||||
Ok(host)
|
||||
}
|
||||
|
||||
/// Every timeline opened so far; readiness probes these.
|
||||
pub(crate) async fn opened(&self) -> Vec<(String, Arc<TimelineHost>)> {
|
||||
self.hosts
|
||||
.lock()
|
||||
.await
|
||||
.iter()
|
||||
.map(|(id, host)| (id.clone(), host.clone()))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
27
crates/ghostlight-dungeon/tests/build_provenance.rs
Normal file
27
crates/ghostlight-dungeon/tests/build_provenance.rs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
use std::{fs, path::Path, process::Command};
|
||||
|
||||
#[test]
|
||||
fn embedded_commit_matches_checkout_head() {
|
||||
let repo_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let output = Command::new("git")
|
||||
.args(["rev-parse", "HEAD"])
|
||||
.current_dir(&repo_root)
|
||||
.output()
|
||||
.expect("git must be available for the provenance regression test");
|
||||
let checkout_head = if output.status.success() {
|
||||
String::from_utf8(output.stdout)
|
||||
.expect("git commit must be UTF-8")
|
||||
.trim()
|
||||
.to_owned()
|
||||
} else {
|
||||
fs::read_to_string(repo_root.join(".ghostlight-source-commit"))
|
||||
.expect("frozen source archive must carry its exact commit witness")
|
||||
.trim()
|
||||
.to_owned()
|
||||
};
|
||||
assert_eq!(
|
||||
env!("GHOSTLIGHT_BUILD_COMMIT"),
|
||||
checkout_head,
|
||||
"the binary embedded stale Git provenance"
|
||||
);
|
||||
}
|
||||
Loading…
Reference in a new issue